2

If I am correct, "A" in "AJAX" means sending a HTTP request asynchronously without waiting for a HTTP response.

I learn that we can send an asynchronous HTTP request by XMLHttpRequest, for example:

function handleButtonPress(e) { 
    var httpRequest = new XMLHttpRequest(); 
    httpRequest.onreadystatechange = handleResponse; 
    httpRequest.open("GET", e.target.innerHTML +  ".html"); 
    httpRequest.send(); 
} 

How can we send a HTTP request synchronously?

halfer
  • 19,824
  • 17
  • 99
  • 186
Tim
  • 1
  • 141
  • 372
  • 590
  • What use case do you have for synchronous requests? In general they are not recommended (certain browsers even state this in their console when a synchronous request is sent) – NielsNet May 03 '19 at 10:42
  • Just put `false` as the 3rd parameter to open, but a big warning, if you use this feature not inside a WebWorker it might stop working in the future. – Keith May 03 '19 at 10:42
  • I suppose the question is more about alternatives to XMLHttpRequest, no? – raina77ow May 03 '19 at 10:43
  • Possible duplicate of [JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."](https://stackoverflow.com/questions/24639335/javascript-console-log-causes-error-synchronous-xmlhttprequest-on-the-main-thr) – Jorge Fuentes González May 03 '19 at 10:46
  • @Keith Thanks. where do you recommend to look up the API usages? – Tim May 03 '19 at 11:18
  • @Tim MDN usually has good docs on stuff like this -> https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open – Keith May 03 '19 at 11:21

1 Answers1

5

The third param in open function is for async request sending. You can set it to false for a synchronous request

function handleButtonPress(e) { 
    var httpRequest = new XMLHttpRequest(); 
    httpRequest.onreadystatechange = handleResponse; 
    httpRequest.open("GET", e.target.innerHTML +  ".html", false); 
    httpRequest.send(); 
} 
Samir
  • 111
  • 4