AJAX(Asynchronous JavaScript and XML(Extensible Markup Language))

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?

  • Acronym: Asynchronous JavaScript and XML.
  • Purpose: Fetch data from the server without refreshing the page.
  • Technologies Used: JavaScript: To send requests and handle responses. XML or JSON: To transfer data between the client and the server. DOM: To update the webpage dynamically.


2. How AJAX Works

  1. A user triggers an event (e.g., clicking a button).
  2. JavaScript creates an XMLHttpRequest object.
  3. The request is sent to the server.
  4. The server processes the request and sends back data (usually in JSON or XML format).
  5. JavaScript processes the response and updates the web page dynamically.


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.




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

1 个月
回复

要查看或添加评论,请登录

Hari Mohan Prajapat的更多文章

社区洞察

其他会员也浏览了