Ajax Form Submit examples using jQuery

Ajax forms are the integral part of web technology today. It makes sending HTTP requests very easy, no page reloads and it’s fast, it can send-receive information in a various formats such as HTML, JSON or XML. Let’s learn various ways to send HTML form data using jQuery Ajax.

Browser Support

11+ 29+ 46+ 9.1+ 38+

Simple HTML Form Submit

jQuery has various shorthand Methods to jQuery.ajax(), such as .get(), .post(), .load(), .getJSON(), they all accomplish the same thing, but are more specific to the tasks and require less code.

Lets start off with a simple HTML form, and then we can write jQuery codes for it that perform Ajax requests:

1
2
3
4
5
6
7
8
9
10
<form action="path/to/server/script" method="post" id="my_form">
    <label>Name</label>
    <input type="text" name="name" />
    <label>Email</label>
    <input type="email" name="email" />
    <label>Website</label>
    <input type="url" name="website" />
    <input type="submit" name="submit" value="Submit Form" />
<div id="server-results"><!-- For server results --></div>
</form>

The jQuery snippets below demonstrates ways to submit HTML form.

Submit HTML Form data using regular jQuery ajax() function. It is very flexible and can be configured to the heart content.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$("#my_form").submit(function(event){
    event.preventDefault(); //prevent default action
    var post_url = $(this).attr("action"); //get form action url
    var request_method = $(this).attr("method"); //get form GET/POST method
    var form_data = $(this).serialize(); //Encode form elements for submission
   
    $.ajax({
        url : post_url,
        type: request_method,
        data : form_data
    }).done(function(response){ //
        $("#server-results").html(response);
    });
});
jQuery post() is a shorthand function of ajax().

1
2
3
4
5
6
7
8
9
$("#my_form").submit(function(event){
    event.preventDefault(); //prevent default action
    var post_url = $(this).attr("action"); //get form action url
    var form_data = $(this).serialize(); //Encode form elements for submission
   
    $.post( post_url, form_data, function( response ) {
      $("#server-results").html( response );
    });
});
jQuery get() same as post(), but uses HTTP GET request.

1
2
3
4
5
6
7
8
9
$("#my_form").submit(function(event){
    event.preventDefault(); //prevent default action
    var post_url = $(this).attr("action"); //get form action url
    var form_data = $(this).serialize(); //Encode form elements for submission
   
    $.get( post_url, form_data, function( response ) {
      $("#server-results").html( response );
    });
});
getJSON() also uses HTTP GET like get(), but loads JSON-encoded data from the server.

1
2
3
4
5
6
7
8
9
10
11
12
$("#my_form").submit(function(event){
    event.preventDefault(); //prevent default action
    var post_url = $(this).attr("action"); //get form action url
    var form_data = $(this).serialize(); //Encode form elements for submission
   
    $.getJSON( post_url , form_data,function( response ) {
        //iterate json response
        $.each( response, function(key, val) {
            $("#server-results").append( val + "<br />"); //append results to element
        });
    });
});

The .serialize() method serializes a form inputs to query string that could be sent using Ajax.

HTML Multipart/form-data Form Submit

To upload files to the server, we can use FormData interface available to XMLHttpRequest2, which constructs a FormData object and can be sent to server easily using the jQuery Ajax. Old browsers (eg: IE9) doesn’t support FormData, check caniuse.com for more info.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$("#my_form").submit(function(event){
    event.preventDefault(); //prevent default action
    var post_url = $(this).attr("action"); //get form action url
    var request_method = $(this).attr("method"); //get form GET/POST method
    var form_data = new FormData(this); //Creates new FormData object
    $.ajax({
        url : post_url,
        type: request_method,
        data : form_data,
        contentType: false,
        cache: false,
        processData:false
    }).done(function(response){ //
        $("#server-results").html(response);
    });
});
1
2
3
4
5
6
7
8
9
10
11
<form action="path/to/server/script" method="post" id="my_form">
    <label>Name</label>
    <input type="text" name="name" />
    <label>Email</label>
    <input type="email" name="email" />
    <label>Website</label>
    <input type="url" name="website" />
    <input type="file" name="my_file[]" /> <!-- File Field Added -->
    <input type="submit" name="submit" value="Submit Form" />
<div id="server-results"><!-- For server results --></div>
</form>

That’s all the code we need to upload files using jQuery Ajax. The contentType is set to false otherwise default is set “application/x-www-form-urlencoded”, which is no good for uploading files, setting it false will post data as “multipart/form-data”.

Another important thing here is processData, which must also be set to false, otherwise jQuery will try to serialize the FormData object into query string, and you might end up with an Illegal invocation error.

Submit Ajax Form with a Progress Bar

While posting data to server, we can notify user about the progress happening in the background. For that we use xhr callback function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
$("#my_form").submit(function(event){
    event.preventDefault(); //prevent default action
    var post_url = $(this).attr("action"); //get form action url
    var request_method = $(this).attr("method"); //get form GET/POST method
    var form_data = new FormData(this); //Encode form elements for submission
   
    $.ajax({
        url : post_url,
        type: request_method,
        data : form_data,
        contentType: false,
        processData:false,
        xhr: function(){
        //upload Progress
        var xhr = $.ajaxSettings.xhr();
        if (xhr.upload) {
            xhr.upload.addEventListener('progress', function(event) {
                var percent = 0;
                var position = event.loaded || event.position;
                var total = event.total;
                if (event.lengthComputable) {
                    percent = Math.ceil(position / total * 100);
                }
                //update progressbar
                $("#upload-progress .progress-bar").css("width", + percent +"%");
            }, true);
        }
        return xhr;
    }
    }).done(function(response){ //
        $("#server-results").html(response);
    });
});
1
2
3
4
5
6
7
8
9
10
11
12
<form action="path/to/server/script" method="post" id="my_form">
    <label>Name</label>
    <input type="text" name="name" />
    <label>Email</label>
    <input type="email" name="email" />
    <label>Website</label>
    <input type="url" name="website" />
    <input type="file" name="my_file[]" /> <!-- File Field Added -->
    <input type="submit" name="submit" value="Submit Form" />
<div id="server-results"><!-- For server results --></div>
</form>
<div id="upload-progress"><div class="progress-bar"></div></div> <!-- Progress bar added -->
1
2
3
4
5
6
7
8
9
10
11
/*Progress Bar*/
#upload-progress{
    height: 20px;
    border: 1px solid #ddd;
    width: 100%;
}
#upload-progress .progress-bar{
    background: #bde1ff;
    width: 0;
    height: 20px;
}

That’s it, I hope it has provided some insight into jQuery Ajax Form Submit, and will surely come in handy in your future projects. Please do share your feedbacks which will help improve this article further.

8 Comments Add Comment