Skip to content
Advertisement

JS snippet which is coming as an AJAX response not getting executed

I’ve a php page which returns a full-fledge js snippet when we query that page. Let say that page is get_js.php and looks something like this:

<?php
echo '<script>alert("hey");</script>';
?>

The ask here is that the value returned by that get_js.php should be executed on client side when we do an ajax call. The echo string above is just an example and can be any other js snippet like <script>document.getElementById("this_div_id_exists").style.display = "none";</script>.

The client side implementation is something like this:

$.ajax({
    url: 'get_js.php',
    type: 'POST',
    success: function(data) {
        document.getElementById("this_div_id_exists").innerHTML = data;
    }
});

If I check the Elements tab from DevTools, the data is appended inside the proper div.

PS: there’s no issue with retrieving the data as console.log works fine. And also guys this project is far from refactoring process, hence settling down the workaround.

Advertisement

Answer

Use eval()

$.ajax({
    url: 'get_js.php',
    type: 'POST',
    success: function(data) {
        document.getElementById("this_div_id_exists").innerHTML = data;
        // now loop through any script tags and eval() them
        document.querySelectorAll("#this_div_id_exists script").forEach(tag => eval(tag.innerHTML));
    }
});
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement