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);