Skip to content

Instantly share code, notes, and snippets.

@dvayns2
Last active August 29, 2015 14:17
Show Gist options
  • Save dvayns2/1aafea3c1fb819ac31e5 to your computer and use it in GitHub Desktop.
Save dvayns2/1aafea3c1fb819ac31e5 to your computer and use it in GitHub Desktop.
Sinatra Jquery request example from AJAXify Hacker News
Controller action
post '/posts' do
post = Post.create( title: params[:title],
username: Faker::Internet.user_name,
comment_count: rand(1000) )
if post
status 200
erb :_post_fields, locals: {post: post}, layout: false
else
status 500
end
end
JQUERY action
$('form').on('submit', function(e) {
e.preventDefault();
var title = $(this)
$.ajax({
'url': title.attr('action'),
'method': title.attr('method'),
'data': title.serialize(),
'success': function(response) {
console.log(response)
$('.post-container').append(response)
title[0].reset()
},
});
})
Rails handles ajax/javascript/jquery in a way that allows for the concept of unobtrusive javascript.
Unobtrusive JavaScript is a best practice methodology for attaching JavaScript to the front-end of a website.
It allows for maintenance and updating functionality to be substantially easier.
BAD:
<input type="button" id="btn" onclick="alert('Test')" /> Here we have HTML and JS mixed in together.
GOOD:
<input type="button" id="btn" />
var el = document.getElementById('btn');
el.onclick = function(){
alert('Test');
};
Unobtrusive javascript assumes everything works and we are just layering on what already works.
Best way is to allow our server to recognize the possibility of an ajax call... Rails magic!
πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘πŸ‘οΏ½
<li>
<%= post.title %>
<%=button_to "Delete Post", post, :method => delete, :remote => true %>
</li>
In our view we can render a form with a remote true and this allows the form to be submitted by Ajax
rather than by the browser refresh cycle. Essentially, remote true signifies that we will
be able to use ajax here.
For example, if you have a button with a delete and set it to remote true it will hook into the controller
and delete it, but you will
not be able to see it without refreshing the page.
def destroy
post.destroy
respond_to do |format|
format.js do
render nothing: true
end
format.any do
redirect_to posts_path
end
end
$(function() {
$("form[data-remote-true]").on("ajax:success", function(e){
var listItem = $(e.target).closest('li')
listItem.remove();
})
})
Recommendations: watch Mike talk on devtalks -> search for Rails AJAX and checkout jquery_ujs
(shortcuts for making ajax requests)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment