Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript HTTP POST with JSON data

Can I send a request as below? With parameters being assigned with a JSON style object. I only get error. But when I use a REST client and choose RAW data, it's OK. I guess I must have written incorrect code. How to send raw JSON data in JavaScript? Could anyone help me?

xmlhttp = new XMLHttpRequest();
var url = "https://someURL";
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        alert(xmlhttp.responseText);
    }
}
var parameters = {
    "username": "myname",
    "password": "mypass"
};
// Neither was accepted when I set with parameters="username=myname"+"&password=mypass" as the server may not accept that
xmlhttp.send(parameters);
like image 801
anaconda_wly Avatar asked Sep 23 '13 15:09

anaconda_wly


2 Answers

No. The send() method can take a number of different argument types, but a plain object is not one of them (so it will probably end up having toString() being called on it and being turned into "[Object object]").

If you want to send JSON then you must:

  1. Say you are sending JSON: xmlhttp.setRequestHeader("Content-type", "application/json");
  2. Convert your JavaScript object to a string of JSON text: var parameters = JSON.stringify({"username":"myname","password":"mypass"});
  3. Be prepared to accept JSON instead of application/x-www-form-urlencoded data on the server side.

Also note that, since you are using an absolute URI, you may run into cross domain issues.

like image 86
Quentin Avatar answered Nov 03 '22 02:11

Quentin


xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", AjaxURL, true);
xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
cb(xmlhttp.responseText);               
}
};
xmlhttp.send(JSON.stringify(Idata)); 
like image 38
mhdnp1234 Avatar answered Nov 03 '22 02:11

mhdnp1234