Submit form in rails 3 in an ajax way (with jQuery) Submit form in rails 3 in an ajax way (with jQuery) ajax ajax

Submit form in rails 3 in an ajax way (with jQuery)


You want to:

  1. Stop the normal behaviour of submit.
  2. Send it through ajax to the server.
  3. Get a reply back and change things accordingly.

The code below should do that:

$('form').submit(function() {      var valuesToSubmit = $(this).serialize();    $.ajax({        type: "POST",        url: $(this).attr('action'), //sumbits it to the given url of the form        data: valuesToSubmit,        dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard    }).success(function(json){        console.log("success", json);    });    return false; // prevents normal behaviour});


If you use :remote => true on your forms, you can submit them with JavaScript with

$('form#myForm').trigger('submit.rails');


The preferred way in Rails 3 to do ajax form submission is to utilize Rails-ujs.

Basically you allow Rails-ujs to do the ajax submit for you (and you won't need to write any js code). Then you just write js code to capture the response event (or other events) and do your thing.

Here are some code:

First, use the remote option in form_for so form will submit via ajax by default:

form_for :users, remote:true do |f|

Then when you want to do some action based on ajax response status (e.g. successful response), write the javscript logic like this:

$('#your_form').on('ajax:success', function(event, data, status, xhr) {  // Do your thing, data will be the response});

There are several events which you can hook to.