Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

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.

Solution 2:

You can do of course - you prevent your form from submitting as usual, you take its data and perform a POST via jQuery:

$(form).submit(function(event){

    // prevents default behaviour, i.e. reloading the page
    event.preventDefault();

    $.post(

        $(this).attr('action'), // the form's action
        $(this).serializeArray(),   // the form data serializedfunction(data)
        {

            // what you are supposed to do with POST response from server

        }

    )

});

Solution 3:

Post a Comment for "Intercept Form Post String And Send Via Ajax Instead"