Using eval() for the responseText of XMLHttpRequest?

I’m interested to know how others feel about eval() in Javascript (mostly in regard to the topic), plus how you generally handle the response from an XMLHttpRequest.
[size=1]
The common implementation I read online is something to this extent:

    [size=2]XMLHttpRequest requests a script (e.g. PHP), which fetches data from a database (e.g. MySQL). PHP must encode the data in some format so it's traversable back in Javascript. 
    
 Two methods: encode an XML document in PHP, or separating the data in a string using delimiters (e.g. |||).
    
    An XML response can be handled by:

        httpRequest.responseXML.getElementsByTagName('myTag');
        
    While the delimited response can be iterated easily after parsing it into an array:

        data = httpRequest.responseText.split('|||');
        
    [/size][/size]     In my applications I choose another method. I echo Javascript in PHP and eval() the responseText in JS.
     
    Something like:

           httpRequest['onreadystatechange'] = new Function('
            	if (httpRequest[readyState] == 4)
            	{
            		eval(httpRequest[responseText]);
            	}
           ');
              
      [size=1](may have syntax errors; done on the fly)
    
    [size=2]I made various PHP functions to handle DOM manipulation routines (e.g. form error checking) with data.
    
    For example, populating a form from a query:

        function populateForm($data)
        {
        	foreach ($data as $key => $value)
        	{
        		echo "document.getElementById('$key').value = '".addslashes($value)."';";
        	}
        }
        
        $profile = $Db->fetchRow("
        	SELECT profileId, firstName, lastName, phone 
        	FROM profile 
        	WHERE profileId = $profileId
        ");
        
        populateForm($profile);
        

[/size][/size][size=1][size=2]

I haven’t seen much usage of eval() in XMLHttpRequest examples & projects online (except JSPAN). It seems easier not having to iterate your data, encode it in XML, then in Javascript re-iterate it.

The only 2 drawbacks I believe with eval() is, notably, how fast it evaluates this dynamic Javascript. Secondly is the issue of caching, since it’s dynamic code it isn’t being cached by the browser like the static JS. I haven’t noticed any significant slowdown in my applications though, and they work flawlessly on IE6 and Firefox.

   [/size][/size][size=1][size=2][i]Note: my application [/i][/size][/size][size=1][size=2][i]depends on XMLHttpRequest for form submissions and error handling, living the largest taboo to web standards/[/i][/size][/size][size=1][size=2][i]accessibility[/i][/size][/size][size=1][size=2][i]. Except this application [/i][/size][/size][size=1][size=2][i]is for a company and runs only on local company owned computers (under IE6 & Windows), used by employees, making it a nonissue. I plan to implement code that's compatible with Javascript disabled.[/i][/size][/size]

Hi,

I haven’t seen much usage of eval() in XMLHttpRequest examples & projects online
Well, I think there are a couple of different situations you are talking about. Generally, the examples you see show raw data being sent back to a browser in response to a request. The raw data could be a list of names, or places, zip codes, or the links to the latest news stories on a subject, etc. Before sending that raw data to the client, it can be helpful to organize it in some way. The two ways you mentioned are a delimited string or an XML document. Obviously an XML document provides a more sophisticated way of organizing the data, and that organization allows the client browser to search the data in more sophisticated ways. On the other hand, a delimited string requires brute force to search and extract the desired data. In any case, neither of those methods of returning data require eval(). eval() is a js function that takes a string that looks like javascript code and executes the javascript code in the string. If you are returning raw data from an XMLHttpRequest organized into an XML document or a delimited string, there is no javascript to eval().

What you seem to be doing is returning javascript from your XMLHttpRequest:

echo "document.getElementById('$key').value = '".addslashes($value)."';";

I have seen some similar examples of that posted recently. The problem you face when doing that is: how do you get the browser to parse the javascript and execute it. There are several ways to do it, and you have chosen to use eval(). However, my question with all these sending js in a response examples is, why do you need to get javascript with an XMLHttpRequest? I tend to think of an XMLHtttpRequest as a means for getting dynamically changing data from the server to display in a web page. If whatever you are retrieving isn’t dynamically changing, then it seems to me an XMLHttpRequest is the wrong approach. You don’t get XMLHttpRequests for free: they require hitting up the server for more information, and if the server is slow, you are going to keep the user waiting, and the user may be gone before the request ever finishes. So, it seems to me that a web programmer should be trying to avoid XMLHttpRequests, and if you do have to make one, then you want to grab as little data as possible.

My question for you is: why couldn’t the javascript you are returning from your XMLHttpRequest be included in the page when it is first sent to the browser?

I probably will, initially I didn’t want to use XML as my medium. Eval seemed promising at the time. But I see the dark clouds looming near, and large slowdown from all the redundant Javascript is probable.

    An example (obfuscated as one line) of a response back from one of my scripts.
    
    [size=1]

document.getElementById(‘updateButton’).value = ‘Update Template’;var currentInput; if (document.getElementById(‘_templateId’)) { document.getElementById(‘_templateId’)[‘innerHTML’] = ‘’; } currentInput = document.getElementById(“templateId”); if (!currentInput) { window.alert(“\“templateId\” does not exist!”); } else { currentInput.value = “8”; } if (document.getElementById(‘_name’)) { document.getElementById(‘_name’)[‘innerHTML’] = ‘’; } currentInput = document.getElementById(“name”); if (!currentInput) { window.alert(“\“name\” does not exist!”); } else { currentInput.value = “clock_notice_header”; } if (document.getElementById(‘_templateGroupId’)) { document.getElementById(‘_templateGroupId’)[‘innerHTML’] = ‘’; } currentInput = document.getElementById(“templateGroupId”); if (!currentInput) { window.alert(“\“templateGroupId\” does not exist!”); } else { currentInput.value = “”; } if (document.getElementById(‘_title’)) { document.getElementById(‘_title’)[‘innerHTML’] = ‘’; } currentInput = document.getElementById(“title”); if (!currentInput) { window.alert(“\“title\” does not exist!”); } else { currentInput.value = “Time Clock Status”; } if (document.getElementById(‘_content’)) { document.getElementById(‘_content’)[‘innerHTML’] = ‘’; } currentInput = document.getElementById(“content”); if (!currentInput) { window.alert(“\“content\” does not exist!”); } else { currentInput.value = “”; } if (document.getElementById(‘_description’)) { document.getElementById(‘_description’)[‘innerHTML’] = ‘’; } currentInput = document.getElementById(“description”); if (!currentInput) { window.alert(“\“description\” does not exist!”); } else { currentInput.value = “Employee\'s status is as follows.”; } if (document.getElementById(‘_html’)) { document.getElementById(‘_html’)[‘innerHTML’] = ‘’; } currentInput = document.getElementById(“html”); if (!currentInput) { window.alert(“\“html\” does not exist!”); } else { currentInput.value = “”; } if (document.getElementById(‘_evalCondition’)) { document.getElementById(‘_evalCondition’)[‘innerHTML’] = ‘’; } currentInput = document.getElementById(“evalCondition”); if (!currentInput) { window.alert(“\“evalCondition\” does not exist!”); } else { currentInput.value = “”; } if (document.getElementById(‘_tabName’)) { document.getElementById(‘_tabName’)[‘innerHTML’] = ‘’; } currentInput = document.getElementById(“tabName”); if (!currentInput) { window.alert(“\“tabName\” does not exist!”); } else { currentInput.value = “”; } if (document.getElementById(‘_parentName’)) { document.getElementById(‘_parentName’)[‘innerHTML’] = ‘’; } currentInput = document.getElementById(“parentName”); if (!currentInput) { window.alert(“\“parentName\” does not exist!”); } else { currentInput.value = “”; } if (document.getElementById(‘_displayOrder’)) { document.getElementById(‘_displayOrder’)[‘innerHTML’] = ‘’; } currentInput = document.getElementById(“displayOrder”); if (!currentInput) { window.alert(“\“displayOrder\” does not exist!”); } else { currentInput.value = “”; }[/size]

You could dynamically add new script elements and then call functions from the new JS files.