Updating DOM element with AJAX returned Javascript code

Hey guys,

I want to update an element in my DOM that contains Javascript code when an action X is performed and an AJAX response generated with new Javascript code that is one of the AJAX response variables.

The AJAX request is successfully returned, as is the Javascript JSON response variable. However, I’m having no luck updating the DOM element containing the old JS code with the new JS code. I’m performing these operations using JQuery. Is what I need to do actually even possible?

Thanks,

Bardi

Okay, I’m still having some problems getting that to work as what you’ve suggested is pretty much what I was attempting. However I’m glad to know that that the problem lies elsewhere and is more specific to my JS code. I’ll look into this, and get back if I still can’t get anywhere. I do have one question though…

I’ve successfully managed to replace the JS code for the DOM element explicitly for debugging purposes by using the following code:

$('script#main').html( '$(function (){ alert(\\'hi\\');});' );

However once the DOM element is swapped, no alert is prompted. I’ve also tried…

$('script#main').html( 'alert(\\'hi\\')' );

… to no avail.

What would I need to do to ensure the alert is shown as soon as the content of <script id=‘main’ type=‘text/javascript’> is changed? Once again I’ll ask, is this possible even?

Basically the only way i know of without writing some fancy code would be to use jQuery’s getScript() which loads and executes the code function http://api.jquery.com/jQuery.getScript/

Once your Ajax query has been executed and a response returned simply do the following

$('#element-id').html(response);
<element id="element-id"></element>