Sunday, April 8, 2012

JQuery Ajax

Given below is a simple example of a jquery ajax call 

    type: "POST",
    url: "" ,
    contentType: "application/x-www-form-urlencoded",
    data: 'Celsius=75',
    dataType: "text/html"
    success: function (msg) {
   //code to handle success goes in there
    error: function (xhr, msg) {
   //code to handle failure goes in there

Given below are their definitions

What it means
Possible values

Whether to get data from or post data to the webserver
Get:  If you just need to fetch a webpage. (default)
Post: If you need to send some data to the webserver and get a response based on that data. This is generally used to change the current state of the web page.
Tells the webserver what type of content is being sent by the browser

The common content  types include:

  • application/x-www-form-urlencoded (default)
  • application/json
  • text/html
  • text/plain

Check here for all possible values

The url to make the request to.
Any web url
The data to be sent to the webserver
Key, value pairs
The datatype that the Jquery code would prefer to get back from the webserver.
·         xml

To make a jquery call using JSON, you would do something like this

            type: "POST",
            url: "WebServices/myWebService.asmx/MyMethod",
            contentType: "application/json; charset=utf-8",
            data: '{"param1":"' + param1+ '", "param2":"' + param2 + '"}',
            dataType: "json",
            success: function(msg) {
                var jsonObj = msg.d;

                var returnParam1 = jsonObj['To'];
                var returnParam2 = jsonObj['Subject'];
                var returnParam3 = jsonObj['Body'];
              error: function (xhr, msg) {              
                         //code to handle failure goes in there

   }); //end of  $.ajax

Check this out on a detailed simple example on making an ajax call.

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator