Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
POST JSON Data with AJAX
<!DOCTYPE html>
<html>
<body>
<br><br><br><br>
<center>
<h1>Send JSON Data to Server via the HTTP POST Method</h1>
<button onclick="postJSON();">SEND DATA</button>
</center>
<script>
function postJSON() {
var myJSONObject = {
"foo": "abc",
"bar": "xyz"
}
xhr = new XMLHttpRequest();
var url = "http://wingsuitgp.com/receivejson.php";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
// console.log(json.email + ", " + json.name)
alert("$myVariable: " + json.foo + "\n" + "$myOtherVariable: " + json.bar);
}
}
var data = JSON.stringify(myJSONObject);
xhr.send(data);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment