Click here to Skip to main content
Click here to Skip to main content

A Working Example of Five Different Ways to Make jQuery AJAX Calls

, 2 Feb 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
This article introduces a working example of five different ways to make AJAX calls using jQuery.

Introduction

This article introduces a working example of five different ways to make AJAX calls using jQuery.

Background

This is intended to be a short article to introduce a working example of five different ways to make AJAX calls using jQuery.

I have been developing applications running on web browsers for many years, and I realize that AJAX and jQuery are getting close to the ultimate dreams of any programmer who has been working on this subject for some time. Recently, I noticed a great article by Piao Yishi, "5 Ways to Make AJAX Calls with jQuery". My article is a working example of the five ways described in Piao's article, and you are strongly recommended to read Piao's article, if you are interested in my article.

jQuery is a client-side scripting library, so it is totally independent from the development environment, regardless of whether it is ASP.NET, J2EE, PHP, or any other platform. Visual Studio is readily available to me, so the example is created as an ASP.NET project. Borrowed from Piao's article, the five methods demonstrated in this article are the following:

Five Methods

jQuery AJAX calls are very powerful and flexible. The code in this article is to demonstrate only one aspect of jQuery features, that is retrieving an HTML fragment and inserting it into the content of the main ASP.NET page using the above five methods. I may write other articles to talk about processing the XML and JSON content at the client and server sides though, if I have time later.

The example code is developed in Visual Studio 2008 and using jQuery 1.4. I did not test it on other versions, but I do not feel that versions make any difference for the five AJAX methods that we are going to talk about.

The HTML Fragment for jQuery Calls to Retrieve

I am going to talk about five jQuery methods to retrieve a list of sample student information represented by an HTML fragment. The HTML fragment is an HTML table. All the jQuery calls in this article will get this HTML table and insert it into the calling ASP.NET page. At the server, the information in the student record list is represented by the class "StudentRecords", as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
 
namespace jQueryFiveAjaxCalls.StudentRecordArchive
{
    public class StudentRecords : DataTable
    {
        public StudentRecords(int NoOfRecordsToRetrieve): base()
        {
            Columns.Add("ID", System.Type.GetType("System.Int32"));
            Columns.Add("Name", System.Type.GetType("System.String"));
            Columns.Add("Score", System.Type.GetType("System.Int32"));
            Columns.Add("Comment", System.Type.GetType("System.String"));
            Columns.Add("Evaluation Time", System.Type.GetType("System.DateTime"));
 
            Random rd = new Random();
            for (int Idex = 1; Idex <= NoOfRecordsToRetrieve; Idex++)
            {
                string Name = "Student Name No." + Idex.ToString();
                int Score = System.Convert.ToInt16(60 + rd.NextDouble() * 40);
                string Comment = "Comment on " + Name + " is extremely bad";
                if (Score < 80)
                {
                    Comment = "Comment on " + Name + " is very good by the teacher";
                }
 
                DataRow row = Rows.Add();
                row["ID"] = Idex;
                row["Name"] = Name;
                row["Score"] = Score;
                row["Comment"] = Comment;
                row["Evaluation Time"] = System.DateTime.Now;
            }
        }
    }
}

This class represents an ADO.NET DataTable. By creating an instance of this class and passing an integer indicating the number of student records to the constructor, we can obtain a DataTable filled with randomly generated sample student record information.

The HTML fragment is generated by the ASP.NET file "StudentRecordsHTMLFragment.aspx" using StudentRecords of type DataTable. A normal ASP.NET page will have all the HTML tags, such as "<html>" and "<body>", etc. In order to obtain a clean HTML fragment which has only an HTML "<table>", I will have to modify the default ASP.NET page generation process. The following is the code-behind file for "StudentRecordsHTMLFragment.aspx":

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
 
namespace jQueryFiveAjaxCalls.StudentRecordArchive
{
    public partial class StudentRecordsHTMLFragment : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            String ReturnJson = Request.QueryString["RETURNJSON"];
            String NoOfRecordsToRetrieve = Request.QueryString["NRECORD"];
 
            if (NoOfRecordsToRetrieve == null)
            {
                NoOfRecordsToRetrieve = Request.Form["NRECORD"];
            }
 
            StudentRecords Records = 
              new StudentRecords(System.Convert.ToInt16(NoOfRecordsToRetrieve));
 
            DataGrid DG = new DataGrid();
            DG.CellPadding = 14;
            DG.Style.Add("font-size", "10px");
            DG.HeaderStyle.BackColor = System.Drawing.Color.Brown;
            DG.HeaderStyle.ForeColor = System.Drawing.Color.White;
            DG.HeaderStyle.Font.Bold = true;
 
            DG.Attributes.Add("bordercolor", "black");
            DG.DataSource = Records;
            DG.DataBind();
 
            StringBuilder SB = new StringBuilder();
            HtmlTextWriter TW = 
              new HtmlTextWriter(new System.IO.StringWriter(SB));
            DG.RenderControl(TW);
 
            string ContentType = "text/html";
            string Content = SB.ToString();
            if (ReturnJson == "True")
            {
                ContentType = "text/x-json";
                StringBuilder JsonSB = new StringBuilder();
                JsonSB.Append("{\"TB\": \"");
                JsonSB.Append(SB.Replace("\"", "'").Replace(
                  "\t", "").Replace("\r", "").Replace("\n", ""));
                JsonSB.Append("\"}");
                Content = JsonSB.ToString();
            }
 
            Response.ContentType = ContentType;
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            Response.OutputStream.Write(encoding.GetBytes(Content), 0, 
                                        Content.Length);
        }
    }
}

In the code above, we first obtain the two parameters from the callers, which will be the jQuery methods in this article. The two parameters to obtain are:

  • "RETURNJSON", indicating if the HTML table will be returned in a JSON object
  • "NRECORD", indicating the number of student records to be included in the HTML table

You may notice that NRECORD is retrieved by both Request.QueryString() and Request.Form(). This is because some jQuery calls use the GET method, while others use the POST method. To make sure that StudentRecordsHTMLFragment.aspx always knows how many student records to include in the HTML fragment, both Request.QueryString() and Request.Form() are used. When the code knows how many student records are needed, it initiates a StudentRecords object and binds it to an ASP.NET DataGrid object. From the DataGrid object, we can obtain the HTML string for the HTML table and pass the text string back to the caller. When the caller wants a simple HTML fragment, the code returns the caller with content type "text/html". If the caller wants a JSON object, a JSON object is returned after some processing of the data.

The Main ASP.NET File "Default.aspx"

Now, let us take a look at the "Default.aspx" file. Since jQuery is a client-side scripting library, the commonly used ASP.NET specific features are no longer useful in this article, so I disabled the view state, and removed the ASP.NET web form, so Default.aspx is never "posted back".

<%@ Page Language="C#" AutoEventWireup="true" 
    EnableViewState="false" CodeBehind="Default.aspx.cs" 
    Inherits="jQueryFiveAjaxCalls.Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Demo Code for 5 Ajax Calls Using jQuery</title>
    <link rel="SHORTCUT ICON" href="Images/icon_tong.ico" />
    <link href="Styles/AppStyles.css" rel="stylesheet" type="text/css" />
    <script src="JS/jquery-1.4.1.min.js" type="text/javascript"></script>
 
<script language="javascript" type="text/javascript">
    $(document).ready(function() {
        var $target = $("#MainContent");
        var $resource = 
          "StudentRecordArchive/StudentRecordsHTMLFragment.aspx";
        var $jsresource = "JS/ExampleScript.js";
        var $information = $("#lblInformation");
        var $informationDefaultTextNotSelected =
            "Please select the number of records to retrieve " + 
            "and click on one of the links above ...";
        var $informationDefaultTextSelected =
            "Please click on one of the links above ...";
        var $ajax_load = "<img src='Images/ajax-loader.gif' alt='Loading ...'/>";
 
        $.ajaxSetup({ cache: false });
 
        $("#selNoOfStudentRecords").change(function() {
            $target.html("");
            if ($('#selNoOfStudentRecords').val() == "*") {
                $(":button").attr("disabled", true);
                $(":button").removeClass("ButtonStyle");
                $(":button").addClass("ButtonDisabled");
                $information.html($informationDefaultTextNotSelected);
                
            } else {
                $(":button").attr("disabled", false);
                $(":button").removeClass("ButtonDisabled");
                $(":button").addClass("ButtonStyle");
                $information.html($informationDefaultTextSelected);
            }
        }).change();
 
        $("a").hover(function() {
            this.style.color = "red";
        }, function() {
            this.style.color = "";
        });
 
        $("#btnClear").click(function(e) {
            e.preventDefault();
 
            $target.html("");
            $information.html($informationDefaultTextSelected);
        });
 
        $("#btnUseLoad").click(function(e) {
            e.preventDefault();
 
            var $nRecord = $('#selNoOfStudentRecords').val();
            $target.html($ajax_load).load($resource, { NRECORD: $nRecord });
            $information.html("Information retrieved by load method ...");
        });
 
        $("#btnUseGet").click(function(e) {
            e.preventDefault();
 
            var $nRecord = $('#selNoOfStudentRecords').val();
            $target.html($ajax_load);
            $.get($resource, { NRECORD: $nRecord }, function($x) {
                $target.html($x);
                $information.html("Information retrieved by get method ...");
            });
        });
 
        $("#btnUsePost").click(function(e) {
            e.preventDefault();
 
            var $nRecord = $('#selNoOfStudentRecords').val();
            $target.html($ajax_load);
            $.post($resource, { NRECORD: $nRecord }, function($x) {
                $target.html($x);
                $information.html("Information retrieved by post method ...");
            });
        });
 
        $("#btnUseGetJSON").click(function(e) {
            e.preventDefault();
 
            var $nRecord = $('#selNoOfStudentRecords').val();
            $target.html($ajax_load);
 
            $.getJSON($resource, { NRECORD: $nRecord, RETURNJSON: "True" }, function($x) {
                $target.html($x.TB);
                $information.html("Information retrieved by getJSON method ...");
            });
        });
 
        $("#btnUseGetScript").click(function(e) {
            e.preventDefault();
 
            var $nRecord = $('#selNoOfStudentRecords').val();
            $target.html($ajax_load);
            $.getScript($jsresource, function() {
                $.loadStudentHtmlFragment($target, $resource, { NRECORD: $nRecord });
                $information.html("Information retrieved by " + 
                                  "getScript method and run this script ...");
            });
        });
 
    });
    
</script>
</head>
 
<body>
<div>
<div class="AppTitle">A Working Example of the Five Ways to Make jQuery Ajax Calls</div>
<div class="AuthorTitle"><asp:Label 
   ID="lblAuthorInformation" runat="server"></asp:Label></div>
 
<div>
<table style="width: 100%" cellpadding="0px" cellspacing="0px">
    <tr>
        <td style="white-space: nowrap" align="left">
            <span>
                <span>
                    <input type="button" id="btnUseLoad" 
                        class="ButtonStyle" value="Call by load (...)" />
                </span>
                <span>
                    <input type="button" id="btnUseGet" 
                        class="ButtonStyle" value="Call by get (...)" />
                </span>
                <span>
                    <input type="button" id="btnUsePost" 
                        class="ButtonStyle" value="Call by post (...)" />
                </span>
                <span>
                    <input type="button" id="btnUseGetJSON" 
                        class="ButtonStyle" value="Call by getJSON (...)" />
                </span>
                <span>
                    <input type="button" id="btnUseGetScript" 
                        class="ButtonStyle" value="Call by getScript (...)" />
                </span>
                <span>
                    <input type="button" id="btnClear" 
                        class="ButtonStyle" value="Clear" />
                </span>
            </span>
        </td>
        <td>   </td>
        <td style="white-space: nowrap">
            <span style="float: right">
                <span>
                    <span>Select the number of records to retrieve  </span>
                    <span>
                        <select id="selNoOfStudentRecords" class="SmallText">
                            <option value="*">** Please select **</option>
                            <option value="5">5</option>
                            <option value="10">10</option>
                            <option value="20">20</option>
                            <option value="50">50</option>
                        </select>
                    </span>
                </span>
            </span>
        </td>
    </tr>
</table>
</div>
 
<div class="Information"><label id="lblInformation"></label></div>
<div id="MainContent" class="MainContent" 
  style="width: 100%; float: left; text-align: left"></div>
</div>
<div class="Copyright">Copy right: The Code Project Open License (CPOL)</div>
</body>
</html>

In the HTML section of Default.aspx, you can see that we only have a few functional visual components:

  1. Five buttons, each triggers a jQuery call using one of the AJAX methods
  2. A selection box, where the number of student records is selected from
  3. A "div" with id "MainContent"; this is the place where the HTML fragment is inserted into "Default.aspx"

The use of most of the AJAX call methods is pretty straightforward in this article, except "$.getScript()" and "$.getJSON()". It is because the two methods are actually not designed to load HTML fragments. To demonstrate how to use them in this article, I let them load the HTML fragment anyway, so I will need to give them some detailed explanation.

jQuery Methods "$.getScript()" and "$getJSON()"

The jQuery method "$.getScript()" is designed to load some JavaScript from the server in an AJAX fashion. In this article, the script being loaded is the following:

$.loadStudentHtmlFragment = function($target, $url, $data) {
    $target.load($url, $data);
}

This JavaScript snippet is a simple function "$.loadStudentHtmlFragment()" that uses the jQuery load() method to load the HTML fragment and insert it in to Default.aspx. If you read the code more closely, you will notice that $target references the div object with ID MainContent. The $.getScript() method is used in Default.aspx like the following:

$("#btnUseGetScript").click(function(e) {
 e.preventDefault();
 
 var $nRecord = $('#selNoOfStudentRecords').val();
 $target.html($ajax_load);
 $.getScript($jsresource, function() {
                $.loadStudentHtmlFragment($target, 
                        $resource, { NRECORD: $nRecord });
                $information.html("Information retrieved " + 
                  "by getScript method and run this script ...");
 });
});

When the button to trigger the call to $.getScript() is clicked, the $.getScript() method is first called to load the script file which contains the definition of the $.loadStudentHtmlFragment() function, then $.loadStudentHtmlFragment() is called to load the HTML fragment.

The $.getJSON() method is not designed to load HTML fragments. But in the StudentRecordsHTMLFragment.aspx file, we have included the option to return the HTML fragment in a JSON object, so we can still use jQuery's $.getJSON() to obtain the JSON object and then obtain the HTML fragment from the JSON object. The following is how $.getJSON() is used in this article:

$("#btnUseGetJSON").click(function(e) {
    e.preventDefault();
 
    var $nRecord = $('#selNoOfStudentRecords').val();
    $target.html($ajax_load);
 
    $.getJSON($resource, { NRECORD: $nRecord, RETURNJSON: "True" }, function($x) {
        $target.html($x.TB);
        $information.html("Information retrieved by getJSON method ...");
    });
});

Run the ASP.NET Application

If you download the source code in this article, and if you set Default.aspx as the start page, you can debug run the application. If everything is alright, you should see all five methods work fine. The following screenshot shows the result of calling the $.getJSON() method to retrieve the information for five randomly generated students:

Run Application

This ASP.NET application is designed to be used when the web browser is maximized. The above picture is taken when the browser is re-sized to fit in this article, so the layout is slightly off. If you run the application and maximize the browser, it will look much prettier than what you see here.

Points of Interest

  1. Exchanging information with the server in AJAX style calls is a great step forward in web application development. With the help of jQuery, this turns out very easy and manageable. It makes the traditional web applications remain competitive with RIAs, such as Silverlight and Flex, although RIAs should by no means considered not traditional.
  2. The five jQuery AJAX methods used in this article are wrappers of the $.ajax() method. The wrappers are so thin, so we should not have any difficulty using $.ajax(). If you prefer, you can use $.ajax() directly.
  3. The $.getJSON() and $getScript() methods are not designed for the purpose of loading HTML fragments. In this article, I just managed to make them do the work that they are not good at, but somehow they worked.
  4. jQuery is a great tool; when combined with other technologies, we can achieve a lot good things, such as passing configuration information from the hosting web application to a Silverlight application in a more secure and flexible fashion.
  5. During my own test, jQuery runs pretty well in different browsers. I have tested this application in IE, Firefox, and Google Chrome. It functions well in all three of them, except in Firefox, the underlines of the text in the button controls are not shown. This is a problem with styles, not a problem with jQuery.
  6. Besides calling the five methods, the application also uses some other jQuery features. If you want to reference the code, you should be aware of it.

History

This is the first revision of this article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Dr. Song Li

United States United States
I have been working in the IT industry for some time. It is still exciting and I am still learning. I am a happy and honest person, and I want to be your friend.

Comments and Discussions

 
QuestionExcellent example - works with VS 2010 and Windows 7 Pinmembercharles92215-Jul-13 17:04 
GeneralMy vote of 5 PinmemberMd. Touhidul Alam Shuvo3-Jul-11 18:49 
QuestionGood Artical Pinmemberlovejun25-Jun-10 22:14 
AnswerRe: Good Artical PinmemberDr. Song Li12-Oct-10 17:03 
GeneralAnother good article based on Webservice Json ,Jquery with asp.net Pinmemberrajendra malav15-Feb-10 5:10 
GeneralRe: Another good article based on Webservice Json ,Jquery with asp.net PinmemberDr. Song Li26-Mar-10 16:12 
Thank you. I just do not understand why we will have consume web services and wcf if we use jQuery. But it is definitely useful, if the web application (using jQuery) have to consume some external data sources developed by someone else. If the the same team to develop the web application and the data source, I do not see the advantage to use web service nor WCF, except some security reason, which we do have a lot of ways to achieve.
GeneralExcellent Article Pinmemberadi007me10-Feb-10 22:07 
GeneralSafer PinmemberMihai Maerean9-Feb-10 2:18 
GeneralRe: Safer PinmemberDr. Song Li8-Apr-10 16:38 
GeneralNaming Pinmemberbinyamd2-Feb-10 7:22 
GeneralRe: Naming PinmemberDr. Song Li2-Feb-10 7:29 
GeneralRe: Naming Pinmemberjkjain jkjain13-Jul-10 21:07 
GeneralMis-typed PinmemberJerryK@POSOnThe.NET2-Feb-10 2:36 
GeneralRe: Mis-typed PinmemberDr. Song Li2-Feb-10 3:56 
GeneralRe: Mis-typed PinmemberGevorg3-Feb-10 5:43 
GeneralRe: Mis-typed PinmemberDr. Song Li3-Feb-10 8:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141216.1 | Last Updated 2 Feb 2010
Article Copyright 2010 by Dr. Song Li
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid