Monday, October 22, 2012

jQuery Ajax POST Example

jQuery offers various ways in which ajax requests can be passed to the server, the ajax() method is the core method which provides all types of options to make Ajax requests. In this post we shall see on how to send a POST request using the jQuery ajax() method.

The syntax for sending a POST request using the ajax() method is as follows.

$.ajax({
    url: "",
    type: 'POST',
    data: {},     
    cache: <true/false>,
    dataType: "",
    success: function(result) {…});
    }
});
The following example sends a HTTP POST request to the server, processes the XML returned from the server page and displays the result in the browser.

.aspx Page (Client Side)
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>jQuery Ajax</title>
    <script type="text/javascript" src="JavaScript/jquery-1.7.2.js"></script>
    <script
        type="text/javascript"
        language="javascript">
        $(document).ready(function() {
            //
            //
            // Send HTTP Post Request
            $('#btnHttpPOSTRequest').click(function(event) {
                event.preventDefault();
                var nameList = "";
                $.ajax({
                    url: "AjaxData.aspx",
                    type: 'POST',
                    data: {ID: "2"},
                    cache: false,
                    dataType: "xml",
                    success: function(result) {
                        $(result).find("Name").each(function() {
                            nameList = nameList + $(this).text() + "
"
;
                        });
                        $("#divPOSTRequest").html(nameList);
                    }
                });
            });
        });
    </script>                 
</head>
<body>
    <form id="frmAjax" runat="server">
    <table border="1">
        <tr>
            <td><b>Action</b></td>
            <td><b>Response</b></td>
        </tr>
        <tr>
            <td>
                <asp:Button
                    ID="btnHttpPOSTRequest"
                    runat="server"
                    Text="HTTP POST Request" />
            </td>
            <td>
                <div id="divPOSTRequest"></div> 
            </td>
        </tr> 
    </table>
    </form>
</body>
</html>

.aspx.cs page (Server side)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;

namespace jQuery
{
    public partial class AjaxData : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if ((Request.Form != null)&&(Request.Form.Count > 0))
            {
                // Process HTTP POST Request
                string strFilterID = Request.Form["ID"].ToString();
                List<clsContacts> lstContacts = getContactByID(strFilterID);
                Response.Write(buildXML(lstContacts));
            }
            else
            {
                // Process HTTP GET Request
                string strFilterID = Request.QueryString["ID"].ToString();
                //
                List<clsContacts> lstContacts = getContactByID(strFilterID);
                Response.Write(buildXML(lstContacts));
            }
        }
        //
        private List<clsContacts> getContactByID(string filterKey)
        {
            List<clsContacts> lstContacts = new List<clsContacts>();
            lstContacts.Add(new clsContacts("1", "John", "34"));
            lstContacts.Add(new clsContacts("2", "David", "24"));
            //
            var filteredContacts = from c in lstContacts
                                   where c.ID.Equals(filterKey)
                                    select c;
            //
            return filteredContacts.ToList();
        }
        //
        private string buildXML(List<clsContacts> lstContacts)
        {
            XElement contactsXML = new XElement("Contacts");
            //
            foreach (clsContacts objContact in lstContacts)
            {
                contactsXML.Add(
                    new XElement("Contact",
                        new XElement("Name", objContact.Name),
                        new XElement("Age", objContact.Age)
                    )
                );
            }
            return contactsXML.ToString();
        }
    }
    //
    //
    public class clsContacts
    {
        public string _id;
        public string _name;
        public string _age;
        //
        public clsContacts(string strID, string strname, string strAge)
        {
            this._id = strID;
            this._name = strname;
            this._age = strAge;
        }
        //
        public string ID
        {
            get { return _id; }
            set { _id = value; }
        }
        //
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        //
        public string Age
        {
            get { return _age; }
            set { _age = value; }
        }
    }
}

Run the Application and click on the btnHttpPOSTRequest button, notice that the request is processed using HTTP POST and the result data is displayed in the browser.

Related Post
jquery ajax method
jquery ajax get example
jquery ajax post example
jquery ajax html response example
jquery ajax xml response example
jquery ajax json response example
jquery ajax text response example

Search Flipkart Products:
Flipkart.com

No comments: