Javascript HTTP POST with JSON data

Can I send a request as shown below? With parameters, a JSON style object is assigned. I get an error. But when I use the REST client and select RAW data, this is normal. I guess I wrote the wrong code. How to send raw JSON data in JavaScript? Can 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); 
+8
javascript post
source share
2 answers

Not. The send() method can take several different types of arguments , but a simple object is not one of them (so it will probably eventually call toString() on it and turn into "[Object object]" ).

If you want to send JSON, you need to:

  • Suppose you send JSON: xmlhttp.setRequestHeader("Content-type", "application/json");
  • Convert the JavaScript object to a JSON text string: var parameters = JSON.stringify({"username":"myname","password":"mypass"});
  • Be prepared to accept JSON instead of server / application-x-www-form-urlencoded data.

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

+21
source
 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)); 
+2
source

All Articles