Home / Questions / Coding Examples of Synchronous and Asynchronous AJAX
Explanatory Question

Coding Examples of Synchronous and Asynchronous AJAX

👁 102 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

Synchronous AJAX Example


var xhrSync = new XMLHttpRequest();
xhrSync.open('GET', 'example-url', false);
xhrSync.send();

// Process the response

Asynchronous AJAX Example


var xhrAsync = new XMLHttpRequest();
xhrAsync.open('GET', 'example-url', true);
xhrAsync.send();

// Process the response

Handling Responses


xhrAsync.onreadystatechange = function() {
  if (xhrAsync.readyState === 4 && xhrAsync.status === 200) {
    // Process the asynchronous response
    var responseData = xhrAsync.responseText;
  }
};