-1
var response_var=""; // Added this line for debugging

ajax.onreadystatechange=function()
{
   if(ajax.readyState==4 & ajax.status==200)
   {
     response_var=(ajax.responseText);
     alert(ajax.responseText); // This alerts properly (some text).
     return (ajax.responseText); // This is returning as undefined
   }
}

return response_var; // This is empty if I add the line 1, if not in console it gives error response_var is not defined.

Why does not the response is getting stored in the variable or returned? I guess the scope of response_var ends within the onreadystatechange function so I tried return. But the value is undefined.

Mr Cathode
  • 73
  • 14

1 Answers1

0

Ajax function always work out of sync with normal code flow ,hence the name "Asynchronous JavaScript and XML" .For Ajax required events you should not rely on return ,rather do your task immediately when you get your response from AJAX.

Thi49
  • 358
  • 1
  • 11