Monday, October 22, 2012

jQuery Ajax JSON Response Example

jQuery supports different types of responses data types which are sent by the server as a result of processing Ajax request, the various types of data supported are HTML, XML, JSON and Text. In this post we shall see on how to process JSON data returned from the server using jQuery.
The syntax for receiving and processing JSON response is as follows.

    url: "AjaxData.json",
    cache: true,
    dataType: "json",
    success: function(result) {…}

The following example receives a JSON format data from the server and displays the data in a DIV tag in the browser.

.aspx Page (Client Side)
<html xmlns="" >
<head runat="server">
    <title>jQuery Ajax</title>
    <script type="text/javascript" src="JavaScript/jquery-1.7.2.js"></script>
        $(document).ready(function() {
            // Get JSON Response data from the Server
            $('#btnGetJSON').click(function(event) {
                var jsonContent = "";
                    url: "AjaxData.json",
                    cache: false,
                    dataType: "json",
                    success: function(result) {
                        for (var x = 0; x < result.length; x++) {
                            jsonContent += result[x].Name;
                            jsonContent += "-";
                            jsonContent += result[x].Age;
                            jsonContent += "";                        }
    <form id="frmAjax" runat="server">
    <table border="1">
                    Text="Get JSON"/>
                <div id="divJSON"></div> 

AjaxData.json (Server side)
[{"Name": "John", "Age": "34"}, {"Name": "David", "Age":"24"}]

Run the Application and click on the btnGetJSON button, notice that the request is processed and the JSON data sent by the server is parsed and displayed in the Browser.

Search Flipkart Products: