Dynamic JavaScript Loading (xmlhttprequest)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • RMWChaos
    New Member
    • Oct 2007
    • 137

    Dynamic JavaScript Loading (xmlhttprequest)

    Currently testing in: WinVista / IE7

    I have been working on getting xmlhttprequest going for weeks now. I have finally gotten a semi-working script going. Pulling up text or xml files works great and populates into the webpage; however, executing javascript has a few problems:

    1. Opens on a blank page, but not a new page. It appears to compeltely overwrite the original page. I want it to update the existing page by loading within a <div> element.

    2. I cannot seem to get functions to work. It seems as if the script is not opening in the global space despite using the 'window' element.

    3. What format should the external javascript file that I am attempting to load be in? I think that I have figured out not to include the '<!--' and '//-->' tags normally included in an external javascript file.

    4. I have no idea how to tell when the browser is using JScript or JavaScript (friggin' Microsoft :-D) and how the two may respond differently.

    I have been reading a lot on the global issues, but none of the suggested fixes has worked for me. One thing that I've learned is that in IE7, all three of these methods of initiating an external javascript file work: eval(), execScript(), and setTimeout().

    Here is the code for your viewing pleasure (I break my code out for ease of reading; so I apologize if it seems longer than normal):

    [code=javascript]

    <!--

    var xmlhttp;

    var fileType;

    function loadData(url)

    {

    xmlhttp = null;

    fileType = url;

    // code for native xmlhttp

    if (window.XMLHttp Request)

    {

    xmlhttp = new XMLHttpRequest( );

    }

    // code for old IE

    else if (window.ActiveX Object)

    {

    xmlhttp = new ActiveXObject(" Microsoft.XMLHT TP");

    }

    if (xmlhttp != null)

    {

    xmlhttp.open("G ET", url, false);

    xmlhttp.onready statechange = processData;

    xmlhttp.send(nu ll);

    }

    else

    {

    alert("Please upgrade to a browser that supports XMLHTTP.");

    }

    }

    function processData()

    {

    // if xmlhttp shows "loaded"

    if (xmlhttp.readyS tate == 4)

    {

    // if "OK"

    if (xmlhttp.status == 200)

    {

    // if text document

    if (fileType.lastI ndexOf("txt") != -1)

    {

    document.getEle mentById('conte nt').innerHTML = xmlhttp.respons eText;

    }

    // if xml document

    if (fileType.lastI ndexOf("xml") != -1)

    {

    // xml parse code here for xmlhttp.respons eXML

    }

    // if javascript file

    if (fileType.lastI ndexOf("js") != -1)

    {

    // if MSIE

    if (window.execScr ipt)

    {

    window.execScri pt(xmlhttp.resp onseText, "javascript ");

    return null;

    }

    // if others

    else if (window.eval)

    {

    window.eval(xml http.responseTe xt);

    }

    // if Safari

    else

    {

    window.setTimeo ut(xmlhttp.resp onseText, 0);

    }

    }

    }

    else

    {

    alert("Problem retrieving data:\n" + xmlhttp.status + "\n" + xmlhttp.statusT ext);

    }

    }

    }

    //-->

    [/code]

    Thanks in advance for your help.
  • RMWChaos
    New Member
    • Oct 2007
    • 137

    #2
    By the way, this:

    [code=javascript]document.getEle mentById('conte nt').innerHTML = window.execScri pt(xmlhttp.resp onseText, "javascript ");[/code]
    throws a "Permission Denied" error but otherwise operates exactly the same.

    In all cases where loading an external javascript file, the "Back" button functions; so it is not loading within the original page as it should. This does not occur with either Text or XML files.

    Oh, I even tried renaming my javascript files to .txt and adding <script> and </script> to them, which sort of worked. At least they loaded within the original page; however, the functions they called within the external script file still did not work. So once again, the global scope problem. Grrr.

    What am I doing wrong!?

    Comment

    • gits
      Recognized Expert Moderator Expert
      • May 2007
      • 5390

      #3
      hi ...

      may be you could try something like this:

      the js-text should look like the assignment to responseText:

      [CODE=javascript]var responseText = 'window.test = function test(x) { alert(x); }; test(3);';

      eval(responseTe xt);

      // you also may do now:
      test(4):
      [/CODE]
      kind regards

      Comment

      • RMWChaos
        New Member
        • Oct 2007
        • 137

        #4
        Thanks for the reply, gits. If I understand your example code correctly, you are suggesting creating a global var and setting it equal to some function. I assume you mean the function would be the responseText from xmlhttprequest. I have tried that. Basically I did this:

        [code=javascript]
        var response; // along with the other global vars such as xmlhttp

        // in the processData() function

        response=xmlhtt p.responseText;

        execScript(resp onse);
        // or
        window.execScri pt(response);
        //same for eval() or setTimeout()
        [/code]

        In all cases, the result was the same. I even tried setting a global variable for 'window', which probably makes no sense, and that didn't work either.

        I have got to be doing something silly here to be causing the problem.

        Thanks again.

        Comment

        • gits
          Recognized Expert Moderator Expert
          • May 2007
          • 5390

          #5
          could you please post an example responseText that you are trying to eval?

          Comment

          • RMWChaos
            New Member
            • Oct 2007
            • 137

            #6
            Oh wait! Are you saying to do this:

            [code=javascript]
            var loadData= function() { // here I would place my loadData() code};

            // then call loadData from the processData() function

            function processData() {

            // ...

            window.execScri pt(loadData, "javascript );

            }
            // then I would have to change the way I initiate the script and pass 'url' to loadData
            [/code]

            Am I on the right track? I will try this now.

            Comment

            • RMWChaos
              New Member
              • Oct 2007
              • 137

              #7
              Below is some example responseText from an external javascript file called loadLogin.js. So from my webpage, I might have a button "Login" with an onclick property:

              [HTML]onclick="loadDa ta('loadLogin.j s')"[/HTML]

              [code=javascript]

              function loginOver()

              {

              document.login. src = "../images/loginHover.jpg" ;

              }

              function loginOut()

              {

              document.login. src = "../images/loginDefault.jp g";

              }

              function submitOver()

              {

              document.submit .src = "../images/submitHover.jpg ";

              }

              function submitOut()

              {

              document.submit .src = "../images/submitDefault.j pg";

              }

              function loginForm()

              {

              document.write( '<form name="login" action="http://api.eve-online.com/account/Characters.xml. aspx" method="post">' );

              document.write( 'UserID: <input type="text" name="userID" size="10" /><br /><br />');

              document.write( 'APIKey: <input type="text" name="apiKey" size="75" /><br /><br />');

              document.write( '<input type="image" alt="Submit" name="submit" value="Submit" src="../images/submitDefault.j pg" onmouseover="su bmitOver" onmouseout="sub mitOut" />');

              document.write( '</form>');

              }

              document.write( '<img src="../images/loginDefault.jp g" name="login" alt="Login" onmouseover="lo ginOver" onmouseout="log inOut" onclick="loginF orm" />');

              [/code]

              Comment

              • RMWChaos
                New Member
                • Oct 2007
                • 137

                #8
                Ok, so calling var loadData from function processData() does not make sense because processData is waiting on the new XMLHttpRequest to be readystate ==4 and status==200.

                There has got to be some way to get the functions from an external javascript file pulled in from xmlhttprequest loaded into global scope. I thought this happened automatically with execScript() and setTimeout().

                Perhaps because my xmlhttprequest script is an external file itself, not embedded in the HTML code, window refers back to the script file and not the htm file. Does that make sense? I am going to try putting the code directly into my webpage and see what happens.

                Comment

                • RMWChaos
                  New Member
                  • Oct 2007
                  • 137

                  #9
                  Nope. Exact same issue occurs when I run the xmlhttprequest script directly from within the html code. So this has something to do with how execScript() is evaluating the code. It is not loading the functions in the global scope or not remembering them or something.

                  Comment

                  • gits
                    Recognized Expert Moderator Expert
                    • May 2007
                    • 5390

                    #10
                    hi ...

                    did you try something that i showed you in my first post (#3)? ... as far as i can see that should work, i tested that with firefox ... in your processData() function you first should eval the responseText. after that you should be able to call the function by name only? do you get any errors? or do you just have no access to the evaluated functions?

                    kind regards

                    Comment

                    • gits
                      Recognized Expert Moderator Expert
                      • May 2007
                      • 5390

                      #11
                      and try to avoid document.write ... this destroys your current document, you may use regular dom-methods (createElement( ), appendChild() etc.) for that ... or use innerHTML ...

                      kind regards

                      Comment

                      • RMWChaos
                        New Member
                        • Oct 2007
                        • 137

                        #12
                        gits,

                        I don't completely understand what you are suggesting I do in your post #3. Sorry, I have only been doing javascripting for about a month now; so without explicit examples, I sometimes get lost.

                        To answer your other question, once the external javascript file is either eval'd, execScript'd, or setTimeout'd, it does not appear that I can call any of the functions from the file. I will try a few things to confirm.

                        The example I gave was just one of the shorter external javascripts I am using, and I certainly will remove the document.write in favor of the dom method as you suggest. Other scripts I am calling do not have document.write in them and run into the same problem.

                        Figures I choose some of the most complex type of coding for my first project.

                        Thanks for your help! :-)

                        Comment

                        • gits
                          Recognized Expert Moderator Expert
                          • May 2007
                          • 5390

                          #13
                          first try the alert example i gave you ... and tell if that works ... please!

                          put the test-function to one of your js files. use firefox to test it. before that ... install the firebug extension so that we may easily debug our code ... i strongly recommend that step. ... next: load our test function, eval it and try to call it after the eval ... and then ... please post back the results ...

                          kind regards

                          Comment

                          • RMWChaos
                            New Member
                            • Oct 2007
                            • 137

                            #14
                            gits,

                            Added your code in post #3 to my loadXHR.js file in place of my other data processing files in processData(). Worked fine in both IE and FireFox. Firebug did not report any errors. An alert popped up with "3" in both IE and FF as expected.

                            I am going to test further with my original code using Firebug to see what errors it logs. I strongly suspect this has something to do with loading the external javascript in the global scope.

                            Thanks.

                            Comment

                            • gits
                              Recognized Expert Moderator Expert
                              • May 2007
                              • 5390

                              #15
                              hi ...

                              but when the test() - alert worked ... it is loaded in the gobal scope when you could call it by name and with a new param = 4 after the eval. so in that case your code should work too ... tell what firebug says ...

                              kind regards

                              Comment

                              Working...