
AJAX Crash Course (Vanilla JavaScript)
In this video we will dive into AJAX with Vanilla JS and NO JQUERY. We will examine the XHR object and how it works. This is a beginner friendly tutorial for...
https://www.youtube.com/watch?v=82hnvUYY6QA
AJAX is a set of techs (not a framework) that allows sites to send and receive data asynchronously.
AJAX = "Async Javascript and XML" It allows requests and sends to happen behind the scenes and not interact with the current webpage. (XML has been replaced by JSON.)
The Fetch API is contained here, that's an indication of why I should learn this before wrapping my head around fetch. But I've got to DL XAMPP, woof.
XAMPP installed.
Basic example of using the XML object, which is how AJAX interacts with the broswer/server:
<!DOCTYPE html htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"
content="width=device-width, initial-scale=1.0">
<title>Ajax 1 - Text File</title>
</head>
<body>
<buttonid="button">Get Text File</button><br/><br/><div id="text"></div>
<script>
//Create event listener
document.getElementById('button').addEventListener('click',loadText())
function loadText(){
//Create XHR object
const xhr =newXMLHttpRequest()
// OPEN - type of request, URL or filename, async true or false
xhr.open('GET',"sample.txt",true)
// optional, usually for loading screen
xhr.onprogress=function(){console.log(xhr.readyState)}
xhr.onload=function(){
if(this.status==200){
console.log(this.responseText)
document.getElementById("text").innerHTML=this.responseText}}
xhr.onerror=function(){
console.log("request error")}
//sends request
xhr.send();}
</script>
</body>
</html>
200 : all ok
403: forbidden
404: not found