2

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.

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I have only one script tag one that page, but unfortunately your first solution with neither filter nor find will append it to head.
Sorry man, my mistake. There were multiple script tags so I had to use 2nd solution it works like a treat. Many many thanks for your help!!
0

Did you added quotes to string variables in javascript?

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

4 Comments

This isn't needed if you did var posts = <?php echo json_encode($x); ?>.
This also isn't needed if the value was a number: var posts = <?php echo $a/$b; ?>.
I wrote, only if string value.
This is not an issue as this cod works perfect on page itself. Issue is to execute it after loaded with AJAX. Thanks
0

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;
});

1 Comment

I assume there's more code in the <script> tag than just var posts = <?php .... ?>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.