Repository navigation
Communicating w Server
AJAX is the shortened version of "Asynchronous JS And XML," and it's the general way we make requests to the server without reloading the web page, and then work with data we receive from the server. We give the user HTML and CSS first, then JavaScript, behind the scenes, fills in the rest of the action we want the page to offer. There are a few different ways to do this technically, and next we'll take a look at one of the most efficient ways: fetch().
The data that comes back from the server is not sent in HTML. While (once) sent back in XML, it's now most-often sent back in a format known as JSON. JavaScript Object Notation (JSON) is a String that JavaScript knows how to turn into an Object. So, in this module, we'll also need to talk about JavaScript Objects.
In AJAX we:
-
Deliver an initial, engaging page using HTML and CSS which browsers render quickly
-
Then we use JavaScript to add more to the DOM, behind the scenes
-
It allows us to pull in dynamic content.
-
It allows us to get data from multiple sources.
Using fetch(), we can include requests for data wherever we need to in our code. We can fetch() data on the click of a button or the expansion of an accordion display. There are many older methods for fetching data, but fetch() is the future.
If you think about it, fetch() is a little browser in your browser. You tell fetch() to go to a URL by passing it an argument e.g. fetch("https://flatironschool.com") and it makes a network request. You chain calls to fetch() with then(). Each then() call takes a callback function as its argument, based on actions in the callback function, we can display the content, update it, or inject it into the DOM.
The fetch() function retrieves data. It's a global method on the window object.
Here is a skeleton of how it works:
fetch("string representing a URL to a data source")
/*
The function above returns an object that represents what the data source
sent back. It does *not* return the actual content.
We have to call the then() method on the object that comes back. then()
takes as its argument a function that receives the response as its argument.
Inside of the function, we do whatever processing we need, but at the end we
*have to return* the content that we've gotten out of the response.
The response has some basic functions on it for the most common data types.
The most important ones are .json() and .text().
This callback function is usually only one line: returning the content from
the response. What we return from this function will be used in the _next_
then() function.
*/
.then(function(response) {
return response.json();
})
/*
The function above returns the content from the response.
We can use that content inside of the callback function that's
passed in to the then() function below.
*/
.then(function(json){
// Use this data inside of `json` to do DOM manipulation
})the abov is actually very easy concepts made look more complicated than they are.
fetch('http://api.open-notify.org/astros.json')
.then(function(response) {
return response.json();
}).then(function(json) {
console.log(json);
console.log(`Holy cow! There are ${json["number"]} humans in space.`);
});
//or
fetch('https://anapioficeandfire.com/api/books')
.then(resp => resp.json())
.then(json => console.log(json));fetch() provides us with a short way to fetch and work with resources. However, fetch() has only recently arrived in browsers. In older code you might see jquery.ajax or $.ajax or an object called an XMLHttpRequestObject.
We can use JavaScript to send a web request to an API and receive a collection of JSON in return.
Another fetch() example:
function fetchBooks() {
fetch('https://anapioficeandfire.com/api/books')
.then(resp => resp.json())
.then(json => {
console.log(json);
renderBooks(json)
});
}
function renderBooks(json) {
const main = document.querySelector('main')
json.forEach(book => {
const h2 = document.createElement('h2')
h2.innerHTML = `<h2>${book.name}</h2>`
main.appendChild(h2)
})
}
document.addEventListener('DOMContentLoaded', function() {
fetchBooks()
})JSON server install and start up:
$ npm install -g json-server
$ json-server --watch db.json
This will create a server storing all of our data with restful routes at http://localhost:3000/elements. You can also check out http://localhost:3000/elements/:id
fetch() take a JavaScript Object ({}) as the second argument. This Object can be given certain properties with certain values in order to change fetch()'s default behavior.
fetch(destinationURL, configurationObject);let formData = {
dogName: "Byron",
dogBreed: "Poodle"
};
let configObj = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify(formData)
};
fetch("http://localhost:3000/dogs", configObj) //this line is sufficient to POST the new item to db.json
.then(function(response) {
return response.json();
})
.then(function(object) {
console.log(object);
});body needs to be a STRING as fetch() is still an HTTP request. For this reason the Object Data needs to be converted into JSON.
When something goes wrong in a fetch() request, JavaScript will look down the chain of .then() calls for something very similar to a then() called a catch().
fetch("http://localhost:3000/dogs", configObj)
.then(function(response) {
return response.json();
})
.then(function(object) {
console.log(object);
})
.catch(function(error) {
alert("Bad things! Ragnarők!");
console.log(error.message);
});Sent to our JSON server from a page like index.html, we would receive a logged message:
Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.
catch() shows what otherwise would have been a silent error.