-1

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

user3052975
  • 57
  • 10

1 Answers1

1

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();  
              }
rckrd
  • 3,124
  • 1
  • 13
  • 23
  • Tried this, undefined is gone but no data is shown from the (HTML) pages. – user3052975 Dec 21 '16 at 10:22
  • if it helps you can view the whole project here: http://spleric.com/test – user3052975 Dec 21 '16 at 10:26
  • Since you have declared `tmp` as a global variable and use `tmp.xhr` for all requests you will only get one result back. I have edited my answer and declared the `xhr` request as a local variable in the load function. You also have a typo in your test site, `tmp.xhr.readyState = XMLHttpRequest.DONE ` should be `===` – rckrd Dec 21 '16 at 10:46
  • Thanks alot, problem solved from your Genius work! – user3052975 Dec 21 '16 at 10:54