JQuery Ajax form submit Example

JQuery Ajax form submit Example

Sending Ajax requests to server with JQuery library is pretty easy. We just need to include JQuery in your page after that we can use JQuery’s ajax API methods in the page.


Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

For better understanding ,i will create one HTML form and i will explain how to submit a HTML form asynchronously using jQuery AJAX API.

Here is my example form with 2 fields – name and email.

<form name="contact" id="contactForm" action="/process.php" method="POST">
  <div>
    <label for="name">Name</label>
    <input type="text" name="name" id="name"  placeholder="Enter your name"/>
  </div>
  <div>
      <label for="name">Email</label>
     <input type="text" name="email" id="email" placeholder="Enter your Email" />
  </div>
  <div><input type="submit" value="submit" name="submit" /></div>
</form>

we generally use jQuery.ajax() method for sending ajax requests, But we can also use $.post() method for sending post requests and $.get() method for making get requests.

As usually i used $.ajax() method in the below example, and i used $.serializeArray() method to serialize form data instead of this you can also use $.serialize() method.Both methods works similar way.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
    //callback handler for form submit
    $("#contactForm").submit(function(e) {
        // prevent default submit behaviour
        e.preventDefault();
        // serialize total form data
        var postData = $(this).serializeArray();
 
        // get form action url
        var formActionURL = $(this).attr("action");
        $("#submit").val('please wait...');
        // JQuery ajax method , for post we can directly use $.post({}); this is shortcut method for sending post request
        $.ajax({
            url: formActionURL,
            type: "POST",
            data: postData,
         }).done(function(data) {
            alert("success");
         }).fail(function() {
            alert("error");
         }).always(function() {
            

Share This Blog

Comment

Do you want to get our quality service for your business?