views:

130

answers:

5

How do i use ajax to send POST requests to the server instead of GET?

+1  A: 

Put POST in as the first argument to xmlhttp.open() assuming you're using pure javascript:

xmlhttp.open('POST', 'example.php', true);
stimms
don't i have to add some other stuff? and where do parameters go?
Jcubed
More detail (at least a link to it) would sincerely help. Also, any indication of cross-browser compatibility.
Nerdling
+1  A: 

You can do it using jquery:

$.post("pageToPost.php", { firstParam: "Foo", secondParam: "Foo2" }, function(result){
alert("Response from pageToPost: " + result);
});
Sebastian
it would be ideal if i didn't use jquery.
Jcubed
Consider it as a valid option Jcubed. IMHO Jquery, as other javascript frameworks are great wrappers for great functionality and solving cross-browsing issues.
Sebastian
+3  A: 

Since I think that you're using the XHR object directly, you can make an 'postRequest' function easily:

We need the request url, the parameters to be send (params), and at least two callback functions success, which receives the responseText as the first argument when the request is completed successfully, and the error callback, which receives the XHR object and the status text:

function postRequest (url, params, success, error) {  
  var xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : 
                                   new XMLHttpRequest(); 
  xhr.open("POST", url, true); 
  xhr.onreadystatechange = function(){ 
    if ( xhr.readyState == 4 ) { 
      if ( xhr.status == 200 ) { 
        success(xhr.responseText); 
      } else { 
        error(xhr, xhr.status); 
      } 
    } 
  }; 
  xhr.send(params); 
}
CMS
@CMS: Your var xhr line is flawed on IE8/IE7 that have native support and ActiveX disabled. The ActiveX will throw an error and it will totally ignore the native support. Not good since it still could make a call. That is why it is important to use try catch which most libraries ignore.
epascarello
+1  A: 

Sounds like you really should sit down and read about Ajax if you can not figure out how to move from a GET to a POST. That is Ajax 101 stuff:

https://developer.mozilla.org/En/AJAX

epascarello
A: 

YUI connection manager would also be worth taking a look at as an alternative to jQuery. Using that you can make an ajax POST request as follows:

YAHOO.util.Connect.asyncRequest('POST', 'php/post.php', callback, "new=1&old=2");
ajitomatix