SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Zealot
    Join Date
    Jan 2004
    Location
    Manchester
    Posts
    132
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,191
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Once your Ajax query has been executed and a response returned simply do the following

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

  3. #3
    SitePoint Zealot
    Join Date
    Jan 2004
    Location
    Manchester
    Posts
    132
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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:

    Code:
    $('script#main').html( '$(function (){ alert(\'hi\');});' );
    However once the DOM element is swapped, no alert is prompted. I've also tried..

    Code:
    $('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?

  4. #4
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,191
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    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/


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •