Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest onreadystatechange called multiple times

Tags:

I am implementing a login system in php and using ajax requests.

this is my request

hr.open("POST", url, true); hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");  hr.onreadystatechange = function() {      var return_data = hr.responseText;     if(hr.readyState == 4 && hr.status == 200) {         alert('is logged');     }else if (hr.status == 400){         alert('is not logged');     } }   hr.send(vars); // Actually execute the request 

but when i get the response back the browser launches various alerts. Can anyone help how to fix this?

like image 658
pedrotorres Avatar asked Jan 13 '13 17:01

pedrotorres


1 Answers

Yeah its working as it should.......onreadystatechange may be called several times in one request.. And for alerting both the conditions is that whenever the request is okay that is 200.

It alerts :

'its not logged'

and when it got readystate=4 as well as Ok signal it alerts:

logged in.

Then

readyState =4 --> request finished and response is ready

status= 200 --> it means the request is successfully handled by the Server.

So, 2nd alert popup because at least your request was successfully handled. For more info: https://www.w3schools.com/js/js_ajax_http_response.asp

Here it is:

      xhrobj.onreadystatechange = function()     {       if (xhrobj.readyState == 4 && xhrobj.status == 200)       {         if (xhrobj.responseText)          {                 //put your code here             document.write(xhrobj.responseText);           }        }      }; 
like image 134
TaLha Khan Avatar answered Oct 22 '22 21:10

TaLha Khan