www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 16

Thread: Javascript won't initiate after being loaded into div

Hybrid View

  1. #1
    Join Date
    Dec 2008
    Posts
    5

    Javascript won't initiate after being loaded into div

    I am working to create a more dynamic way to view speaker information for a conference. I initially developed this, a page that basically has two iframes in which i basically pull queries from our database. One iframe contains a list of links; you click on the links, and it will pass on a query string to the second iframe and put all the info into an accordion menu. I really don't like using iframes, and especially hate how it cuts off the content and sticks in a scrollbar if it's just slightly too long. I wanted something more fluid looking and set out to dynamically insert the asp results directly into a div.

    At first I tried using an XMLHttpRequest, and while i managed to get the content to successfully load into the div, it for some reason disabled the javascript command that initiated the accordion menu.

    I tried moving the initiate command from the bottom of the asp page where i actually create the accordion menu to the referencing url (from the first iframe). I also tried using the timeout feature in the referencing url, and that didn't work. I tried having it initialize from the XMLHttpRequest function, and that didn't work either. I tried loading it into an html panel instead, and while it still loaded, the javascript was still disabled. Also, the javascript will work if you run it manually from the url bar in the browser after the page has loaded. Oddly enough, when i added an alert to the accordion menu javascript file, then the accordion menu started working. You can see almost all my files with firebug.

    I am not a developer or coder. The code for the accordion menu and the html panel came from Adobe templates and the idea for the XMLHttpRequest came from w3schools. I'm a graphic designer who's just trying to pick this stuff as I go along, so please be specific and as non-hypothetical as possible.

    Please help!! I've pretty much spent two solid days trying to figure this out. I have no idea what's going on and have run out of developer friends to pester.

  2. #2
    Join Date
    Feb 2003
    Location
    Michigan, USA
    Posts
    5,773
    Are you loading it into the DIV by assigning a string of HTML text to the DIV tag's innerHTML property? If doing this, SCRIPTs won't execute. I'd say assign the HTML text to the innerHTML property, then do a div.getElementsByTagName("script"), loop through the resulting list and eval() the innerHTML of the script tags.

    Some JavaScript libraries automatically evaluate JavaScript when it's inserted into the DOM using the innerHTML property.

  3. #3
    Join Date
    Dec 2008
    Posts
    5
    Thanks so much for responding!

    I'm not sure I totally understand what you mean though.

    For the XMLHttpRequest method I tried, I made the url a variable and then put that in js function. So, I basically have:
    <a onclick="loadXMLDoc('session_list.asp?id=25'); " href="#">Bob's Info</a>

    Code:
    function loadXMLDoc(url){
    xmlhttp.onreadystatechange=state_Change;
    xmlhttp.open("GET",url,true)
    xmlhttp.send(null);
    }
    function state_Change(){
    document.getElementById('col_2').innerHTML=xmlhttp.responseText;
    }
    How is this different than what you are talking about?

    I also tried changing it to <a onclick="loadXMLDoc('session_list.asp?id=25'); var Accordion1 = new Spry.Widget.Accordion(Accordion1);" href="#">Bob's Info</a>. I also tried adding the initiation line to
    Code:
    function state_Change(){
    document.getElementById('col_2').innerHTML=xmlhttp.responseText;
    var Accordion1 = new Spry.Widget.Accordion(Accordion1);
    }
    What is eval()? I don't have that function listed anywhere.

    I tried loading it an html panel, which I think has the settings you are referring to because I saw something about enabling eval scripting, which I thought I did based on the comments in the template, but honestly, the javascript file I used for that is a template with 400+ lines of code and I only vaguely understood about 40% of what was going on in it.

  4. #4
    Join Date
    Feb 2003
    Location
    Michigan, USA
    Posts
    5,773
    Code:
    function loadXMLDoc(url){
      xmlhttp.onreadystatechange=state_Change;
      xmlhttp.open("GET",url,true)
      xmlhttp.send(null);
    }
    function state_Change(){
      document.getElementById('col_2').innerHTML=xmlhttp.responseText;
    }
    Since you are putting the responseText into the HTML tag using the innerHTML property, any JavaScript inside <script> tags injected into the HTML tag won't get executed.

    This HTML tag below:
    HTML Code:
    <a onclick="loadXMLDoc('session_list.asp?id=25'); " href="#">Bob's Info</a>
    Is that HTML part of the responseText you are injecting into the web page using AJAX, or is that a link that already exists on the page, which then calls AJAX?

    Just trying to get a grasp on the workflow.

  5. #5
    Join Date
    Dec 2008
    Posts
    5
    It's a link that already exists on the page, which then calls the ajax to load into the div.

    So my javascript won't execute because i'm using the innerHTML thing? Why won't it work even when I included the initiate command in the referencing url?
    <a onclick="loadXMLDoc('session_list.asp?id=25'); var Accordion1 = new Spry.Widget.Accordion(Accordion1);" href="#">Bob's Info</a>

    Is there another way to execute it?

    Thanks so much!!!

  6. #6
    Join Date
    Feb 2003
    Location
    Michigan, USA
    Posts
    5,773
    You'll need to execute the Spry.Widget.Accordion code in the AJAX callback function that executes once the AJAX call has run its course, and after the new HTML text was assigned to the innerHTML property.
    Last edited by toicontien; 12-20-2008 at 06:39 PM.

  7. #7
    Join Date
    Mar 2009
    Posts
    6
    Sorry to bring up an old thread, but I'm running into the same problem. My Javascript will not execute in the external php page and I can't figure out a way around it. I can post my code if needed. Any help is much appreciated.

    Quote Originally Posted by toicontien View Post
    You'll need to execute the Spry.Widget.Accordion code in the AJAX callback function that executes once the AJAX call has run its course, and after the new HTML text was assigned to the innerHTML property.

  8. #8
    Join Date
    Feb 2003
    Location
    Michigan, USA
    Posts
    5,773
    Basically, do not use <script> tags in HTML source code returned in an AJAX call if that HTML source code is injected into the document object model by using the innerHTML property of a DOM node. If you want to attach event handlers to HTML tags returned from an AJAX call and then inserted via innerHTML, you need to move that JavaScript to the AJAX callback function.

    Wrong:
    Code:
    <!-- HTML returned in AJAX call and inserted using innerHTML -->
    
    <a href="" id="mylink">Click me!</a>
    
    <script type="text/javascript">
    document.getElementById("mylink").onclick = function() {
      alert("Clicked!");
    };
    </script>
    Right
    Code:
    // JavaScript to make AJAX call:
    var xhr = createRequest();
    
    // Initialization code goes here ...
    xhr.onreadystatechange = function () {
      if ( /* test to make sure AJAX request is complete */ ) {
        var div = document.getElementById("mydiv");
        div.innerHTML = this.responseText;
        document.getElementById("mylink").onclick = function() {
          alert("Clicked!");
        };
      }
    };
    xhr.send(); // Send the AJAX request
    Code:
    <!-- HTML returned in AJAX call and inserted using innerHTML -->
    
    <a href="" id="mylink">Click me!</a>

  9. #9
    Join Date
    Mar 2009
    Posts
    6
    Thank you for the quick response, but I'm not sure I understand. Here's a part of my my external file, basically it talks to our database and based on a few variables builds a form. It's a report module so these forms can have different number of input boxes (Spry widgets) which are suppose to validate.

    Code:
    foreach ($ReportParams as $Row3)
        { 
            $ParamNames .= trim($Row3->DbField). "~";
            ?>
            <tr>
            <td width="159" nowrap><?php echo trim($Row3->DisplayColumnName); ?></td>
            <td width="28" nowrap><?php echo trim($Row3->ParameterDefault); ?></td>
            <td width="383">
            <span id="sprytextfield<?php echo $Row3->SystemReportFilterSid; ?>">
            <input type="text" name="<?php echo trim($Row3->DbField); ?>" id="<?php echo trim($Row3->DbField); ?>" value="<?php echo trim($Row3->DefaultFill); ?>" />
            <span class="textfieldRequiredMsg">A value is required.</span></span>
            </td>
            </tr>
            <script language="Javascript" type="text/javascript">
            <!--
            var sprytextfield<?php echo $Row3->SystemReportFilterSid ?> = new Spry.Widget.ValidationTextField("sprytextfield<?php echo $Row3->SystemReportFilterSid ?>", "none");
            //-->
            </script>
    <?php }
    I don't think the Javascript gets executed in that foreach statement. I tried writing a onsubmit function but that didn't work either.

  10. #10
    Join Date
    Mar 2009
    Posts
    6
    Is there a different way of inserting the content other than innerHTML?

  11. #11
    Join Date
    Feb 2003
    Location
    Michigan, USA
    Posts
    5,773
    You can use purely DOM methods, like document.createElement and *.appendChild, however innerHTML is by far the most efficient. If you know the HTML tag which gets the innerHTML, you can grab references to all the SCRIPT tags and eval their innerHTML, which then causes the JavaScript to execute:
    Code:
    function evalScripts(el) {
      var scripts = el.getElementsByTagName("script");
      var i = 0;
      var end = scripts.length;
      
      for (i; i < end; i++) {
        eval( scripts[i].innerHTML );
      }
      
      scripts = null;
    }
    And to use:
    Code:
    // xhr is XMLHttpRequest object
    
    mydiv.innerHTML = xhr.responseText;
    
    evalScripts(mydiv);

  12. #12
    Join Date
    Mar 2009
    Posts
    6
    Wow, that definitely did the trick!! Thank you so much for the help.


    Quote Originally Posted by toicontien View Post
    You can use purely DOM methods, like document.createElement and *.appendChild, however innerHTML is by far the most efficient. If you know the HTML tag which gets the innerHTML, you can grab references to all the SCRIPT tags and eval their innerHTML, which then causes the JavaScript to execute:
    Code:
    function evalScripts(el) {
      var scripts = el.getElementsByTagName("script");
      var i = 0;
      var end = scripts.length;
      
      for (i; i < end; i++) {
        eval( scripts[i].innerHTML );
      }
      
      scripts = null;
    }
    And to use:
    Code:
    // xhr is XMLHttpRequest object
    
    mydiv.innerHTML = xhr.responseText;
    
    evalScripts(mydiv);

  13. #13
    Join Date
    Mar 2009
    Posts
    6
    Guess I spoke too early, I'm getting a Javascript error (only in IE) on this line:

    Code:
    eval( scripts[i].innerHTML );
    Do you have any ideas what it could be?

  14. #14
    Join Date
    Feb 2003
    Location
    Michigan, USA
    Posts
    5,773

  15. #15
    Join Date
    Mar 2009
    Posts
    6
    Nice! Removed the comments and it works perfect! Thanks again!!


    Quote Originally Posted by toicontien View Post
    If the <script> tags contain any invalid JavaScript, it might be throwing an error, so remove the HTML comments inside the script tags and give it a shot.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

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



Recent Articles