Jump to content
Larry Ullman's Book Forums

Ajax's Onreadystatechange Return Uncaught Typeerror While Trying The Example In The Book


Recommended Posts

Uncaught TypeError: Cannot set property 'onreadystatechange' of undefined

    at window.onload (test.js:4). 

 

The above error message is what is displayed on the console while trying to run the ajax example on page 433 of the book. What can be done to rectify it? Any clue or answer will be appreciated.

Link to comment
Share on other sites

getXMLHttpRequestObject returns nothing, which means it returns undefined. The ajax variable inside that function is not the same as the one outside. So I have to return variable ajax at the end of both functions.

 

window.onload = function(){

     'use strict';
     var ajax = getXMLHttpRequestObject();
     ajax.onreadystatechange = function(){
         if(ajax.readyState == 4){
             if((ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304)){
 

                 document.getElementById('output').innerHTML = ajax.responseText;
             }else{
                 document.getElementById('output').innerHTML = 'Error ' + ajax.statusText;
             }
         }
     };
         document.getElementById('btn').onclick = function(){
         ajax.open('GET', 'resources/test.txt', true);
         ajax.send(null);
     };

     //return var ajax
     **return ajax;**
 }
 function getXMLHttpRequestObject(){
     var ajax = null;
     if(window.XMLHttpRequest){
         ajax = new XMLHttpRequest();
     }else if(window.ActiveXObject){
         ajax = new ActiveXObject('MSXML2.XMLHTTP.3.0');
     }

     //return var ajax
     **return ajax**
}

Link to comment
Share on other sites

 Share

×
×
  • Create New...