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).

2

1 Answer 1

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('');
}
Sign up to request clarification or add additional context in comments.

6 Comments

i'm using javascript ajax call... not jquery ajax.. :(
If you are just using XHR objects then its just a little bit more complex, but still remains the same.
xhr.onreadystatechange = function() { if (xhr.readyState == 4) { alert(xhr.responseText); } }
thanks a lot @justin.. but am not clear with xhr objects. i use the normal ajax call given in link w3schools.com/ajax/tryit.asp?filename=tryajax_first
If you remove the <script> tags from the php script you can run eval() in JavaScript to run the code dynamically after your callback is complete. Or you can add it to the DOM. either way will work.
|

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.