AJAX stands for Asynchronous JavaScript and XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with server-side scripts. It can send as well as receive information in a variety of formats, including JSON, XML, HTML, and even text files. AJAX’s most appealing characteristic is its "asynchronous" nature which means it can communicate with the server, exchange data, and update the page all without having to refresh the browser.
The two major features of AJAX allow you to do the following:
- Make requests to the server without reloading the page
- Receive and work with data from the server
... - Mozilla website
Use AJAX to send and receive data on the client-side, without refreshing the page.
Be careful not to assume synchronous execution of your JavaScript code. Assume the time between request and response is not certain.
After fetching the data, it won't be accessible to the console or other global scope part of your program (unless you save the results to a variable previously defined in the global scope). For more information, refer to this guide on global vs local scopes.
When we make an asynchronous request, we'll be working with objects called Promises, so it will be helpful to read up about them. To make use of the data eventually returned in a Promise, we'll either use a then()
strategy (preferred), or an async/await strategy (might not work on older browsers).
To make an asyncronous HTTP request, we can either use vanilla JavaScript, or third-party packages like d3, jQuery, or axios.
NOTE: let's prefer to use the Vanilla JavaScript
fetch()
method if possible, unless we're already using one of the other packages in our project, to avoid unnecessary dependencies.
References:
Issuing GET requests (the following approaches are equivalent):
var requestUrl = "https://raw.githubusercontent.com/prof-rossetti/internet-technologies/main/exercises/fetch-the-data/gradebook.json"
// PROMISE CHAINING w/ ARROW FUNCTIONS
fetch(requestUrl)
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.log(err))
// PROMISE CHAINING
fetch(requestUrl)
.then(response => {
console.log("RESPONSE", response)
return response.json()
})
.then(data => {
console.log("DATA", data) // this is the data you're looking for
})
.catch(err => {
console.error("FETCH ERR", err)
})
Issuing POST requests:
var requestUrl = "https://example.com/api/robots"
var formData = {name: "New Bot", description: "Does all the things."}
var requestOptions = {
method: "POST",
headers: {'Accept':'application/json', 'Content-Type':'application/json'},
body: JSON.stringify(formData)
}
fetch(requestUrl, requestOptions)
.then(function(response) {
if (response.ok) { // check response status and proceed accordingly
response.json()
.then(function(data){
console.log(data)
})
} else {
console.log("OOPS")
}
})
.catch(function(err){
console.log("OOPS")
})
References:
Issuing GET requests with D3:
var requestUrl = "https://raw.githubusercontent.com/prof-rossetti/internet-technologies/main/exercises/fetch-the-data/gradebook.json"
d3.json(requestUrl, function(json){
console.log("GOT SOME DATA:", json)
// DO SOMETHING WITH THE DATA HERE!
})
Issuing POST requests with D3:
var requestUrl = "https://example.com/api/robots"
var formData = {name: "New Bot", description: "Does all the things."}
d3.request(requestUrl)
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.on("error", function(error) {
// HANDLE ERRORS HERE
})
.on("load", function(xhr) {
// HANDLE RESPONSE HERE
})
.send("POST", JSON.stringify(formData))
References:
Issuing GET requests with JQuery:
var url = "https://raw.githubusercontent.com/prof-rossetti/internet-technologies/main/exercises/fetch-the-data/gradebook.json"
$.getJSON(url, function(json) {
console.log("GOT SOME DATA:", json)
// DO SOMETHING WITH THE DATA HERE!
});
Issuing POST requests with JQuery:
var requestUrl = "https://example.com/api/robots"
var formData = {name: "New Bot", description: "Does all the things."}
$.post(requestUrl, formData)
.done(function(data, textStatus, xhr) {
// HANDLE RESPONSE HERE
})
.fail(function(xhr, textStatus, errorThrown){
// HANDLE ERRORS HERE
})
References:
Issuing GET requests with axios:
var requestUrl = "https://raw.githubusercontent.com/prof-rossetti/internet-technologies/main/exercises/fetch-the-data/gradebook.json"
axios.get(requestUrl)
.then(function (response) {
// handle success
console.log("RESPONSE:", response)
console.log("DATA:", response.data)
})
.catch(function (error) {
// handle error
console.log(error)
})
.then(function () {
// always executed
})
Issuing GET requests with URL params object (as an alternative to compiling the params in the request URL itself, which would require some escaping of spaces and special characters), with Axios:
var API_KEY = "abc123" // TODO: use env vars instead of hard-coding
// https://www.yelp.com/developers/documentation/v3/business_search
var requestUrl = "https://api.yelp.com/v3/businesses/search"
console.log("REQUEST URL:", requestUrl)
var requestOptions = {
headers: {
Authorization: `Bearer ${API_KEY}`,
},
params: {
location: "Washington, DC", // todo: use form data
price: 3 // todo: use form data
}
}
console.log("REQUEST OPTIONS:", requestOptions)
axios.get(requestUrl, requestOptions)
.then(function (response) {
//console.log("RESPONSE:", response)
console.log("DATA:", response.data)
})
.catch(function (error) {
console.log("ERR:", error)
})
.then(function () {
console.log("DONE...")
})
})
Issuing POST requests with axios:
var requestUrl = "https://example.com/api/robots"
var requestData = {
firstName: 'Fred',
lastName: 'Flintstone'
}
axios.post(requestUrl, requestData)
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
References:
FYI: sometimes instead of using then()
to handle Promises, you might see an async / await strategy:
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved')
}, 2000)
});
}
async function asyncCall() {
const result = await resolveAfter2Seconds()
console.log(result);
}
asyncCall()
NOTE: The await keyword can only be used inside an async function. So it might require us to use some awkward wrapper function(s).