Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Send a body of data to XMLHttpRequest that looks like this?

How do I format this correctly?

var params = {
  "range":"Sheet1!A4:C4",
  "majorDimension": "ROWS",
  "values": [
    ["Hello World","123", "456"]
  ],
}

Then send it using POST like :

   var xhr = new XMLHttpRequest();
   xhr.open(method, url);
   xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);
   xhr.onload = requestComplete;
   xhr.send(params);

I know Im going to encounter errors because there's a proper way of formatting my "request body". It looks like a mixture of array and JSON so Im asking for your help how to format it correctly.

like image 705
ReyAnthonyRenacia Avatar asked Jun 06 '16 09:06

ReyAnthonyRenacia


People also ask

How does XMLHttpRequest send body data?

Create a new XMLHttpRequest object let xhr = new XMLHttpRequest(); // 2. Configure it: GET-request for the URL /article/.../load xhr. open('GET', '/article/xmlhttprequest/example/load'); // 3. Send the request over the network xhr.

What are the types of send () method used for XMLHttpRequest?

The XMLHttpRequest method send() sends the request to the server. If the request is asynchronous (which is the default), this method returns as soon as the request is sent and the result is delivered using events.


2 Answers

var xhr = new XMLHttpRequest();
   xhr.open(method, url);
   xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);
   xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
   xhr.onload = requestComplete;
   xhr.send(JSON.stringify(params));

It looks like you just needed to stringify your params before passing them to send()

like image 99
Vladu Ionut Avatar answered Oct 21 '22 06:10

Vladu Ionut


Have you tried it out yet? You can't just assume that you are going to encounter errors. You wouldn't know unless you try. Try you first method, if it fails, you would have discovered a way that won't work. Then you find other ways that would work, that's how we learn. It is from the errors and failures that we learn not from the successes.

That being said, if your method fails as you have assumed, try to use JSON.stringify on the params before sending it just like this

xhr.send(JSON.stringify(params))

That should work.

like image 24
El'Magnifico Avatar answered Oct 21 '22 06:10

El'Magnifico