How To Submit AJAX Forms | JQuery

AJAX is simply Asynchronous XML or JSON. A great way to improve the user experience of your website is to validate and submit forms without a page refresh. You can use the $.post() method in combination with the serialize() method to submit a form using AJAX in jQuery.

Submit AJAX Forms


Submit a Form Without Page Refresh Using jQuery

You can submit a form by ajax using submit button and by mentioning the values of the following parameters.

  1. type: It is used to specify the type of request.
  2. url: It is used to specify the URL to send the request to.
  3. data: It is used to specify data to be sent to the server.
The $.ajax() function is used for ajax call using jQuery. Syntax:
$.ajax({name:value, name:value, ... })
Example: The form will use jQuery to process a form without a page refresh (using AJAX) and display a success message.
$("#idForm").submit(function(e) { e.preventDefault(); var form = $(this); var actionUrl = form.attr('action'); $.ajax({ type: "POST", url: actionUrl, data: form.serialize(), // serializes the form's elements. success: function(data) { alert(data); // show response. } }); });
  1. The jQuery post() method sends a request to the server and retrieves the data asynchronously.
  1. The serialize() method creates a URL encoded text string by serializing form values for submission. Only "successful controls" are serialized to the string.
  1. Using event.preventDefault() instead of return false is good practice as it allows the event to bubble up. This lets other scripts tie into the event, for example analytics scripts which may be monitoring user interactions.