Search code examples
javascriptxmlhttprequest

XHR Request get content results 'undefined' without JQUERY


I want to get two separate pages as my header and footer via Javascript with Async.

WITHOUT JQuery.

Page Object:

load: function(v, cb) { 
        tmp.xhr = new XMLHttpRequest(); 
        tmp.xhr.open('GET', v, true); tmp.xhr.send();    
        tmp.xhr.onreadystatechange = function (e) { 
            if (tmp.xhr.readyState == 4 && tmp.xhr.status == 200) { 
               return tmp.xhr.responseText; cb(); 
            } 
        }  
      }

TPL Object:

appendTo: function(e, v) { document.getElementById(e).innerHTML = v; }

Both of these functions are located in DIFFERENT OBJECTS

and to call them:

tpl.appendTo('header', tpl.load(tmp.views + 'header_generic_2'));
tpl.appendTo('header', tpl.load(tmp.views + 'footer_generic'));

where tmp.views is a variable for the directory level only

On my web page I have the following content:

<div id='header'></div>
<div id='footer'></div>

and the result I get is:

<div id="header">undefined</div>
<div id="footer">undefined</div>

Picture of result:

Error given

and there are no console errors

BUT, the response is 200 and everything works according to Debug: https://gyazo.com/95dba118fe9eebdb310f617168c8d763 https://gyazo.com/e446b7db7f0a62c280273869eac4d04a


Solution

  • You need to call load with a callback

    tpl.load(tmp.views + 'header_generic_2',function(data){
      tpl.appendTo('header',data);
    });
    

    and pass the data back when it has been fetched.

    load: function(v, cb) { 
                    var xhr = new XMLHttpRequest(); 
                    xhr.open('GET', v, true);     
                    xhr.onreadystatechange = function (e) { 
                        if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) { 
                            cb(xhr.responseText); 
                        } 
                    }
                    xhr.send();  
                  }