There are several ways to make an HTTP request in JavaScript. Here are 3 popular ways to make HTTP requests in JavaScript, which is supported by all modern browsers.
- XMLHttpRequest Object
- fetch function
- Ajax method in jQuery
XMLHttpRequest with Example
One of the most popular ways is to use the XMLHttpRequest object, which is supported by all modern browsers.
Here’s an example of how to use XMLHttpRequest to make a GET request to retrieve a JSON file and parse it,
1 2 3 4 5 6 7 8 9 10 |
const xhr = new XMLHttpRequest(); xhr.open('GET', '/my/url', true); xhr.responseType = 'json'; xhr.onload = function() { if (xhr.status === 200) { const data = xhr.response; // do something with the data } }; xhr.send(); |
Here is an example of how to use XMLHttpRequest to send a GET request to a server,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// Create an XMLHttpRequest object var xhr = new XMLHttpRequest(); // Open a connection xhr.open('GET', 'https://www.example.com/api/endpoint', true); // Set the response type xhr.responseType = 'json'; // Send the request xhr.send(); // Process the response xhr.onload = function () { if (xhr.status >= 200 && xhr.status < 300) { // Success! var data = xhr.response; console.log(data); } else { // Error :( console.error(xhr.statusText); } }; xhr.onerror = function () { console.error(xhr.statusText); }; |
Example Explanation:
- First, we have created an XMLHttpRequest object
- Then we opened the connection by using
xhr.open
method. - The open method takes three parameters, one is the request method, the second is an API endpoint and the last is a boolean.
- Then we set the response type to JSON or we can set XML as well.
- Now we can send the request using
send()
method on page load using JSonload()
function.
JavaScript Fetch Function
The fetch()
function is a modern way to make HTTP requests in JavaScript. It is a part of the window
object, and you can use it to fetch resources from a server.
Here is an example of how you can use the fetch()
function to retrieve data from a server,
1 2 3 4 5 |
fetch('https://example.com/api/endpoint') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)) |
- In this example, the
fetch()
function makes a GET request to the specified URL, and the server responds with a JSON object. - The
response.json()
method parses the response into a JavaScript object, and thethen()
method logs the data to the console.
- If there is an error making the request or parsing the response, it will be caught by the
catch()
method and logged into the console.
You can also use the fetch()
function to make POST requests, send data to the server, and customize the request with various options.
1 2 3 4 5 6 7 8 9 10 11 |
fetch('/my/url', { method: 'POST', body: JSON.stringify({name: 'John', age: 30}), headers: { 'Content-Type': 'application/json' } }) .then(response => response.json()) .then(data => { // do something with the data }); |
Note that fetch() is not supported in all browsers, so you may need to use a polyfill or a library such as Axios to ensure compatibility.
For more information on the fetch()
function and other ways to make HTTP requests in JavaScript, you can check out the documentation at https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API.
Ajax method in jQuery
The $.ajax() method in jQuery is a way to send an asynchronous HTTP (Ajax) request to a server. It allows you to send HTTP requests to a server and receive a response, without reloading the page.
Here is a simple example of how to use $.ajax() to send a GET request to a server and display the response,
1 2 3 4 5 6 7 8 |
$.ajax({ type: 'GET', url: '/my/server/endpoint', success: function(response) { // handle the server response console.log(response); } }); |
The $.ajax() method takes an object as its argument, which can have the following options:
type: The HTTP method to use for the request (e.g., “GET”, “POST”, “PUT”, etc.)
url: The URL to send the request to
data: Data to send to the server as part of the request (optional)
success: A function to be called if the request succeeds
error: A function to be called if the request fails
There are many other options available for $.ajax(), including options for handling HTTP headers, caching, and authentication. You can find a full list of options in the jQuery documentation.
Above are complete example-based explanations to make HTTP requests in JavaScript.
Also, Read:
- Auto Add Country Code in Input using JavaScript
- Auto Expand Input and Textarea Based on Text Length
- How Does JavaScript Array Filter Function work With Example
- Send Emails in JavaScript Using SMTP with Example
Happy Coding..!