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?
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?
With jQuery I would do it using getScript
Just remember if you create a function the way below through ajax...
...and execute it via eval, you'll probably get a context problem. Take this as your callback function:
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:
But, I also think you shouldn't be doing this...
Sorry for any mistake here...
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
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
ajaxRequest.php
PHP side code Name of file class.sendCode.php
Now from your Html page you must trigger the ajax function to send the data.
Now at our local script.js we will define the ajax
This code work as well, instead eval the html i'm going to append the script to the head
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.
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):
And it works, at least in Internet Explorer 9 and Google Chrome.