0

I created a standard function to POST a data object

post = function(url, data){

// Return a new promise.
return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();
    req.open("POST", url, true);
    req.setRequestHeader("Content-Type", "application/json");

    req.onload = function() {
        // This is called even on 404 etc
        // so check the status
        if (req.status == 200) {
            // Resolve the promise with the response text
            resolve(req.response);
        }
        else {
            // Otherwise reject with the status text
            // which will hopefully be a meaningful error
            reject(Error(req.statusText));
        }
    };

    // Handle network errors
    req.onerror = function() {
        reject(Error("Network Error"));
    };

    var jayson = JSON.stringify(data);
    req.send(jayson);
    });
};

when I call this function with data = {key: value, anotherKey: value}, the jayson variable looks like this:

"{"key":value, "anotherKey":value}"

In the end, the data does not reach the server (the request does). I get a 200 status back, so on the server all is well.

(yes, it needs to be a POST - no, I do not want to use jQuery)

What's going wrong in my function, that it does not send my data?

Johan P
  • 89
  • 13
  • 2
    "In the end, the data does not reach the server (the request does)" — this sounds unlikely. Open the developer tools in your browser. Look at the Network tab. Examine the request. Is it a POST request? Does it have the request body you expect? – Quentin Jun 08 '17 at 14:01
  • Whatever `JSON.stringify` reruns is valid JSON. – Felix Kling Jun 08 '17 at 14:01
  • 1
    Why you think that data does not reach the server ? Other words how you check it ? – Alisher Gafurov Jun 08 '17 at 14:07
  • in Network tab, I klick on the request - I can't see it defined as POST i do see the Request Payload – Johan P Jun 08 '17 at 14:08
  • @AlisherGafurov - I check in the $_POST object - nothing there – Johan P Jun 08 '17 at 14:09
  • @JohanPotums — "I check in the $_POST object - nothing there" — Well, there wouldn't be. You're sending JSON, not a standard form encoding type. – Quentin Jun 08 '17 at 14:10
  • So where do I find it? – Johan P Jun 08 '17 at 14:12
  • See the duplicate question. – Quentin Jun 08 '17 at 14:15
  • @Quentin ah - I found it after letting the response come back - it is definitely POST - not sure about the Request Body though - the Request Payload (Chrome Developer tools) gives correct values – Johan P Jun 08 '17 at 14:16
  • @Quentin - thanks for your input - I had no idea and the resources about posting JSON do not mention this – Johan P Jun 08 '17 at 14:20

0 Answers0