daniel.tosaba
daniel.tosaba

Reputation: 2563

execute ajax loaded javascript code

I am loading piece of page that contains some javascript code as well, and $.getScript() approach wont work here as some of the javascript code is dynamically build through php.

<div id="fetch-me">
...
<script...>
var posts = <?php .... ?> 
...
</script>
</div>

As you might be familiar with this kind of issue, once I load this div with:

$("#load-me").load("... #fetch-me"); 

Javascript is not usable. I need to execute obviously. And I've tried few things but with no success. As an example this:

$("#load-me").load("... #fetch-me", function(){
 eval($("#load-me").find("script").text());
}); 

Any help appreciated, thanks.

Upvotes: 2

Views: 823

Answers (3)

Ram&#243;n
Ram&#243;n

Reputation: 21

You can do it like this:

$.get("page.php", function(data){
    //data is the information that page.php returns
    //Now instead of use this --> var posts = <?php .... ?>
    //do this:
    var post = data;
});

Upvotes: 0

gen_Eric
gen_Eric

Reputation: 227240

load will return you the data it loaded in its callback. Try to get the script(s) and append them to a <script> tag.

$("#load-me").load("... #fetch-me", function(data){
    $('<script>').html($(data).filter('script').html()).appendTo('head');
});

If there are multiple script tags in the loaded page, that may not work. If that's the case, try this:

$("#load-me").load("... #fetch-me", function(data){
    $(data).filter('script').each(function(){
        $('<script>').html($(this).html()).appendTo('head');
    });
});

P.S. If this doesn't work, try changing .filter to .find.

Upvotes: 1

Meliborn
Meliborn

Reputation: 6645

Did you added quotes to string variables in javascript?

var posts = "<?php .... ?>" 

Upvotes: 0

Related Questions