1

How do I send a custom HTTP body with my POST AJAX request in plain Javascript (not JQuery)? I am actually trying to send a JSON file in the body. I can set the custom header fields but can't find how to set HTTP body.

below is the code

function calculateorder() {

    document.getElementById("finalize").style.display = "inline";

    url1 = "https://ethor-prod.apigee.net/v1/stores/";    
    url2 = "/orders/calculate?apikey=wSgbv9PE8aJhDOI17vvTUX1NlAceUXG7";

    url = url1 + store_id + url2;

    var xmlhttp;
    xmlhttp = new XMLHttpRequest();

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

    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader("Content-Type", "application/json");
    xmlhttp.send(JSON.stringify(calculate));
}

When I used the same headers and JSON file with Rested (a OSX HTTP client) It works perfectly

9
  • Are you trying to read the posted data as a file on the server? If so see stackoverflow.com/questions/16223485/… Commented Mar 10, 2014 at 2:31
  • I am not sure. I did the same thing in Java using Data output stream and it worked. I guess server just reads it as a JSON stream. Commented Mar 10, 2014 at 2:35
  • Where do I put my JSON in that example? Commented Mar 10, 2014 at 2:41
  • Replace the xml with your json Commented Mar 10, 2014 at 2:42
  • Tried it. Did not work Commented Mar 10, 2014 at 2:51

1 Answer 1

2

Add parameter in XmlHttpRequest Obeject's .send() method

Like this:

xhr.send('username=me');

Send JSON Format Data myData Like this:

xhr.send(JSON.stringify(myData));
Sign up to request clarification or add additional context in comments.

6 Comments

What if I am sending a JSON file?
a file in your computer? or just a json format data?
Json format data. The json file is perfect. I checked it using Rested. But for some reason, it is not working when used with AJAX.
try xhr.send(JSON.stringify(myData));
any error message on the console? or try console.log(JSON.stringify(myData)) to debug
|

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.