Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to execute ajax output script

I'm getting an ajax output success data.

Where the data contains some html text and a script.

But the script is not executing, how can I execute the script.

Let's say Ajax response obj is

<div>something....</div><script>alert("test");</script>

the above code is my Ajax response.The div is getting rendered, but the alert is not working.

like image 686
Santhosh Avatar asked Jan 30 '26 04:01

Santhosh


1 Answers

Assuming you are not using JSON or jQuery, or any other library, and your AJAX call returns some HTML and/or javascript which is being added to your existing document (eg. using innerHTML), any javascript returned using AJAX will not execute in the browser - except for events on elements in the HTML.

So if your AJAX call returns <input type="button" value="Click me" onclick="alert('hello');" />, the js alert will work ok, but if your AJAX call returns <script type="text/javascript">alert('hello');</script> it will not execute. In that case, you would have to parse the result to extract the javascript and execute it, using a function such as this:

function extract_and_execute_js(output_to_parse)
{    
    if(output_to_parse != '')    
    {    
        var script = "";
        output_to_parse = output_to_parse.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(){if (output_to_parse !== null) script += arguments[1] + '\n';return '';});
        if(script) 
        {
            if (window.execScript)
            {
                window.execScript(script);
            }
            else
            {
                window.setTimeout(script, 0);
            }
        }
    }
}
like image 83
Russ Avatar answered Feb 01 '26 18:02

Russ