Page 1 of 1

Call javascript after xmlHttpRequest

Posted: Sun Nov 02, 2008 5:23 am
by invisibled
Hey there,

I'm relatively new to ajax, and i'm calling a php file with xhr. That works fine, but then im trying to add some javascript to the div that gets called up, but it doesn't seem to run any javascript i put in. This is the function that is being called.

Code: Select all

function alert_success($msg){
        
        print '<div id="alert_success" style="display:none;">';
            print '<img src="../lib/img/icons/success.png" alt="Success" />';
            print $msg;
        print '</div>';
        
        print '<a href="#" onClick="$(\'alert_success\').appear(); return false;">Show</a>';
        ?>
        
        <script type="text/javascript">
                $('alert_success').appear();    
        </script>
        
        <?php
    }
just a simple scriptaculous effect. The "show" link i just put there to test, and it show's the div fine. The code also works if i just call up the function on a page, not though XHR. So is there somthing i need to do to run the javascript or what? all suggestions apricated!

Re: Call javascript after xmlHttpRequest

Posted: Sun Nov 02, 2008 7:34 am
by kaszu
You need to use eval to execute javascript.

Re: Call javascript after xmlHttpRequest

Posted: Sun Nov 02, 2008 2:56 pm
by invisibled
Hey man,could you post an example? i can't seem to get it to work for me. Thanks

Re: Call javascript after xmlHttpRequest

Posted: Mon Nov 03, 2008 2:33 pm
by kaszu

Code: Select all

function evalJs(html_text) {
    var regex = /<script[^>]*>(.*?)<\/script>/ig;
    var result;
    while ((result = regex.exec(html_text)) != null) {
      eval(result[1])
    }
}
 
var html_text = '<a href="#">asd</a>' +
                '<script type="text/javascript">' +
                    'alert("x");' +
                '<\/script>' +
                '<p>COOL</p>' +
                '<script type="text/javascript">' +
                    'alert("y");' +
                '<\/script>';
                            
evalJs(html_text);