Assistance with XMLHttpRequest()

I’m trying some scripting (cannot use jquery) and having trouble with this:

var deviceID = "53ff6c04fa2465541432367";
var accessToken = "ac19a50d65c3fc798aa8b70efc7b4ca95a01";
var url = "https://api.spark.io/v1/devices/" + deviceID + "/Power";
var newValue = -1;
var params = JSON.stringify({'params':newValue, 'access_token':accessToken});
//alert(params); //OK

var http = new XMLHttpRequest();
http.open("POST", url, true);

http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {
    //if(http.readyState == 4 && http.status == 200) {
        {alert(http.responseText);
    }
}

http.send(params);

I’m getting the error:

“error”: “invalid_request”,
“error_description”: “The access token was not found”

can anyone see my error?

Being a JS noob, I might be completely off, but would this change anything?

var accessToken = "\'ac19a50d65c3fc798aa8b70efc7b4ca95a01\'";

(meaning embedding the single quotes in the access token string - if it’s done like that at all :blush:)

thanks but…

the access_token is embedded itno a JSON object and this:

JSON.stringify()

seems to take care of all of that… I’m guessing.

for me without jquery, this is like doing long division and only ever having used a calculator!!!i

Still, would be nice to figure this out!

1 Like

Just taking a quick stab at this before I run out the door.

JSON.stringify() is converting the object into a string, but I believe you actually need a URL encoded string.

Try this:
var params = "params=" + newValue + "&access_token=" + accessToken;

If that solves your problem, take a look at http://stackoverflow.com/questions/6566456/how-to-serialize-a-object-into-a-list-of-parameters for a more elegant way of doing that permanently.

1 Like