Translate

Sunday, April 8, 2012

JQuery Ajax

Given below is a simple example of a jquery ajax call 


$.ajax({
    type: "POST",
    url: "http://www.w3schools.com/webservices/tempconvert.asmx/CelsiusToFahrenheit" ,
    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

Parameter
What it means
Possible values



type
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.
contentType
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

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


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



$.ajax({
            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