The different way of handle AJAX in JQuery

No.of Views696
Bookmarked0 times
Downloads 
Votes0
By  pranay rana   On  29 Jul 2011 10:07:57
Tag : JQuery , AJAX
Recently I am working on Website with the asp.net and JQuery. While working with JQuery library I found that there are 5 different function that used to make AJAX call to page and to fetch data such as load,getJSON,GET,POST and ajax.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

Recently I am working on Website with the asp.net and JQuery. While working with JQuery library I found that there are 5 different function that used to make AJAX call to page and to fetch data. I am going to discuss about that five function one by one.

Following is list of that five function availale in jquery libaray to make ajax call.

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

1.LOAD

Method allow 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 above code you can easily make call to any page by passing it Url. The call back function provide more control and allows to handle the error if any by making use of the Status value.
One of the important thing about the load method is its allow to load part of page rather than whole page. So get only part of the page call remains same but the url is

var loadUrl = "TestPage.htm #dvContainer";

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

Image Loading

Firebug shows the repose get return by when we call the page by Load method.

Important Features

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

2.getJson

Method allow 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 treat 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;
            });

Above code make use of getJSON function and displays json data fetch from the page.
Following is json data return by the Json.htm file.

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

Following image displays the json Data return as respose.

Image Loading

Important Features

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

3.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 passe by me as Get request  and  value of the parameter is pranay

Image Loading

Important Features

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

4.POST

Allow 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 send 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 passe by me as Get request  and  value of the parameter is Hanika

Image Loading

Important Features

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

5.AJAX

Allow to make the ajax call. This method provide more control than all other methods we seen. you can figure out the difference by checking the list of parameter.

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 Successfull service call
                        var result = json.name;
                        $("#dvAjax").html(result);
                    },
                    error: ServiceFailed// When Service call fails
                });
 
 
                return false;
            });

In above code you can see the all the parameter and comment related to each parameter describe the purpose of each one.

Fire bug shows the called page return json data and Ajax function treat the respose as Json because in code datatype = json

Image Loading

Important Features

  • Provide more control on the data sending and on response data.
  • Allow to handle error occur during call.
  • Allow to handle data if the call to ajax page is successfull.

Summary

So each method of jQuery ajax is different and can use for the difference purpose.

 
Sign Up to vote for this article
 
About Author
 
pranay rana
Occupation-CEO
Company-GMind Solusion
Member Type-Senior
Location-India
Joined date-08 Jan 2011
Home Page-http://pranayamr.blogspot.com
Blog Page-http://pranayamr.blogspot.com
Hey, I am Pranay Rana, working as a Senior Software engineer in mid-size company located in ahmedabad. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 4.3 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 me on my blog - http://pranayamr.blogspot.com/ StackOverFlow - http://stackoverflow.com/users/314488/pranay My CV :- http://careers.stackoverflow.com/pranayamr
 
 
Other popularSectionarticles
    In this article I will demonstration to how to validate whether to check at least one checkbox is checked in the Gridview in ASP.NET using JQuery. The JQuery is significant library to manipulate client html and css with less line of code.Before Jquery come up we have used the pure JavaScript to implement this features. I will give the JavaScript code as well in end of this article.
    Published Date : 30/Dec/2010
    Today I have implemented to my project to check and uncheck all checkboxes within gridview in asp.net. So in this article we focus how to implement this features using JQuery with less code. And also I have given live demonstration as well you can try it in live.
    Published Date : 29/Dec/2010
    In this article, I will explain how to sort custom objects array using JQuery. Let’s say you have array with custom objects, the custom object has few attributes as well, so in this case, you may need to sort objects with different order with specific attributes.
    Published Date : 12/Jan/2011
    The JQuery is powerful library to manipulate client side HTML, CSS, object and etc. On this article I will explain how to sort element within array using JQuery. In this demonstration I will show sort for string and numeric elements.
    Published Date : 11/Jan/2011
    Today I have introduced the new features for CodeGain article submit page to count characters for description textbox with JQuery on time. The character counter is support to users to display how many characters have entered and how many chars remaining in live.
    Published Date : 25/Dec/2010
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top