0

I'm trying to get an Xmlhttp.response from a website, specifically with this part of code:

var apiUrl = "http://somesite/someapicall/correctapiKey";
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", apiUrl, false);
xmlHttp.setRequestHeader("Content-Type", "application/json");
var data {
    "username": username,
    "password": hashedPass,
    "someOption": "true",
    "someOtherOption": "true"
}
xmlHttp.send(data);
var response = xmlHttp.responseText;
var parsed = eval('(' + response + ')');

If i put in the actual strings in "username": & "password" instead of using the variables the code does work. with the variables it fails.

I'm probably missing something small again, but i really can't see it and i'm breaking my head over it since this afternoon :(

anyone ? please...

edited: the username and the hashed pass are given as variables with known correct values. changed the code to reflect the use of the variables

6
  • Just look at how markdown renders your code... You missed a quote mark... Commented Dec 30, 2013 at 14:44
  • You can't unless it's jsonp. Look up Same-origin policy Commented Dec 30, 2013 at 14:44
  • You're also missing an = in your assignment of var data. Commented Dec 30, 2013 at 14:45
  • at which browser you are running this code Commented Dec 30, 2013 at 14:48
  • Also, not the reason it's failing but don't use eval() to parse JSON. Commented Dec 30, 2013 at 14:48

1 Answer 1

1

This:

 var apiUrl = "http://somesite/someapicall/correctapiKey";

uses an absolute URI, which implies you may be performing a cross-origin request. Make sure you aren't going to run into problems with the Same Origin Policy. (See also ways to circumvent it).


This:

var data {
    "username": username,
    "password": hashedPass,
    "someOption": "true",
    "someOtherOption": "true"
}

… is a syntax error. You need an = sign after data.

If the last two options are supposed to be booleans, they shouldn't have quotes around them.

You should avoid automatic semi-colon insertion. Put a ; after the }.


This:

xmlHttp.send(data);

… will convert data to a string by calling toString() on it. This will give you [Object object].

If you want to send JSON, then you must convert the JavaScript object to JSON:

data = JSON.stringify(data);

This:

var parsed = eval('(' + response + ')');

is evil, slow, hard to debug and potentially dangerous if you get an expected response. Use a JSON parser instead:

var parsed = JSON.parse(response);
Sign up to request clarification or add additional context in comments.

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.