John Stimac
John Stimac

Reputation: 5493

How do I use POST with ajax?

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

Upvotes: 1

Views: 424

Answers (5)

ajitomatix
ajitomatix

Reputation: 388

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");

Upvotes: 0

epascarello
epascarello

Reputation: 207501

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

Upvotes: 1

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827208

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); 
} 

Upvotes: 3

Sebastian
Sebastian

Reputation: 1521

You can do it using jquery:

$.post("pageToPost.php", { firstParam: "Foo", secondParam: "Foo2" }, function(result){
alert("Response from pageToPost: " + result);
});

Upvotes: 1

stimms
stimms

Reputation: 44046

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

xmlhttp.open('POST', 'example.php', true);

Upvotes: 1

Related Questions