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
});

Leave a Comment