json_encode() works for one string but not another?
EDIT:
Solved. Somebody commented with an answer, but then deleted it.
Embarrassingly, the problem was fixed by adding semi-colons after the two
json_encode lines. I still have no idea why string1 worked without a
closing semi-colon and string2 did not, but it works, so… success?
/EDIT
Hi… fairly nooby programmer here.
Within PHP, I'm grabbing two arrays from my database. This works fine. I
then implode each array into a string. This too works fine.
Later in the same file, in the javascript section of my code (featuring
jQuery), I do:
string1 = <?php echo json_encode($string_1);?>
string2 = <?php echo json_encode($string_2);?>
Encoding string1 works perfectly… so long as I comment out the string2
line entirely. It kills my page.
I've tried ensuring that my string is utf8-encoded. I've tried ensuring
that there are no backslashes or other problematic characters. Currently,
I've got some dummy code that's designed to be as unproblematic as
possible… still doesn't work.
Here's the skeleton version of it.
PHP:
$array1 = array();
$array2 = array();
$i = 1;
while($row = mysqli_fetch_assoc($query_result)) {
$array1[$i] = $row['column1'];
$array2[$i] = $row['column2'];
$i++;
}
$string1 = implode(",", $array1);
$string2 = "oh_come_on_why_doesnt_this_work"; // implode(",", $array2);
And JS/HTML/JQuery:
var string1;
var string2;
$.getScript("js/set_functions.js", function(){ loadedScript() });
function loadedScript() {
string1 = <?php echo json_encode($string1);?>
string2 = <?php echo json_encode($string2);?>
// string2 = <?php echo "'" . $string2 . "'";?> doesn't work either
alert(string1); // works if I comment out both string2 = … lines
alert(string2); // displays "undefined" if the first string2 = … line
is commented…
// …out, doesn't display at all if it isn't
}
STUCK PLEASE HELP.
Let me know if you need to see more of my code, or if there's anything
else I could do to help make this question better. Thanks.
PS: I'm not a good programmer, I know. Please don't correct my other bad
coding habits IN LIEU OF helping solve this problem. Thanks!
EDIT: Sorry, in response to Joe Fraumbach, that was an error in my
copy-pasting. I had actually declared $array2 = array();
No comments:
Post a Comment