3

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.

3
  • You won't get an answer until you post some code so we know exactly what you're dealing with. Commented Sep 30, 2009 at 3:40
  • You need to add more information. Can you give us an example of the text/script returned? How are you currently trying to "execute the script"? Commented Sep 30, 2009 at 3:47
  • Sorry, you're going to have to include much more information than that. Commented Sep 30, 2009 at 4:11

5 Answers 5

2

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

Comments

1

If you are retrieving the JSON formatted result from AJAX call, you can just use eval to execute the javascript.

Assume, if the result json is formed like this

   var res =  '{"Data": "<something>",
              "script": "alert(something)"}';

   var out = eval("(" + res + ")");
   var data = out.data;
   eval(out.script);

2 Comments

This is probably a bad idea. I could easily send my own JSON that could contain malicious javascript and it would execute without problems...
@SpaDusA I would not recommend it to a beginner programmer but that's how JSON is handled. Using HTTPS will improve the security, but if all your accesses are to your server then your in control of the scripts sent to your clients.
1

Interestingly enough, I use jQuery and using the html() function was enough to get the JavaScript to execute. So more or less I had nothing special to do.

There is a simplified version:

var myform = $('form#form-id');
$.post(myform.attr('action'), myform.serialize(), function(response) {
  $('#some-id').html(response.message);
}

In my case the code kicked in automatically so I did not need any other of the solutions proposed here.

Comments

0

Not sure if you are using a library, but with Prototype I had to set

evalScripts: true

before JavaScript would be eval-ed. See here for more info:

http://www.sergiopereira.com/articles/prototype.js.html#UsingAjaxRequest

Comments

0

Using jQuery here is a simple bit of code:

$.ajax({
    type: "POST",
    url: "getData.asmx/HelloWorld",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(result) {
        alert(result);
    }
});

But, to actually use the results of the variable result I ended up using a javascript library, from http://www.json.org/js.html, I did:

success: function(result) {
    var myData = JSON.parse(result.d);

There are probably better approaches, but this was simple, and worked for me, so I just use this. Later, when the project is in production I may go back and clean this up, but that is after I get everything working.

Comments

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.