J

JavaScript Handbook

Clean • Professional

JavaScript AJAX — Top Interview Questions & Answers

5 minute

JavaScript AJAX — Interview Questions & Answers

Ques: What is AJAX in JavaScript?

Ans: AJAX (Asynchronous JavaScript and XML) is a technique that allows web pages to send and receive data from a server asynchronously—without reloading the entire page.

It helps build dynamic, fast, and responsive web applications.

Example: Updating a comment section or live search results without refreshing the page.

Ques: What does AJAX stand for?

Ans: AJAX = Asynchronous JavaScript And XML

Even though it has “XML” in the name, AJAX commonly uses JSON instead of XML for data exchange today.

Ques: How does AJAX work?

Ans: AJAX uses the following workflow:

  1. A JavaScript event triggers a request (e.g., button click).
  2. The XMLHttpRequest or Fetch API sends a request to the server.
  3. The server processes the request and sends data back (usually in JSON format).
  4. JavaScript updates the web page content dynamically without reloading.

Ques: Which technologies are used in AJAX?

  • HTML/CSS → Display content
  • JavaScript → Handle requests & responses
  • XMLHttpRequest / Fetch API → Communicate with server
  • Server-side languages → Process requests (PHP, Node.js, ASP, etc.)
  • Database → Store and retrieve data

Ques: What is the XMLHttpRequest object?

Ans: XMLHttpRequest (XHR) is the core object used in AJAX to communicate with the server in the background.

It allows you to:

  • Send and receive data asynchronously
  • Handle different response types (text, XML, JSON)

Ques: How do you create an XMLHttpRequest object?

let xhr = new XMLHttpRequest();

Ques: What are the common properties of XMLHttpRequest?

PropertyDescription
readyStateHolds the status of the request
statusHTTP response status (200 = OK, 404 = Not Found)
responseTextReturns response data as text
responseXMLReturns response data as XML
onreadystatechangeEvent handler for state changes

Ques: What are the possible values of readyState in XMLHttpRequest?

readyStateMeaning
0Request not initialized
1Server connection established
2Request received
3Processing request
4Request finished and response ready

Ques: How to send a simple AJAX GET request using XMLHttpRequest?

let xhr = new XMLHttpRequest();
xhr.open("GET", "data.json", true);
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  }
};
xhr.send();

Ques: How to send data with a POST request using AJAX?

let xhr = new XMLHttpRequest();
xhr.open("POST", "submit.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onload = function() {
  console.log(xhr.responseText);
};
xhr.send("name=John&age=25");

Ques: What is the difference between GET and POST in AJAX?

MethodDescription
GETSends data in the URL (for retrieving data)
POSTSends data in the request body (for submitting data)
SecurityGET is less secure
Data LimitLimited

Ques: What are AJAX callbacks?

Ans: Callbacks are functions executed when the server’s response is ready.

In AJAX, they handle success or error after an asynchronous request.

Example:

xhr.onload = () => console.log("Request successful!");
xhr.onerror = () => console.log("Request failed!");

Ques: How do you handle AJAX responses in JavaScript?

Ans: You can use:

  • xhr.responseText → To get plain text
  • JSON.parse(xhr.responseText) → To get JSON data

Example:

xhr.onload = () => {
  let data = JSON.parse(xhr.responseText);
  console.log(data.name);
};

Ques: What are the advantages of using AJAX?

  • No full page reload
  • Improved performance
  • Better user experience
  • Reduced server load
  • Real-time updates (e.g., chat, notifications)

Ques: What are the disadvantages of AJAX?

  • Browser history may not update properly.
  • Complex error handling.
  • SEO challenges for dynamic pages.
  • May not work well with disabled JavaScript.

Ques: What is an example of a simple AJAX request?

<button onclick="loadData()">Load Data</button>
<div id="result"></div>

<script>
function loadData() {
  let xhr = new XMLHttpRequest();
  xhr.open("GET", "info.txt", true);
  xhr.onload = function() {
    document.getElementById("result").innerHTML = xhr.responseText;
  };
  xhr.send();
}
</script>

Ques: What are AJAX Events in XMLHttpRequest?

EventDescription
onloadWhen the request completes successfully
onerrorWhen the request fails
onprogressDuring data transfer
onreadystatechangeOn every state change

Ques: How can you use AJAX with PHP?

Ans: AJAX sends data to a PHP file, which processes and returns a response.

Example:

// client.js
let xhr = new XMLHttpRequest();
xhr.open("POST", "server.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onload = () => console.log(xhr.responseText);
xhr.send("name=John");

server.php

<?php
echo "Hello " . $_POST['name'];
?>

Ques: How can you use AJAX with ASP.NET?

let xhr = new XMLHttpRequest();
xhr.open("GET", "server.aspx?user=John", true);
xhr.onload = () => console.log(xhr.responseText);
xhr.send();

server.aspx

<%
Response.Write("Hello " & Request.QueryString("user"))
%>

Ques: How does AJAX interact with a database?

Ans: AJAX doesn’t access a database directly.

It communicates with a server-side language (PHP, Node.js, etc.) that performs database queries (MySQL, MongoDB) and returns results in JSON or XML format.

Ques: Example: Fetching database data with AJAX and PHP

HTML/JS:

<script>
fetch("getUsers.php")
  .then(res => res.json())
  .then(data => console.log(data));
</script>

PHP:

<?php
$conn = new mysqli("localhost", "root", "", "test");
$result = $conn->query("SELECT * FROM users");
echo json_encode($result->fetch_all(MYSQLI_ASSOC));
?>

Ques: What are real-world examples of AJAX?

  • Live search (e.g., Google suggestions)
  • Auto-saving drafts
  • Chat applications
  • News feed updates
  • Form validation without reload
  • Weather widget updates

Ques: How is AJAX used in modern JavaScript frameworks?

Ans: Frameworks like React, Angular, and Vue use AJAX through:

  • fetch()
  • axios
  • Built-in HTTP clients

These libraries simplify handling requests, promises, and responses.

Ques: What’s the modern replacement for XMLHttpRequest?

Ans: The Fetch API — simpler, promise-based, and more readable.

Example:

fetch("data.json")
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.error(err));

Ques: What is synchronous vs asynchronous AJAX?

TypeDescriptionExample
Asynchronous (default)Doesn’t block other codexhr.open('GET', url, true)
SynchronousBlocks until response receivedxhr.open('GET', url, false) (deprecated)

Ques: Why is asynchronous AJAX preferred?

Ans: It prevents the browser from freezing while waiting for the server response, ensuring a smooth user experience.

Ques: What are the readyState and status codes used for in AJAX?

  • readyState = 4 → Request finished
  • status = 200 → OK
  • status = 404 → Not Found
  • status = 500 → Server Error

Ques: How do you handle JSON responses in AJAX?

xhr.onload = function() {
  let obj = JSON.parse(xhr.responseText);
  console.log(obj.message);
};

Q29. How can you debug AJAX calls?

  • Use browser DevTools → Network tab.
  • Check console logs and server response.
  • Handle onerror and HTTP status codes.

Ques: What is the role of the server in AJAX applications?

Ans: The server:

  • Processes the AJAX request
  • Interacts with databases or APIs
  • Sends back the response (in JSON/XML)

Article 0 of 0