Friday, 21 May 2010

What are the differences b/w GET and POST in ajax call?

var http = new XMLHttpRequest();

Using GET method

Now we open a connection using the GET method.

var url = "getdata.php";
var params = "name=ashwani&action=true";
http.open("GET", url+"?"+params, true);
http.onreadystatechange = function() {//Call a function when the state changes.
 if(http.readyState == 4 && http.status == 200) {
  alert(http.responseText);
 }
}
http.send(null);
I really hope that this much is clear for you - I am assuming that you know a bit of Ajax coding.



POST method

We are going to make some modifications so POST method will be used when sending the request...

var url = "getdata.php";
var params = "name=ashwani&action=true";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {//Call a function when the state changes.
 if(http.readyState == 4 && http.status == 200) {
  alert(http.responseText);
 }
}
http.send(params);

The first change(and the most obvious one) is that I changed the first argument of the open function from GET to POST. Also notice the difference in the second argument - in the GET method, we send the parameters along with the url separated by a '?' character...

Cheers!

1 comment:

  1. Nice blog...Very useful information is providing by ur blog..here is a way to find.
    Hire Yii Development Company in India

    ReplyDelete