Sunday, July 29, 2012

php – Unable to parse a string into JSON object, unable to display an alert box from javascript



EDIT: SOLVED. Use any of the solutions below, but document.onload needs to be changed to window.onload. Also works without needing window.onload function anyway.


Here is the test.php file that i\’m working with



<?php
include(\"conn.php\");
?>

<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>

<script src=\"js/jquery.js\"></script>
<script type=\"text/javascript\">
document.onload = function (){
var jsonString = \'<?php echo json_encode($rowarr); ?>\';
var jsonObj = jQuery.parseJSON( jsonString );
console.log(jsonObj);
alert( jsonObj.Auckland );
};

</script>
</body>
</html>


I have verified in Chrome Developer tools the value of jsonString to be



\'{\"Auckland\":37616,\"Wellington\":35357,\"Christchurch\":29818}\'


After that I don\’t get any log on the console or any alert box. I have also tried JSON.parse method instead of jQuery.parseJSON to no avail.


I\’m trying to get this JSON into a datatable format used for google charts geo chart which looks like this bit of code



var data = google.visualization.arrayToDataTable([
[\'City\', \'Population\', \'Area\'],
[\'Rome\', 2761477, 1285.31],
[\'Milan\', 1324110, 181.76],
[\'Naples\', 959574, 117.27],
[\'Turin\', 907563, 130.17],
[\'Palermo\', 655875, 158.9],
[\'Genoa\', 607906, 243.60],
[\'Bologna\', 380181, 140.7],
[\'Florence\', 371282, 102.41],
[\'Fiumicino\', 67370, 213.44],
[\'Anzio\', 52192, 43.43],
[\'Ciampino\', 38262, 11]
]);






Rating: 3 out of 5 based on 3 ratings



The post php – Unable to parse a string into JSON object, unable to display an alert box from javascript appeared first on Javascript ASK.






via Javascript ASK http://javascriptask.phpfogapp.com/php-unable-to-parse-a-string-into-json-object-unable-to-display-an-alert-box-from-javascript-2.html

No comments:

Post a Comment