Skip to content

Instantly share code, notes, and snippets.

@topherPedersen
Created March 1, 2019 06:17
Show Gist options
  • Save topherPedersen/bb535518972edb95eba011993a3a54a1 to your computer and use it in GitHub Desktop.
Save topherPedersen/bb535518972edb95eba011993a3a54a1 to your computer and use it in GitHub Desktop.
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