Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept form POST string and send via AJAX instead

Is it possible to intercept a form's POST string and send it via AJAX instead? I could use $('form').submit() to intercept the POST event, but I don't see where I can get the POST string from. I could reproduce the string from the form's inputs, but this seems dubious.

like image 233
datadamnation Avatar asked Aug 30 '12 01:08

datadamnation


People also ask

What is the difference between AJAX and form submit?

A standard form submit sends a new HTTP request (POST or GET) and loads the new page in the browser. In Ajax, the data is sent to the server (POST or GET) in the background, without affecting the page at all, and the response is then received by javascript in the background, again without affecting the page at all.

How Stop form submit in AJAX?

You'll need to stop it BEFORE the success handler. Because the function finishes executing after your AJAX call the form will submit while your ajax call is occurring (and by the time your ajax call finishes it is too late). But yes, put return false at the end of your function.


1 Answers

// capture submit
$('form').submit(function() {
     var $theForm = $(this);

     // send xhr request
     $.ajax({
         type: $theForm.attr('method'),
         url: $theForm.attr('action'),
         data: $theForm.serialize(),
         success: function(data) {
             console.log('Yay! Form sent.');
         }
     });

     // prevent submitting again
     return false;
});

Note that as Phil stated in his comment that .serialize() doesn't include the submit button. If you also need to value of the submit buton you would have to add it manually.

like image 151
PeeHaa Avatar answered Sep 23 '22 03:09

PeeHaa