9

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);
5
  • 12
    By "JASON", do you mean "JSON"? Commented Sep 23, 2013 at 15:11
  • 1
    @ajp15243 obviously... Commented Sep 23, 2013 at 15:17
  • 1
    You need to convert it to a string JSON.stringify, encode it, and post it. Commented Sep 23, 2013 at 15:20
  • 2
    FYI, that's not a "JSON style" object, nor is it JSON data. It's an object literal that creates an object. Commented Sep 23, 2013 at 15:20
  • 1
    inspect your traffic using the browser console to see what's getting sent. Commented Sep 23, 2013 at 15:21

2 Answers 2

22

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.