Serialize only Selected Elements of a Form and Submit it using jQuery

Posted by: Suprotim Agarwal , on 1/11/2010, in Category jQuery and ASP.NET
Views: 44527
Abstract: This article will demonstrate how to submit form data in the background without using ASP.NET AJAX and at the same time prevent some form fields from being submitted.
Serialize only Selected Elements of a Form and Submit it using jQuery
 
This article will demonstrate how to submit form data in the background without using ASP.NET AJAX and at the same time prevent some form fields from being submitted.
This article is a sample chapter from my EBook called 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls. The chapter has been modified a little to publish it as an article.
Note that for demonstration purposes, I have included jQuery and CSS code in the same page. Ideally, these resources should be created in separate folders for maintainability.
Let us quickly jump to the solution and see how to submit form data in the background using jQuery
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Serialize Form Data</title>
    <script type='text/javascript'
        src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js'>
    </script>
 
    <script type="text/javascript">
        $(function() {
            $('input[id$=btnSubmit]').click(function(e) {
                e.preventDefault();
                var params = $('form[id$=form1]').serializeArray();
                $.post("R51a-ReadValues.aspx",
                   $(params).filter(function() {
                       return !({ "txtLName": 1, "__VIEWSTATE": 1, "__EVENTVALIDATION": 1 })[this.name];
                   }),
                   function(data) {
                       //do something
                   },
                   "json"
               );
                alert('Form data submitted in the background');
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div class="tableDiv">
        <h2>Enter data and click on 'Serialize and Submit' button
        to send form data to a different page without a postback</h2>
        <br /><br />
        <asp:Label ID="lblFName" runat="server"
            Text="FirstName: "></asp:Label>
        <asp:TextBox ID="txtFName" runat="server">
            </asp:TextBox><br />
        <asp:Label ID="lblMName" runat="server"
            Text="MidName: "></asp:Label>
        <asp:TextBox ID="txtMName" runat="server">
            </asp:TextBox><br />  
        <asp:Label ID="lblLName" runat="server"
            Text="LastName: "></asp:Label>
        <asp:TextBox ID="txtLName" runat="server">
            </asp:TextBox><br />          
        <asp:Button ID="btnSubmit" runat="server"
            Text="Serialize and Submit" />
    </div>
    </form>
</body>
</html>
 
$.post() is a very useful method for sending a simple POST request to the server using AJAX. The signature of $.post() is as follows:
$.post( url, [data], [callback], [type] )
where url is the URL where the request is sent, [data] is the data sent with the request, [callback] is a function to execute when the request is complete and [type] is the format in which content has been returned (xml, json)
So a simple piece of code like the one shown below can send the form data to another page using AJAX.
$.post("R51a-ReadValues.aspx", $('form[id$=form1]').serialize());
Now what if you want to prevent some fields from being submitted to the server? So apart from the form fields, there is the ViewState and EventValidation that also gets posted to the server. Let us save some bandwidth by exploring how to prevent these fields as well as some other Form fields too for demonstration purposes (like the lastname) from being posted to the server. Observe this piece of code:
var params = $('form[id$=form1]').serializeArray();
                $.post("R51a-ReadValues.aspx",
                   $(params).filter(function() {
                       return !({ "txtLName": 1, "__VIEWSTATE": 1, "__EVENTVALIDATION": 1 })[this.name];
                   }),
                   function(data) {
                       //do something
                   },
                   "json"
               );
In the code above, we use serializeArray() to serialize all forms and form elements. A JSON structure is returned which is stored in the variable ‘params’. When you use $.post() to submit the form fields, we use the filter() function to filter out the txtLName, __VIEWSTATE and __EVENTVALIDATION fields. Imagine the performance increase when we are able to reduce the data posted. Now when you run the application, enter data in the text fields and submit data, you will see that only two fields are posted – txtFName and txtNName. 
Note: 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.
Firebug_Output
I hope you found this article useful and I thank you for viewing it. This article was taken from my EBook called 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls which contains similar recipes that you can use in your applications.
If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email
Give me a +1 if you think it was a good article. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Pradeep Gaur on Tuesday, January 12, 2010 3:46 AM
Hey it's so nice and useful code
Comment posted by Arnis Thivent on Tuesday, January 12, 2010 6:32 AM
Excellent post!
Comment posted by David on Wednesday, January 13, 2010 4:25 PM
OK thats cool.
Do you have a method to parse the submitted values from the asp.net side if for example to the params did not originate from said asp page?
For example fields add to the form via some javascript?
Comment posted by farrukh hameed on Tuesday, January 26, 2010 2:30 AM
nice article
Comment posted by pradeep gaur on Tuesday, February 22, 2011 11:59 PM

nice code !

http://pradeepgaur.weebly.com/
Comment posted by uyuyu on Thursday, February 14, 2013 12:35 AM
hhgfhgfhgfhfghhfhfghfhfg
Comment posted by Custodi Estensi on Thursday, June 13, 2013 4:19 PM
I think this is a very good solution for less postback.

http://www.custodiestensi.it

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel