AJAX Notes

AJAX, stands for Asynchronous JavaScript and XML, is an approach allows websites to send and request data from a server in the background without disturbing the current page.

XML & JSON

They are both data formats.

An example of XML, stands for Extended Markup Language.

1
2
3
4
<pin>
<title>Adorable Maine Coon</title>
<author>Cindy S</author>
</pin>

An example of JSON

1
2
3
4
'pin': {
'title': 'Adorable Maine Coon'
'author': Cindy S
}

Making Requests with JavaScript by XMLHttpRequest

Random Dog Picture Project - Traditional approach

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var btn = document.querySelector("#btn");
var img = document.querySelector("#photo"); /* The photo to be changed */

// listen for clicks
btn.addEventListener("click", function(){
// make the request
var XHR = new XMLHttpRequest();
XHR.onreadystatechange = function() {
if (XHR.readyState == 4 && XHR.status == 200) {
var data = JSON.parse(XHR.responseText);
console.log(XHR.responseText); /* Text(String) but not JavaScript Objects*/
console.log(data.message); /* Refer to the property of JS Object */
/* A short version */
var url = JSON.parse(XHR.responseText).message;
img.src = url; /* image will be changed as we get the new URL */
}
}
XHR.open("GET", "The-URL");
XHR.send();
})

Fetch

Update to XHR

1
2
3
4
5
6
7
fetch(url)
.then(function(res) {
console.log(res);
})
.catch(function(error) {
console.log(error);
});

.json() method will return a promise

1
2
3
4
5
6
7
8
fetch(url)
.then(function(response){
console.log(response)
return response.json()
})
.then(function(data){
console.log(data)
})

Fetch options

1
2
3
4
fetch(url, {
method: 'POST',
body: 'This is body of the request!'
})

The body can be formatted as

1
2
3
4
body: JSON.stringify({
name: 'blue',
login: 'cat'
})

which will stringify the content as {"name": "blue", "login": "bluecat"}

Fetch error handling

.catch will not respond to the request status, but to connection issues or the request itself, etc.

To handle fetch errors

1
2
3
4
5
6
7
8
9
10
11
fetch(url)
.then(function(res){
if (!res.ok) {
throw Error(res.status)
}
return res;
}).then(function(response) {
/* other code here */
}).catch(function(error) { // The res.status is the parameter passed in
/* other code here */
})

To handle errors in a seperated function

1
2
3
4
fetch(url)
.then(handleErrors)
.then(/* code */)
.catch(/* code */);

User Profile Generator Project

A hint

1
2
3
4
5
fetch(url)
.then(handleErrors)
.then(parseJSON)
.then(updateProfile)
.catch(printError)

Reference: https://codepen.io/rosie99/pen/VweNPJO?editors=1011

Fetch Problems

  • Browser compatibility

AJAX With JQuery

  • $.ajax
  • $.get - shorthand methods
  • $.post - shorthand methods
  • $getJSON - shorthand methods

$.ajax

1
2
3
4
5
6
7
8
9
10
11
12
$.ajax({
method: "GET",
url: "api.com"
// the data type will not be guessed intelligently
// dataType: "json"
})
.done(function(res){ // the method will parse the data intelligently
console.log(res)
})
.fail(function(){
// some code
})
  • What triggered .fail() - connection issues (same as fetch) and request errors
  • jQuery is just generalizing XHR behind the scenes

Shorthand methods

  • $.get()

    1
    2
    3
    4
    $.get("ajax/test.html", function(data)){
    // the success callback function
    // returned data is passed, which will be intelligently parsed
    }
  • $.post for post request

  • $.getJSON() - specifiy parse JSON, which is euqivalent to dataType: "json"

Random Cat Photo Project

1
$('#catImg').attr('src', data.file)

Axios - A lightweight HTTP request library

1
2
3
4
5
6
7
axios.get(url)
.then(function(res){ // res is the response, not the data purely
console.log(res.data) // res.data is needed
})
.catch(function(e){
console.log(e)
})

Error Handling

1
2
3
4
5
6
7
8
9
10
11
// .catch(handleErrors)

function handleErrors(err) {
if (err.response) {
console.log("Problem with response", err.response.status)
} else if (err.request) {
console.log("Problem with request")
} else {
console.log("Error "+err.message)
}
}