AJAX stands for Asynchronous JavaScript and XML. It is a technique for making requests to a server from a client-side web application, without requiring a full page refresh. This allows for a more seamless user experience, as data can be updated on the page without the need for the user to wait for a new page to load.
Making HTTP Requests with XMLHttpRequest
The XMLHttpRequest (XHR) API is a built-in browser object that allows web developers to make HTTP requests from the client side. It has been around for a long time and is supported by all modern browsers.
Here is an example of using the XHR API to make a GET request to retrieve data from a server:
function makeRequest() {
// Create a new XHR object
const xhr = new XMLHttpRequest();
// Open a new connection, using the GET request on the URL endpoint
xhr.open('GET', 'https://api.example.com/endpoint');
// Set the request header
xhr.setRequestHeader('Content-Type', 'application/json');
// Send the request
xhr.send();
// Wait for the request to complete
xhr.onload = function() {
if (xhr.status === 200) {
// If the request is successful, print the response
console.log(xhr.response);
} else {
// If the request is not successful, print an error message
console.error(xhr.response);
}
}
}
This code creates a new XHR object, opens a connection to the specified URL endpoint using a GET request, sets the request header to specify that the data being sent is in JSON format, and sends the request. The onload event handler is used to wait for the request to complete and will either print the response if the request is successful (status code 200) or print an error message if the request is not successful.
Making HTTP Requests with fetch
The fetch API is a newer, more modern way to make HTTP requests from the client side. It uses Promises, which makes it easier to work with than the XHR API.
Here is an example of using the fetch API to make a GET request to retrieve data from a server:
function makeRequest() {
// Make the GET request to the specified URL endpoint
fetch('https://api.example.com/endpoint')
.then(response => response.json()) // Parse the response as JSON
.then(data => console.log(data)) // Print the data
.catch(error => console.error(error)); // Print any errors that occur
}
This code makes a GET request to the specified URL endpoint and uses the then method to parse the response as JSON and print the data. If any errors occur, they will be caught and printed using the catch method.
Making different types of HTTP requests
Here is some additional information on making different types of HTTP requests using both the XMLHttpRequest and fetch APIs.
POST requests
POST requests are used to send data to a server to create or update a resource.
Here is an example of using the XHR API to make a POST request:
function makeRequest() {
// Create a new XHR object
const xhr = new XMLHttpRequest();
// Open a new connection, using the POST request on the URL endpoint
xhr.open('POST', 'https://api.example.com/endpoint');
// Set the request header
xhr.setRequestHeader('Content-Type', 'application/json');
// Create the data to be sent with the request
const data = {
name: 'John',
age: 30
};
// Send the request, with the data as the payload
xhr.send(JSON.stringify(data));
// Wait for the request to complete
xhr.onload = function() {
if (xhr.status === 201) {
// If the request is successful, print the response
console.log(xhr.response);
} else {
// If the request is not successful, print an error message
console.error(xhr.response);
}
}
}
This code is similar to the previous example, with the main difference being that it uses a POST request instead of a GET request, and includes data in the request payload. The Content-Type header is set to application/json to specify that the data being sent is in JSON format. The request will be successful if the server responds with a status code of 201 (Created).
Here is the equivalent code using the fetch API:
function makeRequest() {
// Create the data to be sent with the request
const data = {
name: 'John',
age: 30
};
// Make the POST request to the specified URL endpoint, with the data as the payload
fetch('https://api.example.com/endpoint', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json()) // Parse the response as JSON
.then(data => console.log(data)) // Print the data
.catch(error => console.error(error)); // Print any errors that occur
}
PUT and PATCH requests
PUT and PATCH requests are used to update a resource on the server. PUT requests replace the entire resource, while PATCH requests only update specific fields of the resource.
Here is an example of using the XHR API to make a PUT request:
function makeRequest() {
// Create a new XHR object
const xhr = new XMLHttpRequest();
// Open a new connection, using the PUT request on the URL endpoint
xhr.open('PUT', 'https://api.example.com/endpoint');
// Set the request header
xhr.setRequestHeader('Content-Type', 'application/json');
// Create the data to be sent with the request
const data = {
name: 'Jane',
age: 31
};
// Send the request, with the data as the payload
xhr.send(JSON.stringify(data));
// Wait for the request to complete
xhr.onload = function() {
if (xhr.status === 200) {
// If the request is successful, print the response
console.log(xhr.response);
} else {
// If the request is not successful, print an error message
console.error(xhr.response);
}
}
}
To make a PATCH request using the XHR API, you can simply change the request method from ‘PUT’ to ‘PATCH’.
Here is the equivalent code using the fetch API to make a PUT request:
function makeRequest() {
// Create the data to be sent with the request
const data = {
name: 'Jane',
age: 31
};
// Make the PUT request to the specified URL endpoint, with the data as the payload
fetch('https://api.example.com/endpoint', {
method: 'PUT',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json()) // Parse the response as JSON
.then(data => console.log(data)) // Print the data
.catch(error => console.error(error)); // Print any errors that occur
}
To make a PATCH request using the fetch API, you can simply change the request method from ‘PUT’ to ‘PATCH’.
DELETE requests
DELETE requests are used to delete a resource on the server.
Here is an example of using the XHR API to make a DELETE request:
function makeRequest() {
// Create a new XHR object
const xhr = new XMLHttpRequest();
// Open a new connection, using the DELETE request on the URL endpoint
xhr.open('DELETE', 'https://api.example.com/endpoint');
// Set the request header
xhr.setRequestHeader('Content-Type', 'application/json');
// Send the request
xhr.send();
// Wait for the request to complete
xhr.onload = function() {
if (xhr.status === 200) {
// If the request is successful, print the response
console.log(xhr.response);
} else {
// If the request is not successful, print an error message
console.error(xhr.response);
}
}
}
Here is the equivalent code using the fetch API to make a DELETE request:
function makeRequest() {
// Make the DELETE request to the specified URL endpoint
fetch('https://api.example.com/endpoint', {
method: 'DELETE'
})
.then(response => response.json()) // Parse the response as JSON
.then(data => console.log(data)) // Print the data
.catch(error => console.error(error)); // Print any errors that occur
}
Example:
Here is a real-life example of using the fetch API to make a GET request to retrieve data from a server. This example uses the OpenWeatherMap API to retrieve the current weather for a given city.
First, you will need to sign up for an API key on the OpenWeatherMap website: https://home.openweathermap.org/users/sign_up
Once you have your API key, you can use the following code to make a GET request to the OpenWeatherMap API:
function getWeather(city) {
// Make the GET request to the OpenWeatherMap API
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=YOUR_API_KEY`)
.then(response => response.json()) // Parse the response as JSON
.then(data => {
// Print the temperature in Celsius
console.log(`The temperature in ${city} is ${data.main.temp - 273.15}°C.`);
})
.catch(error => console.error(error)); // Print any errors that occur
}
// Get the weather for London
getWeather('Kathmandu');
This code makes a GET request to the OpenWeatherMap API, passing the city name as a query parameter and your API key as a appid parameter. The then method is used to parse the response as JSON and print the temperature in Celsius. If any errors occur, they will be caught and printed using the catch method.
To use this code, simply replace YOUR_API_KEY with your actual API key, and call the getWeather function with the name of the city where you want to get the weather for.
Other HTTP Libraries
In addition to the XMLHttpRequest and fetch APIs, there are also several third-party libraries that can be used to make HTTP requests from the client side. One popular library is Axios.
Axios is a lightweight, promise-based HTTP client that works in both the browser and Node.js. It has a similar API to fetch, but also offers a few additional features, such as automatic JSON data transformation and the ability to cancel requests.
Here is an example of using Axios to make a GET request to retrieve data from a server:
import axios from 'axios';
function makeRequest() {
// Make the GET request to the specified URL endpoint
axios.get('https://api.example.com/endpoint')
.then(response => console.log(response.data)) // Print the data
.catch(error => console.error(error)); // Print any errors that occur
}
This code is similar to the fetch example, with the main difference being that it uses the axios.get method instead of fetch, and prints the data using response.data instead of response.json().
Here are a few more examples of using Axios to make different types of HTTP requests:
import axios from 'axios';
// Make a POST request
function makePostRequest() {
// Create the data to be sent with the request
const data = {
name: 'John',
age: 30
};
// Make the POST request to the specified URL endpoint, with the data as the payload
axios.post('https://api.example.com/endpoint', data)
.then(response => console.log(response.data)) // Print the data
.catch(error => console.error(error)); // Print any errors that occur
}
// Make a PUT request
function makePutRequest() {
// Create the data to be sent with the request
const data = {
name: 'Jane',
age: 31
};
// Make the PUT request to the specified URL endpoint, with the data as the payload
axios.put('https://api.example.com/endpoint', data)
.then(response => console.log(response.data)) // Print the data
.catch(error => console.error(error)); // Print any errors that occur
}
// Make a DELETE request
function makeDeleteRequest() {
// Make the DELETE request to the specified URL endpoint
axios.delete('https://api.example.com/endpoint')
.then(response => console.log(response.data)) // Print the data
.catch(error => console.error(error)); // Print any errors that occur
}
As you can see, Axios offers a similar syntax to the fetch API, but with the added benefit of automatic JSON data transformation.
Other popular libraries for making HTTP requests include Superagent and jQuery.ajax(). You can choose the library that best fits your needs and preferences.
Practice Exercise
Here are some exercise questions that you can try to practice using the public APIs:
- Using the OpenWeatherMap API (API documentation: https://openweathermap.org/api), create a webpage that allows the user to enter a city name, and displays the current weather for that city. The weather data should include the temperature, humidity, and wind speed. You should also display an appropriate weather icon (e.g. sunny, cloudy, rainy) based on the weather conditions.
- Using the Twitter API (API documentation: https://developer.twitter.com/en/docs), create a webpage that displays the latest tweets from a given Twitter handle. The tweets should be displayed in a list, with the tweet text, user name, and user profile picture. You should also include a “Load More” button that allows the user to load additional tweets if they want to see more.
- Using the GitHub API (API documentation: https://docs.github.com/en/rest/guides/getting-started-with-the-rest-api), create a webpage that displays the list of repositories for a given GitHub username. The repositories should be displayed in a table, with the repository name, description, and the number of stars. You should also include a search bar that allows the user to search for repositories by keyword.
- Using the Spotify API (API documentation: https://developer.spotify.com/documentation/web-api/), create a webpage that displays a list of the top tracks for a given artist. The tracks should be displayed in a list, with the track name, album name, and album cover art. You should also include a search bar that allows the user to search for tracks by artist name.
Both the XMLHttpRequest and fetch APIs are useful for making HTTP requests from the client side but fetch is generally easier to work with due to its use of Promises. Whether you use XHR or fetch will depend on your personal preference and the requirements of your project.
