Call javascript after xmlHttpRequest

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
invisibled
Forum Contributor
Posts: 112
Joined: Sun Apr 29, 2007 3:35 pm
Location: New Westminster

Call javascript after xmlHttpRequest

Post 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!
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Re: Call javascript after xmlHttpRequest

Post by kaszu »

You need to use eval to execute javascript.
invisibled
Forum Contributor
Posts: 112
Joined: Sun Apr 29, 2007 3:35 pm
Location: New Westminster

Re: Call javascript after xmlHttpRequest

Post by invisibled »

Hey man,could you post an example? i can't seem to get it to work for me. Thanks
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Re: Call javascript after xmlHttpRequest

Post 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);
Post Reply