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 }
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(); })
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) { throwError(res.status) } return res; }).then(function(response) { /* other code here */ }).catch(function(error) { // The res.status is the parameter passed in /* other code here */ })
$.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)
functionhandleErrors(err) { if (err.response) { console.log("Problem with response", err.response.status) } elseif (err.request) { console.log("Problem with request") } else { console.log("Error "+err.message) } }