How to usefetch() API in Javascript
In this approach, we will use fetch() API which is used to make XMLHttpRequest with the server. Because of its flexible structure, it is easy to use. This API makes a request to the server and gets the result as a promise which is resolved to the string.
Syntax:
fetch(url, {config}).then().catch();
Parameter: It takes URL and config of the request as parameters.
We will configure the data required and make the request to the server. Since it is a resolved promise we use then() function and the catch() function to create output for the result. In response, we get the string that we print.
Example: In this example, we will use fetch() API to make XMLHttpRequest with the server.
// Url for the request
let url = 'https://jsonplaceholder.typicode.com/todos/1';
// Making our request
fetch(url, { method: 'GET' })
.then(Result => Result.json())
.then(string => {
// Printing our response
console.log(string);
// Printing our field of our response
console.log(`Title of our response : ${string.title}`);
})
.catch(errorMsg => { console.log(errorMsg); });
Output:
{ userId:1 ,id:1 ,title : "delectus aut autem" ,completed : false
__proto__:Object }
Title of our response : delectus aut autem
How to make ajax call from JavaScript ?
Ajax is a powerful tool in web development for asynchronous communication with servers. With Ajax, you can fetch data from the server and update your webpage without interrupting what your user sees. It’s a basic concept in programming.
In this article, we’ll learn about three ways to make Ajax calls in JavaScript:
- Using the XMLHttpRequest object
- Using jQuery
- Using fetch() API
We’ll walk through each method with simple examples to help you understand how to use them in your projects.
Contact Us