MozillaZine


Sending an HTTP Request by POST method with XMLHttpRequest

Talk about add-ons and extension development.
Teamat

User avatar
 
Posts: 35
Joined: December 30th, 2006, 6:06 am
Location: Russia

Post Posted December 30th, 2006, 6:32 am

I want to send an HTTP Request that can substituting submiting a HTML form like:

Code: Select all
<form action="http://somesite.com/" method="POST">
<input type="text" value="20" name="num">
<input type="hidden" value="qwerty" name="str">
</form>


I've tryed to use next code, dut it wasn't successfully:

Code: Select all
var req = new XMLHttpRequest();
req.open('POST', 'http://somesite.com/', true);
var post =
"num=" + encodeURIComponent(unescape("20")) +
"&str=" + encodeURIComponent(unescape("qwerty"));
req.send(post);


Also:
Code: Select all
var req = new XMLHttpRequest();
req.open('POST', 'http://somesite.com/', true);
req.setRequestHeader("num", "20");
req.setRequestHeader("str", "qwerty");
req.send(post);

variant won't de successful too.

I'd be very grateful if someone can provide an example for working with POST method.

einare
 
Posts: 159
Joined: October 22nd, 2006, 1:16 pm
Location: Iceland

Post Posted December 30th, 2006, 7:36 am

You're missing the Content-type header. try something like:
Code: Select all

var http = new XMLHttpRequest();
var postdata= "foo=bar&baz=hey"; //Probably need the escape method for values here, like you did

http.open("POST", "http://yourdomain.com", true);

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

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

Teamat

User avatar
 
Posts: 35
Joined: December 30th, 2006, 6:06 am
Location: Russia

Post Posted December 30th, 2006, 1:11 pm

Thank you. It work excellent.

Return to Extension Development


Who is online

Users browsing this forum: No registered users and 2 guests