About 4 hours
Front-end code of interactive websites often needs to talk to backend servers to get and present data that the user asks for. Usually, this is done using API calls. AJAX is a way to make asynchronous calls to the server using JavaScript.
Participants will be able to:
AJAX stands for Asynchronous JavaScript and XML. It is a technique by which the front-end gets data by making asynchronous calls either to the project’s API in the back-end, or a 3rd-party API. Because AJAX is asynchronous, you must pass in a callback function to handle the received data. Making an AJAX request without any callback function will not have any effect on your application.
Let’s say this website that the end user is visiting is an e-commerce site. The end user is browsing a list of products, sees a product they want to buy, and clicks the “Buy” button. This action (clicking the “Buy” button) triggers the request/response steps listed above, this time for the purpose of putting the product in the shopping cart.
Before AJAX, the request/response cycle could only happen with the web page as a whole. The end user, by clicking the “Buy” button, would cause the backend server to generate a completely new set of HTML and JavaScript, and the browser would reload and render it as an entirely new page.
AJAX, however, enabled the browser to make requests and only re-render parts of a webpage. This was beneficial performance-wise, because smaller strings of HTML, rather than all the HTML for the entire page, was all that was needed to be sent by the server and rendered by the browser. This also made the end user’s browsing experience smoother: interactions with the webpage resulted in changes on screen without being interrupted by a reload.
Lets say there is an input box and a button. Onclick of button the page shows some data say hello world send by the server. When the button is clicked -
Difference Point | Full Load Page | AJAX |
---|---|---|
Client requests to server | waits for response | can perform other task simultaneously |
Server Response | responds a corresponding HTML page | responds with data (preferably JSON ) |
Render | a complete new page is rendered | only that part of page changes which has requested |
Thread Blocked | true | false |
Data Received by | the browser in form of HTML | JavaScript (callback or Promise) |
Now Let us understand this concept in more brief by implementing it practically. Follow the Link, clone the repository and start working.
It is important to understand the concept of Thread of Execution before we start with AJAX.
index.html
onClick
attribute. This will take a function which is called when the button is click.<button class="btn" onclick="getData()"> Show Data </button>
index.css
..btn{
padding: 10px;
border: none;
color: #fff;
background-color: green;
cursor:pointer;
}
index.js
Let’s write a function that fetches data from an API and displays it on the HTML page.
function getData() { console.log("Function getData is executed"); fetch("https://jsonplaceholder.typicode.com/todos/1", { headers: { "Content-Type": "application/json" } }) .then(res => res.json()) .then(data => { console.log("data", data); let element = document.getElementById("data"); element.textContent = data.title; }); }
- #### Breaking this down. -fetch
is a keyword, a function, used to call the server and get the data. It takes two parameters - - A string which is the URL of API. - An object, which has headers, method etc. -fetch
function returns a Promise, whether it is successful or not. If request is successful.then()
function will receive Response object, if request fails then.catch()
function will receive an error object. - When the promise is resolved we get a Response object in return. But wait, if you try logging Response object on the console you will find that it didn’t have the data which we want. That’s because a Response object has information about the response itself. To actually get the data, we need to get the body of the response. - Since we passed thecontent-type
asapplication/json
in headers, the response object is expected to be in.json()
method. - The.json()
method on a Response object returns a Promise, so we need to chain on another.then()
in which actual data is received.
XMLHttpRequest
object instead of AJAX to better understand what the AJAX wrapper doesMake the simplest project you can on Codepen.io. The project must:
fetch API
.