Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Jquery Ajax Calling Functions

4.86/5 (42 votes)
4 Feb 2015CPOL3 min read 308.5K   4.3K  
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)