69

I have a system where I send an Ajax command, which returns a script block with a function in it. After this data is correctly inserted in the DIV, I want to be able to call this function to perform the required actions.

Is this possible?

18 Answers 18

75

I think to correctly interpret your question under this form: "OK, I'm already done with all the Ajax stuff; I just wish to know if the JavaScript function my Ajax callback inserted into the DIV is callable at any time from that moment on, that is, I do not want to call it contextually to the callback return".

OK, if you mean something like this the answer is yes, you can invoke your new code by that moment at any time during the page persistence within the browser, under the following conditions:

1) Your JavaScript code returned by Ajax callback must be syntactically OK;
2) Even if your function declaration is inserted into a <script> block within an existing <div> element, the browser won't know the new function exists, as the declaration code has never been executed. So, you must eval() your declaration code returned by the Ajax callback, in order to effectively declare your new function and have it available during the whole page lifetime.

Even if quite dummy, this code explains the idea:

<html>
    <body>
        <div id="div1">
        </div>
        <div id="div2">
            <input type="button" value="Go!" onclick="go()" />
        </div>
        <script type="text/javascript">
            var newsc = '<script id="sc1" type="text/javascript">function go() { alert("GO!") }<\/script>';
            var e = document.getElementById('div1');
            e.innerHTML = newsc;
            eval(document.getElementById('sc1').innerHTML);
        </script>
    </body>
</html>

I didn't use Ajax, but the concept is the same (even if the example I chose sure isn't much smart :-)

Generally speaking, I do not question your solution design, i.e. whether it is more or less appropriate to externalize + generalize the function in a separate .js file and the like, but please take note that such a solution could raise further problems, especially if your Ajax invocations should repeat, i.e. if the context of the same function should change or in case the declared function persistence should be concerned, so maybe you should seriously consider to change your design to one of the suggested examples in this thread.

Finally, if I misunderstood your question, and you're talking about contextual invocation of the function when your Ajax callback returns, then my feeling is to suggest the Prototype approach described by krosenvold, as it is cross-browser, tested and fully functional, and this can give you a better roadmap for future implementations.

4
  • 1
    This works in the example because everything is in the same page and timing doesn't come into play. It doesn't work with anything that actually utilizes AJAX methodologies to call external files for processing because the eval() function runs before the external process has any time to return with a response.
    – Typel
    Oct 9, 2015 at 18:49
  • Superb answer really save my time. God bless you.
    – Manish
    Dec 22, 2016 at 15:05
  • @Typel Any security risks of using eval() here?
    – Anupam
    Apr 19, 2017 at 9:52
  • 1
    @Anupam I think the general consensus is that eval() always has security risks associated with it - I would be be mindful how and if it gets used. Personally, I wouldn't use it in conjunction with AJAX to avoid opening any XSS vulnerabilities. In most cases if I need a function to execute from an AJAX return, I would just pass the arguments back instead and let the meat of the function reside in and execute from the calling page instead (or something similar).
    – Typel
    Apr 20, 2017 at 16:20
42

Note: eval() can be easily misused, let say that the request is intercepted by a third party and sends you not trusted code. Then with eval() you would be running this not trusted code. Refer here for the dangers of eval().


Inside the returned HTML/Ajax/JavaScript file, you will have a JavaScript tag. Give it an ID, like runscript. It's uncommon to add an id to these tags, but it's needed to reference it specifically.

<script type="text/javascript" id="runscript">
    alert("running from main");
</script>

In the main window, then call the eval function by evaluating only that NEW block of JavaScript code (in this case, it's called runscript):

eval(document.getElementById("runscript").innerHTML);

And it works, at least in Internet Explorer 9 and Google Chrome.

5
  • Amazing, been trying to figure this out for a while +1
    – mwild
    May 8, 2015 at 14:26
  • I've been trying to solve this for hours and just came across this answer! This is awesome and should probably be the accepted! Thank you, +1 :) May 26, 2015 at 13:12
  • 4
    Is there any security hole in implementing this solution? Jul 3, 2015 at 9:16
  • Still actual in 2018: This sounds dangerously like "Security by obscurity". If I was attacking your site and noticed that eval() function, then I would surely notice the ID tag there and modify my attack to just insert the malicios code inside your <script id="my-secure-id"> tag. I do not see any added security by using this solution. In fact, it only gives you the false sense of security, which is even more dangerous. But some 6 years later, HTTPS is now very much more common. I beleive that an attack on eval() should not be possible over secure HTTPS. Am I wrong assuming that? Oct 14, 2018 at 13:12
  • Obviously eval is dangerous in some contexts, but if someone were to intercept your code assuming your not running over ssl and inject some code into eval is there any legitimate reason why they couldn't do the same thing if your response return HTML which is inserted into the DOM (they can just add a script tag to it). It seems to me that running eval on a response from the server has the same security implications as the server giving you HTML that you insert into the DOM. Perhaps there is some difference though.
    – Joel M
    Jan 11, 2020 at 20:53
9

It is fully possible, and there are even some fairly legitimate use cases for this. Using the Prototype framework it's done as follows.

new Ajax.Updater('items', '/items.url', {
    parameters: { evalJS: true}
});

See documentation of the Ajax updater. The options are in the common options set. As usual, there are some caveats about where "this" points to, so read the fine print.

The JavaScript code will be evaluated upon load. If the content contains function myFunc(), you could really just say myFunc() afterwards. Maybe as follows.

if (window["myFunc"])
   myFunc()

This checks if the function exists. Maybe someone has a better cross-browser way of doing that which works in Internet Explorer 6.

1
  • This is aweome! Thanks! I've always used the "onSuccess" function on the updater to eval the Javascript manually. But this is more readable and works in all browser. May 8, 2015 at 9:24
6

That seems a rather weird design for your code - it generally makes more sense to have your functions called directly from a .js file, and then only retrieve data with the Ajax call.

However, I believe it should work by calling eval() on the response - provided it is syntactically correct JavaScript code.

5

With jQuery I would do it using getScript

3

Just remember if you create a function the way below through ajax...

function foo()
{
    console.log('foo');
}

...and execute it via eval, you'll probably get a context problem. Take this as your callback function:

function callback(result)
{
    responseDiv = document.getElementById('responseDiv');
    responseDiv.innerHTML = result;
    scripts = responseDiv.getElementsByTagName('script');
    eval(scripts[0]);
}

You'll be declaring a function inside a function, so this new function will be accessible only on that scope.

If you want to create a global function in this scenario, you could declare it this way:

window.foo = function ()
{
    console.log('foo');
};

But, I also think you shouldn't be doing this...

Sorry for any mistake here...

3

I would like to add that there's an eval function in jQuery allowing you to eval the code globally which should get you rid of any contextual problems. The function is called globalEval() and it worked great for my purposes. Its documentation can be found here.

This is the example code provided by the jQuery API documentation:

function test()
{
  jQuery.globalEval("var newVar = true;")
}

test();
// newVar === true

This function is extremely useful when it comes to loading external scripts dynamically which you apparently were trying to do.

2

A checklist for doing such a thing:

  1. the returned Ajax response is eval(ed).
  2. the functions are declared in form func_name = function() {...}

Better still, use frameworks which handles it like in Prototype. You have Ajax.updater.

2

PHP side code Name of file class.sendCode.php

<?php
class  sendCode{ 

function __construct($dateini,$datefin) {

            echo $this->printCode($dateini,$datefin);
        }

    function printCode($dateini,$datefin){

        $code =" alert ('code Coming from AJAX {$this->dateini} and {$this->datefin}');";
//Insert all the code you want to execute, 
//only javascript or Jquery code , dont incluce <script> tags
            return $code ;
    }
}
new sendCode($_POST['dateini'],$_POST['datefin']);

Now from your Html page you must trigger the ajax function to send the data.

....  <script src="http://code.jquery.com/jquery-1.9.1.js"></script> ....
Date begin: <input type="text" id="startdate"><br>
Date end : <input type="text" id="enddate"><br>
<input type="button" value="validate'" onclick="triggerAjax()"/>

Now at our local script.js we will define the ajax

function triggerAjax() {
    $.ajax({
            type: "POST",
            url: 'class.sendCode.php',
            dataType: "HTML",
            data : {

                dateini : $('#startdate').val(),
                datefin : $('#enddate').val()},

                  success: function(data){
                      $.globalEval(data);
// here is where the magic is made by executing the data that comes from
// the php class.  That is our javascript code to be executed
                  }


        });
}
1

This code work as well, instead eval the html i'm going to append the script to the head

function RunJS(objID) {
//alert(http_request.responseText);
var c="";
var ob = document.getElementById(objID).getElementsByTagName("script");
for (var i=0; i < ob.length - 1; i++) {
    if (ob[i + 1].text != null) 
       c+=ob[i + 1].text;
}
var s = document.createElement("script");
s.type = "text/javascript";
s.text = c;
document.getElementsByTagName("head")[0].appendChild(s);
}
1

My usual ajax calling function:

function xhr_new(targetId, url, busyMsg, finishCB)
{
    var xhr;

    if(busyMsg !== undefined)
        document.getElementById(targetId).innerHTML = busyMsg;

    try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); }
    catch(e)
    {
        try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
        catch(e2)
        {
            try { xhr = new XMLHttpRequest(); }
            catch(e3) { xhr = false; }
        }
    }

    xhr.onreadystatechange = function()
    {
        if(xhr.readyState == 4)
        {
            if(xhr.status == 200)
            {
                var target = document.getElementById(targetId)
                target.innerHTML = xhr.responseText;
                var scriptElements = target.getElementsByTagName("script");
                var i;
                for(i = 0; i < scriptElements.length; i++)
                    eval(scriptElements[i].innerHTML);
                if(finishCB !== undefined)
                    finishCB();
            }
            else
                document.getElementById(targetId).innerHTML = 'Error code: ' + xhr.status;
        }
    };

    xhr.open('GET', url, true);
    xhr.send(null);
    // return xhr;
}

Some explanation:
targetId is an (usually div) element ID where the ajax call result text will goes.
url is the ajax call url.
busyMsg will be the temporary text in the target element.
finishCB will be called when the ajax transaction finished successfully.
As you see in the xhr.onreadystatechange = function() {...} all of the <script> elements will be collected from the ajax response and will be run one by one. It appears to work very well for me. The two last parameter is optional.

0

I've tested this and it works. What's the problem? Just put the new function inside your javascript element and then call it. It will work.

0

This does not sound like a good idea.

You should abstract out the function to include in the rest of your JavaScript code from the data returned by Ajax methods.

For what it's worth, though, (and I don't understand why you're inserting a script block in a div?) even inline script methods written in a script block will be accessible.

1
  • He is not asking weather or not is a good idea, he is asking if it is possible
    – alvaroc
    Mar 1, 2021 at 16:36
0

I tried all the techniques offered here but finally the way that worked was simply to put the JavaScript function inside the page / file where it is supposed to happen and call it from the response part of the Ajax simply as a function:

...
}, function(data) {
    afterOrder();
}

This Worked on the first attempt, so I decided to share.

0

I solved this today by putting my JavaScript at the bottom of the response HTML.

I had an AJAX request that returned a bunch of HTML that was displayed in an overlay. I needed to attach a click event to a button in the returned response HTML/overlay. On a normal page, I would wrap my JavaScript in a "window.onload" or "$(document).ready" so that it would attach the event handler to the DOM object after the DOM for the new overlay had been rendered, but because this was an AJAX response and not a new page load, that event never happened, the browser never executed my JavaScript, my event handler never got attached to the DOM element, and my new piece of functionality didn't work. Again, I solved my "executing JavaScript in an AJAX response problem" by not using "$(document).ready" in the head of the document, but by placing my JavaScript at the end of the document and having it run after the HTML/DOM had been rendered.

0

If your AJAX script takes more than a couple milliseconds to run, eval() will always run ahead and evaluate the empty response element before AJAX populates it with the script you're trying to execute.

Rather than mucking around with timing and eval(), here is a pretty simple workaround that should work in most situations and is probably a bit more secure. Using eval() is generally frowned upon because the characters being evaluated as code can easily be manipulated client-side.

Concept

  1. Include your javascript function in the main page. Write it so that any dynamic elements can be accepted as arguments.
  2. In your AJAX file, call the function by using an official DOM event (onclick, onfocus, onblur, onload, etc.) Depending on what other elements are in your response, you can get pretty clever about making it feel seamless. Pass your dynamic elements in as arguments.
  3. When your response element gets populated and the event takes place, the function runs.

Example

In this example, I want to attach a dynamic autocomplete list from the jquery-ui library to an AJAX element AFTER the element has been added to the page. Easy, right?

start.php

<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<!-- these libraries are for the autocomplete() function -->
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/ui-lightness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript">
<!--
// this is the ajax call
function editDemoText(ElementID,initialValue) {
    try { ajaxRequest = new XMLHttpRequest();
    } catch (e) {
    try { ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
    try { ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) {
    return false;
    }}}
    ajaxRequest.onreadystatechange = function() {
        if ( ajaxRequest.readyState == 4 ) {
            var ajaxDisplay = document.getElementById('responseDiv');
            ajaxDisplay.innerHTML = ajaxRequest.responseText;
            }
        }
    var queryString = "?ElementID="+ElementID+"&initialValue="+initialValue;
    ajaxRequest.open("GET", "ajaxRequest.php"+queryString, true);
    ajaxRequest.send(null);
    }

// this is the function we wanted to call in AJAX, 
// but we put it here instead with an argument (ElementID)
function AttachAutocomplete(ElementID) {
    // this list is static, but can easily be pulled in from 
    // a database using PHP. That would look something like this:
    /*
     * $list = "";
     * $r = mysqli_query($mysqli_link, "SELECT element FROM table");
     * while ( $row = mysqli_fetch_array($r) ) {
     *    $list .= "\".str_replace('"','\"',$row['element'])."\",";
     *    }
     * $list = rtrim($list,",");
     */
    var availableIDs = ["Demo1","Demo2","Demo3","Demo4"];
    $("#"+ElementID).autocomplete({ source: availableIDs });
    }
//-->
</script>
</head>
<body>
<!-- this is where the AJAX response sneaks in after DOM is loaded -->
<!-- we're using an onclick event to trigger the initial AJAX call -->
<div id="responseDiv"><a href="javascript:void(0);" onclick="editDemoText('EditableText','I am editable!');">I am editable!</a></div>
</body>
</html>

ajaxRequest.php

<?php
// for this application, onfocus works well because we wouldn't really 
// need the autocomplete populated until the user begins typing
echo "<input type=\"text\" id=\"".$_GET['ElementID']."\" onfocus=\"AttachAutocomplete('".$_GET['ElementID']."');\" value=\"".$_GET['initialValue']."\" />\n";
?>
0

I needed to get something to do this, I find that this has worked for a long time for me, just posting this here as one of many solutions, I like to have solutions without jQuery and the following function may help you, you can pass the full html with script tags in and it will parse and execute.

function parseScript(_source) {
    var source = _source;
    var scripts = new Array();

    // Strip out tags
    while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
        var s = source.indexOf("<script");
        var s_e = source.indexOf(">", s);
        var e = source.indexOf("</script", s);
        var e_e = source.indexOf(">", e);

        // Add to scripts array
        scripts.push(source.substring(s_e+1, e));
        // Strip from source
        source = source.substring(0, s) + source.substring(e_e+1);
        }

        // Loop through every script collected and eval it
        for(var i=0; i<scripts.length; i++) {
        try {
        if (scripts[i] != '')
        {
        try  {          //IE
            execScript(scripts[i]);
        }
        catch(ex)           //Firefox
        {
            window.eval(scripts[i]);
        }

        }
        }
        catch(e) {
           // do what you want here when a script fails
           if (e instanceof SyntaxError) console.log (e.message+' - '+scripts[i]);
        }
        }
        // Return the cleaned source
        return source;
}
-1

Federico Zancan's answer is correct but you don't have to give your script an ID and eval all your script. Just eval your function name and it can be called.

To achieve this in our project, we wrote a proxy function to call the function returned inside the Ajax response.

function FunctionProxy(functionName){
    var func = eval(functionName);
    func();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.