Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript code being returned through ajax, but not displaying

So basically I am using jQuery post to do an ajax call to an external php page and then I echo out the result, and then display it on the actual page.

The problem is, whenever the external php page returns some javascript, it's not being displayed on the actual page.

Javascript being returned

<script type="text/javascript">z_media = "SQgeKL07Nr"; z_autoplay=false; z_width=899; z_height=506;</script><script type="text/javascript" src="http://www.zunux.com/static/js/embed.js"></script>

My jQuery

function videoGrabber(mirror_id, video_version, firstVideo_version, videoNumber) {


        jQuery.post("/path/to/my/external/php/file.php", {firstParam : mirror_id, secondParam : video_version, thirdParam : firstVideo_version}, function(data) {
            //this is your response data from serv
        console.log(data);
        jQuery('#videoContainer').html(data);

    });
        return false;
}

Now generally, when iframes are being returned, they are showing perfectly fine in the #videoContainer id, however, whenever that javascript embed code is being returned, it's not displaying anything in the #videoContainer id. But I can definitely confirm that the external php page is returning the data since I can see it in the console. So, how can I fix this?

like image 823
Maaz Avatar asked Nov 11 '22 22:11

Maaz


1 Answers

Try adding an eval() to actually run the Javascript code you're retrieving:

function videoGrabber(mirror_id, video_version, firstVideo_version, videoNumber) {
    jQuery.post("/path/to/my/external/php/file.php", {firstParam : mirror_id, secondParam : video_version, thirdParam : firstVideo_version}, function(data) {
        //this is your response data from serv
        console.log(data);
        jQuery('#videoContainer').html(data);
        eval(data);
    });
    return false;
}

BTW be sure you have good security-- eval() has a lot of potential for mayhem if someone can intercept the ajax call and inject their own code.

Oh, and since eval() is going to try to evaluate just Javascript code, you need to change your return code to just raw JS code (no <script> tags):

z_media = "SQgeKL07Nr"; z_autoplay=false; z_width=899; z_height=506;

The only other thing to deal with is this:

<script type="text/javascript" src="http://www.zunux.com/static/js/embed.js"></script>

Can you include that script in the calling page (the one with the ajax code), then trigger it from the code you get via ajax? So your ajax code would ultimately return something like:

z_media = "SQgeKL07Nr"; z_autoplay=false; z_width=899; z_height=506; triggerEmbedScript();
like image 151
Eric Avatar answered Nov 14 '22 22:11

Eric