DotNetCurry Logo

Using jQuery to Submit a Form Using Ajax

Posted by: Suprotim Agarwal , on 3/20/2015, in Category jQuery and ASP.NET
Views: 34524
Abstract: Submit a form programmatically using jQuery Ajax. We will also filter empty form fields From submitting.

There are two different ways to submit a form programmatically. You can either use jQuery Ajax to submit the form asynchronously and use the response inside the current page OR you can use the normal form submission mechanism, which will load the response in a new browser window.

Most jQuery Ajax methods take care of serializing user input automatically in the background. However when you are manually sending data via Ajax, you will have to use the jQuery serialize() method. This method acts on a jQuery object and translates the matched DOM elements into a text string in standard URL-encoded notation. This string can then be passed along with an Ajax request.

 

The jQuery documentation mentions that only "successful controls" are serialized to the string. This excludes those elements that are disabled or radio buttons that have the same "name" attribute or controls that don’t have a name attribute. The Values of input type "radio" or "checkbox" are included only if they are checked. Data from Select element is not serialized unless specified in the serialize() method.

Let's see how to submit a form programmatically using jQuery Ajax. Create a new file ‘SubmitFormUsingAjax.html’. Write the following code:

$("#simpleform").on("submit", function (event) {
    var $this = $(this);
    var frmValues = $this.serialize();
    $.ajax({
        type: $this.attr('method'),
        url: $this.attr('action'),
        data: frmValues
    })
    .done(function () {
        $("#para").text("Serialized! Input String is " + frmValues);
    })
    .fail(function () {
        $("#para").text("An error occured");
    });
    event.preventDefault(); 
});

Let’s understand the code.

$("#simpleform").on("submit", function (event) { });

While submitting forms, it’s a good practice (for future code compatibility) to bind to the form submit event rather than a button click event.

var $this = $(this);
var frmValues = $this.serialize();

We are storing the form object in a variable so that it can be used later. The form data is placed into a variable by using the jQuery serialize() method. This method forms a key-value query string by taking all of the form input names, as well as their values. This string can then be parsed by the server-side script for further processing.

The final bits of code is to use $.ajax() to submit the form to the server.

$.ajax({
    type: $this.attr('method'),
    url: $this.attr('action'),
    data: frmValues
})
.done(function () {
    $("#para").text("Serialized! Input String is " + frmValues);
})
.fail(function () {
    $("#para").text("An error occured");
});

Here we are using the attributes like post method, url defined on the form element. So tomorrow if we decide to change it, we do not have to touch the JavaScript code as it will pick the update attributes automatically. In the done() function, for the sake of it, we are posting the serialized data in a paragraph.

Run the sample and enter some details as shown here:

ajax-submit

Click the Submit button and the serialized data will be passed to the server. Since the form is being posted in the background, you will not see the postback happening. However the output can be seen using FireBug as shown below.

s9-ajax-form

Live Demo

Filter Empty Form fields From Submitting

By default, all form fields that are successful controls get serialized. What if you wanted to prevent some fields from submitting? The answer lies in the serializeArray() method. The serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. In order to eliminate some fields, you have to iterate these objects and filter them as appropriate.

In this example, we will filter all those text fields which do not have any value in them. Create a new file ‘FilterFormFields.html’. The code remains exactly the same as we saw in our previous example. Only the following changes are needed:

$("#simpleform").on("submit", function (event) {
    ...
    var frmValues = $this.serializeArray()
                        .filter(function (elem) {
                            return $.trim(elem.value) != "";
                        });
    ...
});

As you can see, we are using filter() to reduce the set of matched elements to those elements that have some value in it.

Run the sample, enter a value in only the First Name field and hit Submit

s9-partial-form

The output can be seen using FireBug as shown below:

s9-partial-form-firebug

As you can see, only the fields which had some value were serialized and submitted.

serialize() vs serializeArray()?

As we saw, serializeArray() creates an array object, whereas serialize() creates a string (query string). serialize() is a convenient approach, but if you want a data structure that you want to operate on as we just saw, serializeArray() is the way to go.

Live Demo

If you liked this article, take a look at my new book The Absolutely Awesome jQuery Cookbook which contains scores of practical jQuery/jQueryUI recipes you can use in your projects right away.

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Mohammad on Saturday, March 21, 2015 3:56 AM
Thanks for the article
How would you send the textfield values to the backend?

Would it be possible for you to make some articles on how to send multiple drop down list, checkboxes and radio buttons values to the backend.