I'm completely fresh when it comes to javascripts and previously only tried running it through a browser which didn't display script errors. When I made the script error appear (unterminated string constant), the line numbers didn't match up, which made me ask the browser to display the page source.
And suddenly the answer is obvious:
0xa is retained and treated as an actual new line in any script and only disregarded by the browser for output.
Snippet from view page source
// this is a string with 0xa removed
if (input.options[input.selectedIndex].value == 0) {
first.value = 'array ( 1 => array ( \'fName\' => \'Jane\', \'phone\' => \'555 - 5555\', ), 2 => array ( \'fName\' => \'John\', \'phone\' => \'555 - 4444\', ),)';
second.value = "";
}
// this string still has 0xa
else if (input.options[input.selectedIndex].value == 1) {
first.value = "";
second.value = 'array (
1 =>
array (
\'fName\' => \'Jane\',
\'phone\' => \'555 - 5555\',
),
And the full code for testing purposes:
<?php
$people = array( 1 => array('fName' => "Jane", 'phone' => "555 - 5555"),
2 => array('fName' => "John", 'phone' => "555 - 4444"));
// create a string from array data, escape single quotes
$bad_str = addcslashes(var_export($people, true), "'");
// remove all CRs
$ok_str = str_replace(chr( 0xa), "", $bad_str);
?>
<!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">
function setTextNoParams() {
var input = document.getElementById('input');
var first = document.getElementById('first');
var second = document.getElementById('second');
if (input.options[input.selectedIndex].value == 0) {
first.value = '<?php echo $ok_str; ?>';
second.value = "";
}
else if (input.options[input.selectedIndex].value == 1) {
first.value = "";
// problem here...
second.value = '<?php echo $bad_str; ?>'; // breaks entire script
}
else {
first.value = "---";
second.value = "---";
}
}
function setText(bad_str, ok_str) {
var input = document.getElementById('input');
var first = document.getElementById('first');
var second = document.getElementById('second');
if (input.options[input.selectedIndex].value == 0) {
first.value = bad_str;
second.value = "";
}
else if (input.options[input.selectedIndex].value == 1) {
first.value = "";
second.value = ok_str;
}
else {
first.value = "---";
second.value = "---";
}
}
</script>
</head>
<body>
<table border="0pt">
<tr>
<td>Input</td>
<td>First</td>
<td>Second</td>
</tr>
<tr>
<td>
<select id="input"
<?php /* using the line below breaks the entire script due to the $bad_str
onchange="setText('<?php echo $bad_str;?>', '<?php echo $ok_str; ?>')">
*/
?>
onchange="setTextNoParams()">
<option value="-1" selected>None</option>
<option value="0">First</option>
<option value="1">Second</option>
</select>
</td>
<td><input type="text" id="first"></td>
<td><input type="text" id="second"></td>
</tr>
</table>
</body>
Thanks a lot 🙂