views:

49

answers:

1

When I execute the eval function it doesn't turn my json response into a object it just breaks my code. I've tried parsing with prototype.js and JSON2.js to no avail some please explain what I am doing wrong here?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt;
<html>
    <head>
        <title>Inventory Management</title>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>Untitled Document</title>
        <script src="call.js" type="text/javascript"></script>
        <script src="prototype.js" type="text/javascript"></script>
    </head>
    <body>
    <div>
            <p id="resp" >new</p>
        <script type="text/javascript">



    var xhr;
    var results=getPlants(xhr,results);
    var plants;


    function getPlants(xhr,results){
        try {
            xhr=new XMLHttpRequest();   
            }catch(microsoft){
            try{
                xhr=new ActiveXObject("Msxml2.XMLHTTP");                
                }catch(othermicrosoft){
                    try{
                xhr = new ActiveXObject("Microsoft.XMLHTTP");               
                    }catch(failed){
                        xhr=false;
                        alert("ajax not supported");
                    }
                }               
        }   
        xhr.onreadystatechange= function () {
        if(xhr.readyState==4 && xhr.status==200) {
        results = xhr.responseText;                     
        }    
}
    xhr.open("GET","db_interactions.php",true);     
    xhr.send(null);
    alert("sent");
 return results;

}

plants = eval('('+results+')');

document.write(typeof(plants));
        </script>

    </div>

    </body>
</html>
+3  A: 

You're issuing an asynchronous request. That means the function will return even when the data isn't ready yet. But your call assumes the JSON response is ready when getPlants is called. Which obviously makes results undefined because you aren't waiting for it.

Put your

plants = eval('('+results+')');
document.write(typeof(plants));

Inside the xhr.onreadystatechange function to make it work, or open the connection as synchronous

xhr.open("GET","db_interactions.php",false);

By the way, don't use eval to parse JSON because code may be injected maliciously. Use a JSON parser instead.

KennyTM
The response is coming from a trusted source, and when I print results outside of the getPlants definition it returns the proper data, all I am trying to figure out is what is wrong with how I'm using the eval function that it wont properly deserialize the data, and to serialize the data I used php_encode
Daquan Hall
You won't know whether the "trusted" source have a vulnerability elsewhere causing you a XSS. Always minimize the attack surface. Plus a JSON parser is likely faster than `eval` (on my Safari `eval` takes 36% more time to parse a JSON than `JSON.parse`).
KennyTM