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]