0

Please read below my scenario… I have a PHP file wherein I have javascript within it..

 <?php
   echo ‘<script>’;
   echo ‘window.alert(“hi”)’;
   echo ‘</script>’;

 ?>

On execution of this file directly, the content inside the script is executed as expected. But if this same page is being called via ajax from another page, the script part is NOT executed. Can you please let me know the possible reasons. (note: I’m in a compulsion to have script within php page).

esqew
  • 42,425
  • 27
  • 92
  • 132
Samuel Mathews
  • 171
  • 1
  • 2
  • 17
  • 1
    possible duplicate of [Executing – Sean Aug 01 '14 at 18:03
  • There is also this one too: [Calling a javascript function returned from an ajax response](http://stackoverflow.com/questions/510779/calling-a-javascript-function-returned-from-an-ajax-response) – MSD Aug 01 '14 at 18:08

1 Answers1

1

When you do an AJAX call you just grab the content from that page. JavaScript treats it as a string (not code). You would have to add the content from the page to your DOM in your AJAX callback.

$.get('/alertscript.php', {}, function(results){
    $("html").append(results);
});

Make sure you change the code to fit your needs. I'm supposing you use jQuery...

Edited version

load('/alertscript.php', function(xhr) {    
    var result = xhr.responseText;  

    // Execute the code
    eval( result ); 

});



function load(url, callback) {
    var xhr;

    if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
    else {
        var versions = ["MSXML2.XmlHttp.5.0", 
            "MSXML2.XmlHttp.4.0",
            "MSXML2.XmlHttp.3.0", 
            "MSXML2.XmlHttp.2.0",
            "Microsoft.XmlHttp"]

        for(var i = 0, len = versions.length; i < len; i++) {
        try {
            xhr = new ActiveXObject(versions[i]);
            break;
        }
            catch(e){}
        } // end for
    }

    xhr.onreadystatechange = ensureReadiness;

    function ensureReadiness() {
        if(xhr.readyState < 4) {
            return;
        }

        if(xhr.status !== 200) {
            return;
        }

        // all is well  
        if(xhr.readyState === 4) {
            callback(xhr);
        }           
    }

    xhr.open('GET', url, true);
    xhr.send('');
}
Justin Workman
  • 380
  • 3
  • 6