quiz/js: update explain ajax solution (#459)

This commit is contained in:
Nitesh Seram 2024-06-06 07:05:47 +05:30 committed by GitHub
parent 04584f6ed4
commit e9a2f3755f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 93 additions and 2 deletions

View File

@ -2,6 +2,97 @@
title: Explain Ajax in as much detail as possible.
---
Ajax (asynchronous JavaScript and XML) is a set of web development techniques using many web technologies on the client side to create asynchronous web applications. With Ajax, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. By decoupling the data interchange layer from the presentation layer, Ajax allows for web pages, and by extension web applications, to change content dynamically without the need to reload the entire page. In practice, modern implementations commonly use JSON instead of XML, due to the advantages of JSON being native to JavaScript.
**TL;DR**
The `XMLHttpRequest` API is frequently used for the asynchronous communication or these days, the `fetch` API.
Ajax (asynchronous JavaScript and XML) facilitates asynchronous communication between the client and server, enabling dynamic updates to web pages without reloading. It uses techniques like `XMLHttpRequest` or the `fetch` API to send and receive data in the background. In modern web applications, `fetch` API is more commonly used to implement Ajax.
Using `XMLHttpRequest` API:
```js
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error('Request failed: ' + xhr.status);
}
}
};
xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);
xhr.send();
```
Using `fetch` API:
```js
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then((data) => console.log(data))
.catch((error) => console.error('Fetch error:', error));
```
---
Ajax (asynchronous JavaScript and XML) is a set of web development techniques using many web technologies on the client side to create asynchronous web applications. Unlike traditional web applications where every user interaction triggers a full page reload, with Ajax, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. By decoupling the data interchange layer from the presentation layer, Ajax allows for web pages, and by extension web applications, to change content dynamically without the need to reload the entire page. In practice, modern implementations commonly use JSON instead of XML, due to the advantages of JSON being native to JavaScript.
Initially Ajax was implemented using the `XMLHttpRequest` API, but the `fetch` API is more suitable for modern web applications.
## `XMLHttpRequest` API
Here's a basic example of how it can be used:
```js
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error('Request failed: ' + xhr.status);
}
}
};
xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);
xhr.send();
```
## `fetch` API
Alternatively, the `fetch` API provides a modern, promise-based approach to making Ajax requests. It is more commonly used in modern web applications.
Here's how you can use it:
```js
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then((data) => console.log(data))
.catch((error) => console.error('Fetch error:', error));
```
## How does Ajax work?
Here's a breakdown of the core functionalities involved in an Ajax request:
- **Event Trigger**: A user interacts with a web page element, like clicking a button or submitting a form.
- **JavaScript Code Execution**: JavaScript code embedded in the web page captures the event and initiates an asynchronous communication using the XMLHttpRequest object (or the Fetch API in modern implementations).
- **`XMLHttpRequest` (or `fetch`) API**: This object establishes a connection with the server and sends the user's request, which might include data to be submitted or specific information to be retrieved.
- **Server Processing**: The web server receives the request, processes it, and generates a response containing the requested data (e.g., updated content, validation results).
- **Data Reception**: The XMLHttpRequest object or Fetch API receives the response from the server.
- **DOM Manipulation**: JavaScript processes the received data and dynamically alters the HTML content of the web page using the Document Object Model (DOM). This allows for targeted updates without reloading the entire page.
## Further reading
- [Ajax | MDN](https://developer.mozilla.org/en-US/docs/Glossary/AJAX)
- [XMLHttpRequest | MDN](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)
- [Fetch API | MDN ](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)