Javascript AJAX

From wikinotes
Revision as of 02:13, 13 May 2022 by Will (talk | contribs) (Created page with "XHR requests let you POST a request to a REST API, and update the page from a HTML event when it replies. <syntaxhighlight lang="javascript"> var payload = { "foo": "bar" };...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

XHR requests let you POST a request to a REST API, and update the page from a HTML event when it replies.


var payload = { "foo": "bar" };
var json_payload = JSON.stringify(payload);

var XHR = new XMLHttpRequest();

XHR.open("POST", "/path/on/site");
XHR.addEventListener("error", function() {
  console.log("An error occurred");
});
XHR.addEventListener("load", function() {
  document.getElementById("results").innerHTML = this.responseText;
});
XHR.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
XHR.send(json_payload);