0

I am learning about using XMLHttpRequest to recieve JSON data from an api and also to post data, I have the following code to GET the JSON data,

var xmlhttp = new XMLHttpRequest(), json;

xmlhttp.open('GET', 'URL', true);
xmlhttp.send();

xmlhttp.onreadystatechange = function() {
    if(xmlhttp.readyState === 4 && xmlhttp.status === 200) {
        json = JSON.parse(xmlhttp.responseText);
        console.log(json);
        var string = JSON.stringify(json);
        console.log(string);
    }
};

However I am struggling to work out how to POST the data back to an api, after I have stringified a JSON object is this how I POST it?

var xhr = new XMLHttpRequest();
xhr.open('POST', 'URL', true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.send(string);

1 Answer 1

1

Try this

var xhr = new XMLHttpRequest();
xhr.open('POST', 'URL');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
    }
}
xhr.send(JSON.stringify(myData));
Sign up to request clarification or add additional context in comments.

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.