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

Jquery Ajax Calling Functions

, 12 Jul 2011
Rate this:
Please Sign up or sign in to vote.
Jquery Ajax Calling functions

Introduction

Recently I am working on a website with ASP.NET and jQuery. While working with JQuery library, I found that there are 5 different functions that used to make Ajax call to page and to fetch data. I am going to discuss about those five functions one by one. Following is a list of the five functions available in JQuery library to make an Ajax call.

  1. Load
  2. getJson
  3. GET
  4. POST
  5. Ajax

Load

This method allows to make ajax call to the page and allows to send using both Get and Post methods.

var loadUrl = "TestPage.htm";
$(document).ready(function () {
   $("#load_basic").click(function () {
     $("#result").html(ajax_load).load(loadUrl, function (response, status, xhr) {
                    if (status == "error") {
                        var msg = "Sorry but there was an error: ";
                        $("#dvError").html(msg + xhr.status + " " + xhr.statusText);
                    }
                }
                );
                return false;
});

As you can see in the above code, you can easily make a call to any page by passing it Url. The callback function provides more control and allows to handle the error if any by making use of the Status value. One of the important things about the load method is that it allows to load part of the page rather than the whole page. So get only a part of the page call remains the same, but the url is:

var loadUrl = "TestPage.htm #dvContainer"; 

So by passing the above url to load method, it just loads content of the div having id=dvContainer. Check the demo code for details.

Firebug shows the response that get returns when we call the page by Load method.

Important Features

  • Allows to make call with both Get and Post request
  • Allows to load part of the page

getJson

This method allows to get json data by making ajax call to page. This method allows only to pass the parameter by get method posting parameter is not allowed. One more thing - this method treats the respose as Json.

var jsonUrl = "Json.htm";
            $("#btnJson").click(function () {
                $("#dvJson").html(ajax_load);

                $.getJSON(jsonUrl, function (json) {
                    var result = json.name;
                    $("#dvJson").html(result);
                }
                );
                return false;
            });

The above code makes use of getJSON function and displays json data fetch from the page. Following is json data returned by the Json.htm file.

{
"name": "Hemang Vyas",
"age" : "32",
"sex": "Male"
}

The following image displays the json Data returned as response.

Important Features

  • Only sends data using get method, post is not allowed.
  • Treats the response data as Json only

get

Allow to make ajax request with the get method. It handles the response of many formats including xml, html, text, script, json, and jonsp.

var getUrl = "GETAndPostRequest.aspx";
            $("#btnGet").click(function () {
                $("#dvGet").html(ajax_load);

                $.get(getUrl, { Name: "Pranay" }, function (result) {
                    $("#dvGet").html(result);
                }
                );
                return false;
            });

As in code, I am passing Name parameter to the page using get request. On server side, you can get the value of the Name parameter in request object querycollection.

if (Request.QueryString["Name"]!=null)
{
    txtName.Text = Request.QueryString["Name"].ToString();
} 

The firebug shows the parameter passed by me as Get request and value of the parameter is pranay.

Important Features

  • Can handle any type of the response data.
  • Sends data using get method only.

post

Allows to make ajax request with the post method. It handles the response of many formats including xml, html, text, script, json, and jonsp. post does same as get but just sends data using post method.

var postUrl = "GETAndPostRequest.aspx";
            $("#btnPost").click(function () {
                $("#dvPost").html(ajax_load);

                $.post(postUrl, { Name: "Hanika" }, function (result) {
                    $("#dvPost").html(result);
                }
                );
                return false;
            });

As in code, I am passing Name parameter to the page using post request. On server side, you can get the value of the Name parameter in request object formcollection.

if (Request.Form["Name"] != null)
{
    txtName.Text = Request.Form["Name"].ToString();
}

The firebug shows the parameter passed by me as Get request and value of the parameter is Hanika.

Important Features

  • Can handle any type of the response data.
  • Sends data using post method only.

ajax

Allows to make the ajax call. This method provides more control than all other methods we have seen. You can figure out the difference by checking the list of parameters.

var ajaxUrl = "Json.htm";
            $("#btnAjax").click(function () {
                $("#dvAjax").html(ajax_load);


                $.ajax({
                    type: "GET", 		//GET or POST or PUT or DELETE verb
                    url: ajaxUrl, 		// Location of the service
                    data: "", 		//Data sent to server
                    contentType: "",		// content type sent to server
                    dataType: "json", 	//Expected data format from server
                    processdata: true, 	//True or False
                    success: function (json) {//On Successful service call
                        var result = json.name;
                        $("#dvAjax").html(result);
                    },
                    error: ServiceFailed	// When Service call fails
                });

                return false;
            });

In the above code, you can see all the parameters and comments related to each parameter describe the purpose of each one. Firebug shows the called page return json data and Ajax function treats the respose as Json because in code datatype = json.

Important Features

  • Provides more control on the data sending and on response data.
  • Allows to handle error occur during call.
  • Allows to handle data if the call to ajax page is successful.

Summary

So each method of jQuery ajax is different and can be used for difference purposes.

License

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

Share

About the Author

Pranay Rana
Software Developer (Senior) GMind Solusion
India India

Microsoft C# MVP (12-13)

 
Hey, I am Pranay Rana, working as a ITA in MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.
 
For me def. of programming is : Programming is something that you do once and that get used by multiple for many years
 

You can visit my blog

StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr
 
Awards:


Follow on   Twitter   LinkedIn

Comments and Discussions

 
Question[My vote of 1] English Pinmembermsdevtech18-Nov-13 14:08 
Questionafter download,how to open source code without .sln ? Pinmemberlmik989830-May-12 4:03 
GeneralNice -0 thanks Pinmembersada.narayanappa129-Apr-12 12:46 

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 | Mobile
Web02 | 2.8.140902.1 | Last Updated 12 Jul 2011
Article Copyright 2011 by Pranay Rana
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid