Click here to Skip to main content
15,868,349 members
Articles / Web Development / HTML

Jquery Ajax Calling Functions

Rate me:
Please Sign up or sign in to vote.
4.86/5 (42 votes)
4 Feb 2015CPOL3 min read 306.7K   4.3K   78   6
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.

JavaScript
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:

JavaScript
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.

Image 1

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.

JavaScript
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.

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

The following image displays the json Data returned as response.

Image 2

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.

JavaScript
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.

JavaScript
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.

Image 3

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.

JavaScript
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.

JavaScript
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.

Image 4

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.

JavaScript
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.

Image 5

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)


Written By
Software Developer (Senior)
India India

Microsoft C# MVP (12-13)



Hey, I am Pranay Rana, working as a Team Leadin 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:



Comments and Discussions

 
GeneralNice -0 thanks Pin
sada.narayanappa129-Apr-12 12:46
sada.narayanappa129-Apr-12 12:46 

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

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