Do I understand well?

Hi,

I am not sure that I understood this code meaning :

req=new XMLHttpRequest();
req.open("POST",url,true);
req.setRequestHeader('Content-Type','text/plain');
req.onreadystatechange=function(){
  if(req.readyState==4 && req.status==200){
    document.getElementsByClassName('message')[0].innerHTML=req.responseText;
  }
};
req.send(userName);

As I read in the exercice Data Visualization Certification > “JSON APIs and Ajax: Post Data with the JavaScript XMLHttpRequest Method” : the if statement allow us to wait until "the operation is complete " and “the request is successful”. Which means we use the request in a synchronous way.
But the asynchronous use of the fonction is allowed by the 3rd argument of the “open” function (which is set to true).
Should’nt it have the same effect to edit this argument to “false” ?

I trully understand that the exercices are written with a didactic purpose, I just want to be sure to understand everything.

Thank you per advance :slight_smile:

Quoting from MDN: xmlHttpRequest.open:

Async
An optional Boolean parameter, defaulting to true , indicating whether or not to perform the operation asynchronously. If this value is false , the send() method does not return until the response is received. If true , notification of a completed transaction is provided using event listeners. This must be true if the multipart attribute is true , or an exception will be thrown.

To answer your question:

Should’nt it have the same effect to edit this argument to “false”

If you set the third parameter to false the send method will be blocking, means that any instruction after req.send(userName) won’t be executed until you receive a response; viceversa, if set to true, allow your code to continue its execution and when you receive a response it will be managed by the callback (which will be triggered in any case when the response is received)^^

Good luck on your learning path! :smile:

1 Like

Now I understand how I muddled up the asynchonous behavior and non-blocking behavior. I am glad that I asked for it :smiley:

Thank you so much @Layer for your complete and helpful answer.

Have a nice day :slightly_smiling_face:

1 Like