Brett Gregson
Brett Gregson

Reputation: 5913

JavaScript not executing on Ajax loaded content (no jQuery)

I am having an issue where I am loading ajax HTML content into an element on my page using JavaScript, and trying to execute JavaScript within the loaded content, which is not working.

I am not (and cannot) use jQuery on this project.

The JavaScript I am using to load the ajax content look like:

var loadedobjects = "";
var rootDomain = "http://" + window.location.hostname;

function ajaxPage(url, containerId){
    var pageRequest = false;
    pageRequest = new XMLHttpRequest();

    pageRequest.onreadystatechange = function(){
        loadpage(pageRequest, containerId);
    }

    preventCache = (url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime();
    pageRequest.open('GET', url+preventCache, true);
    pageRequest.send(null);
}

function loadpage(pageRequest, containerId){
    if (pageRequest.readyState == 4 && (pageRequest.status==200 || window.location.href.indexOf("http") == -1)){
        document.getElementById(containerId).innerHTML = pageRequest.responseText;
    }
}

As you can see, I am passing a URL (of an HTML page) to the function ajaxPage()

The ajaxPage() function is being called in a separate .js file, like so:

ajaxPage('test.html', 'ajax-wrapper');

Which is working, test.html is being loaded in the element with id 'ajax-wrapper', but no JavaScript in the test.html page is working.

Here is what the test.html page looks like (just plain HTML):

<div class="t-page-title">
    View Thread
</div>

<script>
    alert('hello');
</script>

Even a simple alert('hello'); on the loaded HTML is not firing. The page is not being cached, so that is not the issue. I would know what to do if I was using jQuery, but I am a bit stumped with finding a JavaScript only solution. Any suggestions?

Upvotes: 0

Views: 1074

Answers (1)

Christophe
Christophe

Reputation: 28114

When you use innerHTML, the tags get copied to the destination element, but scripts are not executed. You need an additional eval step to execute the scripts.

jQuery has a function for that called globalEval, without jQuery you'll need to write your own.

[Update] Here is a variation with an iframe that might help address your issue: http://jsfiddle.net/JCpgY/

In your case:

ifr.src="javascript:'"+pageRequest.responseText+"'";

The standard behavior with a div: http://jsfiddle.net/JCpgY/1/

Upvotes: 1

Related Questions