How to Submit a Form Using Ajax

From WikiHTP

Create a simple form[edit]

Sometimes you may have a form and want to submit it using ajax.

Suppose you have this simple form -

<form id="ajax_form" action="form_action.php">
  <label for="name">Name :</label>
  <input name="name" id="name" type="text" />
  <label for="name">Email :</label>
  <input name="email" id="email" type="text" />
  <input type="submit" value="Submit" />
</form>

Call the form using Ajax[edit]

The following jQuery code can be used (within a $(document).ready call) -

$('#ajax_form').submit(function(event){
  event.preventDefault();
  var $form = $(this);

  $.ajax({
      type: 'POST',
      url: $form.attr('action'),
      data: $form.serialize(),
      success: function(data) {
        // Do something with the response
      },
      error: function(error) {
        // Do something with the error
      }
  });
});
  • var $form = $(this) - the form, cached for reuse
  • $('#ajax_form').submit(function(event){ - When the form with ID "ajax_form" is submitted run this function and pass the event as a parameter.
  • event.preventDefault(); - Prevent the form from submitting normally (Alternatively we can use return false after the ajax({}); statement, which will have the same effect)
  • url: $form.attr('action'), - Get the value of the form's "action" attribute and use it for the "url" property.
  • data: $form.serialize(), - Converts the inputs within the form into a string suitable for sending to the server. In this case it will return something like "name=Bob&email=bob@bobsemailaddress.com"

About This Tutorial

This page was last edited on 28 January 2019, at 21:24.