AJAX(Asynchronous JavaScript and XML(Extensible Markup Language))
Hari Mohan Prajapat
SD 3 at UST | Frontend Engineer (React, Next.js, TypeScript, JavaScript) | Python (Django, Flask, Pandas, NumPy, Jupyter) | AWS Computing | Author | Building Happy Software engineer's Community | Fitness Freak|25k
AJAX Complete Tutorial
AJAX (Asynchronous JavaScript and XML) allows you to send and receive data from a server asynchronously without refreshing the entire page. It’s commonly used for dynamic web applications to improve user experience.
1. What is AJAX?
2. How AJAX Works
3. AJAX Basics: A Simple GET Example
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX Example</title>
</head>
<body>
<button id="fetch-data">Fetch Data</button>
<div id="result"></div>
<script src="ajax-example.js"></script>
</body>
</html>
领英推荐
JavaScript (ajax-example.js)
// Select the button and result container
const button = document.getElementById('fetch-data');
const result = document.getElementById('result');
// Add event listener to the button
button.addEventListener('click', () => {
const xhr = new XMLHttpRequest();
// Initialize a GET request
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);
// Handle the response
xhr.onload = function () {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText); // Parse JSON response
result.innerHTML = `<h3>${data.title}</h3><p>${data.body}</p>`;
} else {
result.innerHTML = 'Error fetching data';
}
};
// Send the request
xhr.send();
});
4. AJAX POST Example
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX POST Example</title>
</head>
<body>
<form id="post-form">
<input type="text" id="title" placeholder="Enter title" required />
<textarea id="body" placeholder="Enter body" required></textarea>
<button type="submit">Submit</button>
</form>
<div id="response"></div>
<script src="ajax-post.js"></script>
</body>
</html>
JavaScript (ajax-post.js)
const form = document.getElementById('post-form');
const responseDiv = document.getElementById('response');
form.addEventListener('submit', (e) => {
e.preventDefault();
const title = document.getElementById('title').value;
const body = document.getElementById('body').value;
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://jsonplaceholder.typicode.com/posts', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function () {
if (xhr.status === 201) { // Status 201 means created
const data = JSON.parse(xhr.responseText);
responseDiv.innerHTML = `<h3>Post Created:</h3><p>ID: ${data.id}</p>`;
} else {
responseDiv.innerHTML = 'Error creating post';
}
};
// Send JSON data
xhr.send(JSON.stringify({ title, body, userId: 1 }));
});
5. Key AJAX Methods
Method Description open(method, url, async) Initializes a request (GET, POST, etc.). send(data) Sends the request. For POST, data can be a JSON object. setRequestHeader(key, value) Sets HTTP headers (e.g., Content-Type). onreadystatechange Event triggered when the request state changes. onload Event triggered when the request is complete.
SD 3 at UST | Frontend Engineer (React, Next.js, TypeScript, JavaScript) | Python (Django, Flask, Pandas, NumPy, Jupyter) | AWS Computing | Author | Building Happy Software engineer's Community | Fitness Freak|25k
1 个月https://www.dhirubhai.net/pulse/ajaxasynchronous-javascript-xmlextensible-markup-hari-mohan-prajapat-4muvc medium: https://medium.com/@tech.buildy/b7e58deb9809