Notes about ajax request

Create XMLHttpRequest object

XMLHttpRequest is basic of Ajax request,

1
const xhr = new XMLHttpRequest();

Send a request to the server

1
2
xmlhttp.open("GET", "url"); // url is the api endpoint
xml.send();

onreadystatechange

There are 5 state of xmlhttprequest, from 0 to 4

  1. Request not initialized
  2. Server connection is established
  3. Request has been received
  4. Request is being processed
  5. Request completed and response is ready

Hence, When readyState is equal to 4 and the status is 200, the response is ready.

1
2
3
4
5
xml.onreadystatechange=function() {
if(xml.readyState==4 && xml.status==200) {
document.getElementById("myDiv").innerHTML=xml.responseText;
}
}

Ajax json examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
function loadXMLDoc(){
// init a xmlhttprequest
const xmlhttp = new XMLHttpRequest();

// init a onreadystatechange and parse xml to json
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var myArr = JSON.parse(this.responseText);
myFunction(myArr)
}
}
//send the xml request
xmlhttp.open("GET","/try/ajax/json_ajax.json",true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send();
}
// function to change the dom
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' +
arr[i].title + '</a><br>';
}
document.getElementById("myDiv").innerHTML=out;
}

Ajax with Promise examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

const p = new Promise((resolve, reject)=>{
const xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4){
if (xmlhttp.status==200)
{
//success
resolve(this.responseText)
}else{
//fail
reject(xmlhttp.status)
}
}
}
})

//promise followup
const result = p.then(function(value){
let myArr = JSON.parse(value)
myFunction(myArr)
return myArr
},function(reason){
console.log(reason)
return 'error'
})

// function to change the dom
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' +
arr[i].title + '</a><br>';
}
document.getElementById("myDiv").innerHTML=out;
}
Author

Elliot

Posted on

2022-06-10

Updated on

2023-05-07

Licensed under