Javascript AJAX: Difference between revisions
From wikinotes
(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" };...") |
No edit summary |
||
Line 4: | Line 4: | ||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
var payload = { "foo": "bar" }; | <script> | ||
var json_payload = JSON.stringify(payload); | document.addEventListener("DOMContentLoaded", function() { | ||
function sendAjaxRequest() { | |||
var payload = { "foo": "bar" }; | |||
var json_payload = JSON.stringify(payload); | |||
var XHR = new XMLHttpRequest(); | var XHR = new XMLHttpRequest(); | ||
XHR.open("POST", "/path/on/site"); | XHR.open("POST", "/path/on/site"); | ||
XHR.addEventListener("error", function() { | XHR.addEventListener("error", function() { | ||
console.log("An error occurred"); | |||
}); | }); | ||
XHR.addEventListener("load", function() { | XHR.addEventListener("load", function() { | ||
document.getElementById("results").innerHTML = this.responseText; | |||
}); | }); | ||
XHR.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); | XHR.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); | ||
XHR.send(json_payload); | XHR.send(json_payload); | ||
} | |||
document.addEventListener("click", function (event) { | |||
var target = event.target; | |||
if (target.matches("#submit")) { | |||
sendAjaxRequest(); | |||
} | |||
}); | |||
}); | |||
</script> | |||
<body> | |||
<div> | |||
<button id="submit">Submit</button> | |||
</div> | |||
</body> | |||
</syntaxhighlight> | </syntaxhighlight> |
Revision as of 02:17, 13 May 2022
XHR requests let you POST a request to a REST API, and update the page from a HTML event when it replies.
<script>
document.addEventListener("DOMContentLoaded", function() {
function sendAjaxRequest() {
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);
}
document.addEventListener("click", function (event) {
var target = event.target;
if (target.matches("#submit")) {
sendAjaxRequest();
}
});
});
</script>
<body>
<div>
<button id="submit">Submit</button>
</div>
</body>