1

I have the following code and it seems to be not sending any params with the request. Any ideas what could be the issue? This is just a part of the code and I have ensured the variables x, y and pos in the params are being received:

 const params = {
            lat: x,
            long: y,
            current:pos,

        };

      var xhttp =new XMLHttpRequest();


      xhttp.open("POST","http://example.com/test/",true);
      xhttp.setRequestHeader("X-CSRFToken", csrftoken);
      xhttp.send(JSON.stringify(params));
      location.reload(true);

The POST request gets received on the server but there's no params

0

2 Answers 2

1

The XMLHttpRequst.send() method takes a FormData object as an input parameter, whereas you are passing a string to it. You can pretty simply convert your object to a FormData object using this statement:

var data = new FormData();
for(var key in params){
    data.append(key,params[key]);
}

Then with that, all you need to do is call send() on your new FormData object:

xhttp.send(data);
Sign up to request clarification or add additional context in comments.

Comments

0

var x = "test";
var y = "anothertest";
var pos = "testAgain";
const params = {
  lat: x,
  long: y,
  current: pos
};

var xhttp = new XMLHttpRequest();
var url = "http://example.com/test?";
for (var i in params) {
  if(params[i])
      url += i+"="+params[i]+"&";
}
console.log(url);
// Uncomment the following lines
//xhttp.open("POST",url,true);
//xhttp.setRequestHeader("X-CSRFToken", csrftoken);
//location.reload(true);

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.