#136 jQuery
How do you use jQuery with Rails? In this episode I redo episode #43 using jQuery instead of Prototype/RJS.
- Download:
- source codeProject Files in Zip (111 KB)
- mp4Full Size H.264 Video (14.1 MB)
- m4vSmaller H.264 Video (9.72 MB)
- webmFull Size VP8 Video (25.1 MB)
- ogvFull Size Theora Video (19.4 MB)
Resources
- Episode #43: Ajax with RJS
- jQuery
- jRails
- Myth #3: Rails forces you to use Prototype
- The jSkinny on jQuery
- Full Episode Source Code
layouts/application.html.erb
<%= javascript_include_tag 'jquery', 'application' %>
<%= javascript_include_tag 'jquery', 'application' %>
public/javascripts/application.js
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})
jQuery.fn.submitWithAjax = function() {
this.submit(function() {
$.post(this.action, $(this).serialize(), null, "script");
return false;
})
return this;
};
$(document).ready(function() {
$("#new_review").submitWithAjax();
})
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})
jQuery.fn.submitWithAjax = function() {
this.submit(function() {
$.post(this.action, $(this).serialize(), null, "script");
return false;
})
return this;
};
$(document).ready(function() {
$("#new_review").submitWithAjax();
})
views/reviews/create.js.erb
$("#new_review").before('<div id="flash_notice"><%= escape_javascript(flash.delete(:notice)) %></div>');
$("#reviews_count").html("<%= pluralize(@review.product.reviews.count, 'Review') %>");
$("#reviews").append("<%= escape_javascript(render(:partial => @review)) %>");
$("#new_review")[0].reset();
$("#new_review").before('<div id="flash_notice"><%= escape_javascript(flash.delete(:notice)) %></div>');
$("#reviews_count").html("<%= pluralize(@review.product.reviews.count, 'Review') %>");
$("#reviews").append("<%= escape_javascript(render(:partial => @review)) %>");
$("#new_review")[0].reset();
ruby
def create
@review = Review.create!(params[:review])
flash[:notice] = "Thank you for reviewing this product"
respond_to do |format|
format.html { redirect_to @review.product }
format.js
end
end
def create @review = Review.create!(params[:review]) flash[:notice] = "Thank you for reviewing this product" respond_to do |format| format.html { redirect_to @review.product } format.js end end

