Ruby on Rails: JavaScript May 5th, 2015

  • Sample CoffeeScript AJAX request…
    //This code fetches data from "/test", and then appends the result to the div with an id of results...
    $.ajax(url: "/test").done (html) ->
     $("#results").append html
  • Unobtrusive JavaScript is separating the script from the HTML markup
  • Built-in helper methods
    • form_for and form_tag … helps in writing forms
      // Remote submits the form via AJAX
      <%= form_for(@article, remote: true) do |f| %>
       ...
      <% end %>
      
      // JS ... tie into the success event
      $(document).ready ->
       $("#new_article").on("ajax:success", (e, data, status, xhr) ->
       $("#new_article").append xhr.responseText
       ).on "ajax:error", (e, xhr, status, error) ->
       $("#new_article").append "<p>ERROR</p>"
    • link_to … can use remote: true to use AJAX
    • button_to … can use remote: true to use AJAX
  • Sample AJAX in controller…
    # app/controllers/users_controller.rb
    # ......
    def create
     @user = User.new(params[:user])
     
     respond_to do |format|
       if @user.save
         format.html { redirect_to @user, notice: 'User was successfully created.' }
         format.js {}
         format.json { render json: @user, status: :created, location: @user }
       else
         format.html { render action: "new" }
         format.json { render json: @user.errors, status: :unprocessable_entity }
       end
     end
    end

Resources