Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Oct 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Running javascript that was added to page by ajax

    I'm having trouble getting some javascript code that I add to the page during an ajax call to run. I have some data stored in javascript variables, and when I make an ajax call, I need to set their values with the javascript code returned by the ajax call. I know it's kind of confusing, so I tried to make an example that was as simple as possible. Here's the php for test.php, the main page.

    PHP Code:
    <html>
        <
    head>
            <
    script type='text/javascript' src='scripts/test.js' ></script>
            <script type='text/javascript' >    
                var testVariable = 1;    <!-- THE VARIABLE TO BE UPDATED -->
                
                function ajax() {
                    params = "";
                    request = new ajaxRequest();        // create ajax object
                    request.open("POST", "writevars.php", true);
                    // set headers
                    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                    request.setRequestHeader("Content-length", params.length);
                    request.setRequestHeader("Connection", "close");
                    // assign readystate change event handler
                    request.onreadystatechange = function() {
                        if (this.readyState == 4) {    // completed
                            if (this.status == 200) {        // success
                                if (this.responseText != null) {
                                    <!-- WRITE THE RESPONSE TO THE PAGE INSIDE A DIV -->
                                    document.getElementById('aDiv').innerHTML = this.responseText;
                                    setdata();     <!-- ATTEMPT TO CALL THE NEWLY WRITTEN FUNCTION -->
                                    alert("during ajax" + testVariable);
                                }
                                else {
                                    alert("No data received");
                                }
                            }
                            else {
                                alert("Error " + this.statusText);
                            }
                        }
                    }
                    request.send(params);
                }
            </script>
        </head>

        <body onLoad="test()">
            <div id='aDiv'></div>

            <script type='text/javascript' >
                function test() {
                    ajax();     <!-- CALL THE AJAX FUNCTION -->
                    alert("after ajax" + testVariable);
                }
            </script>
        
        </body>
    </html> 
    PHP Code:
    <?php
        
    if (isset($_POST)) {
            echo 
    "<script type='text/javascript' >";
            echo 
    "    function setdata() {";
            echo 
    "        testVariable = 5;";
            echo 
    "    }";
            echo 
    "</script>";
        }
    ?>
    I create a testVariable and give it a default value. When the page loads, I call test(), which just calls the function ajax(). ajax() makes the ajax request to writevars.php, which just writes some javascript code to set the value of testVariable inside another function, called setData().

    The problem is that after I write the ajax response to the page, setData() always gives an error. My hunch is that the javascript parser only runs when the page first loads, so any code added afterwards isn't recognized by it, but I'm not sure. Is there a simpler way to update the value of a javascript variable after fetching the new value with ajax? Thanks!

  • #2
    Regular Coder
    Join Date
    May 2009
    Posts
    425
    Thanks
    3
    Thanked 62 Times in 61 Posts
    There are a number of ways to do this but I'll list the 2 most feasible...

    The easiest:
    Rather than setting the HTML, use the (much frowned-upon in the programming world) eval function. For something like this, I feel the eval function is okay... as long as you ensure that the data evaluated comes from you and not an outside (malicious) source. Your AJAX function could look something like this:
    PHP Code:
           function ajax(DoEval) {
                    
    params "";
                    
    request = new ajaxRequest();        // create ajax object
                    
    request.open("POST""writevars.php"true);
                    
    // set headers
                    
    request.setRequestHeader("Content-type""application/x-www-form-urlencoded");
                    
    request.setRequestHeader("Content-length"params.length);
                    
    request.setRequestHeader("Connection""close");
                    
    // assign readystate change event handler
                    
    request.onreadystatechange = function() {
                        if (
    this.readyState == 4) {    // completed
                            
    if (this.status == 200) {        // success
                                
    if (this.responseText != null) {
                                    if (
    DoEval) {
                                        eval(
    this.responseText);
                                    } else {
                                        
    document.getElementById('aDiv').innerHTML this.responseText;
                                    }
                                    
                                }
                                else {
                                    
    alert("No data received");
                                }
                            }
                            else {
                                
    alert("Error " this.statusText);
                            }
                        }
                    }
                    
    request.send(params);
                } 
    Your PHP (no newlines allowed):
    PHP Code:
    <?php
        
    if (isset($_POST)) {
            echo 
    addslashes("testVariable = 5;alert(testVariable);");
        }
    ?>
    The slightly more of a pain (i.e., much better) method:
    Forget everything I just said above about using eval on your response text. It's a bad idea to allow response text to define functions for you and an even worse idea to use eval - and with good programming practices it is completely unnecessary. To help ensure that you receive secure data, you could use something like JSON (which I'm personally unfamiliar with... actually upon further reading just now I think I'll go ahead and switch my eval code to JSON haha) to parse the response text into predefined variables... or devise your own parsing methods on the response text. I have a feeling JSON is the way to go though. It'd be something like this...
    Javascript:
    PHP Code:
    <html>
        <
    head>
            <
    script type='text/javascript' src='scripts/test.js' ></script>
            <script type='text/javascript' >    
                var testObj = {    <!-- THE OBJECT (WAS A PLAIN OL VARIABLE BEFORE ;)) TO BE UPDATED -->
                    "testVar": 1
                };
                
                function ajax() {
                    params = "";
                    request = new ajaxRequest();        // create ajax object
                    request.open("POST", "writevars.php", true);
                    // set headers
                    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                    request.setRequestHeader("Content-length", params.length);
                    request.setRequestHeader("Connection", "close");
                    // assign readystate change event handler
                    request.onreadystatechange = function() {
                        if (this.readyState == 4) {    // completed
                            if (this.status == 200) {        // success
                                if (this.responseText != null) {
                                    <!-- WRITE THE RESPONSE TO THE PAGE INSIDE A DIV -->
                                    testObj = JSON.parse(xmlhttp.responseText);
                                    alert(testObj.testVar);
                                    document.getElementById('aDiv').innerHTML = testObj.someHTML;
                                }
                                else {
                                    alert("No data received");
                                }
                            }
                            else {
                                alert("Error " + this.statusText);
                            }
                        }
                    }
                    request.send(params);
                }
            </script>
        </head>

        <body onLoad="test()">
            <div id='aDiv'></div>

            <script type='text/javascript' >
                function test() {
                    ajax();     <!-- CALL THE AJAX FUNCTION -->
                }
            </script>
        
        </body>
    </html> 
    And the PHP file to be requested:
    PHP Code:
    <?php
        
    echo '{"testVar" : 5, "someHTML" : "<b style=\"color:#000077\">JSON is so cool!</b>"}';
    ?>
    To give credit where credit is due, I figured out how to do this by looking at these pages:
    http://www.json.org/js.html
    http://www.developer.com/lang/jscrip...-with-JSON.htm

    The JSON.parse function of course parses the response text into an object to be executed by your predefined javascript. Because the data structure is set and limited to only the actions you define, this will (if done correctly) prevent malicious injection attacks or security breaches. If you read the links above, there is also an optional "reviver" parameter that may be executed while parsing (and the ability to "stringify" - putting an object into a parsable format) which adds another level of awesomeness.

    I don't know if the example I provided for you will work for you since I don't have your AJAX function, but I did create my own test file and it works for me:
    PHP Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
    >
    <
    html>
        <
    head>
            <
    script type='text/javascript' >    
                var 
    testObj = {    <!-- THE OBJECT (WAS A PLAIN OL VARIABLE BEFORE ;)) TO BE UPDATED -->
                    
    "testVar"1
                
    };
                
                var 
    xmlhttp false;
                
    /*@cc_on @*/
                /*@if (@_jscript_version >= 5)
                    // JScript gives us Conditional compilation, we can cope with old IE versions.
                    // and security blocked creation of the objects.
                    try {
                        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                    } catch (e) {
                        try {
                            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (E) {
                            xmlhttp = false;
                        }
                    }
                @end @*/
                
    var IE /*@cc_on!@*/false;
                if (!
    xmlhttp && typeof XMLHttpRequest != 'undefined') {
                    try {
                        
    xmlhttp = new XMLHttpRequest();
                    } catch (
    e) {
                        
    xmlhttp=false;
                    }
                }
                if (!
    xmlhttp && window.createRequest) {
                    try {
                        
    xmlhttp window.createRequest();
                    } catch (
    e) {
                        
    xmlhttp false;
                    }
                }
                function 
    OpenFile(File) {
                    
    xmlhttp.open("GET"File);
                    
    xmlhttp.onreadystatechange = function() {
                        if (
    xmlhttp.readyState == && xmlhttp.status == 200) {
                            
    testObj JSON.parse(xmlhttp.responseText);
                            
    alert(testObj.testVar);
                            
    document.getElementById('aDiv').innerHTML testObj.someHTML;
                        }
                    }
                    
    xmlhttp.send(null);
                }
            
    </script>
        </head>

        <body onLoad="test()">
            <div id='aDiv'>
                <b style="color:#770000">I'm learning something new!</b>
            </div>

            <script type='text/javascript' >
                function test() {
                    OpenFile('Example7_AJAX.php');     <!-- CALL THE AJAX FUNCTION -->
                }
            </script>
        
        </body>
    </html> 
    (The AJAX file is the same.)

    Now, I've read that older browsers (early version of IE8 and below) do not natively support the JSON functions but I'm sure there's a script out there that you can add to your head to fix this. Yep... found it at the bottom of the first link:
    http://www.json.org/json2.js

    I'm definitely switching my web app over to JSON today.

    Last edited by tfburges; 10-03-2010 at 03:54 PM.


  •  

    Posting Permissions

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