how to get data to javascript from php using json_encode?
I could get the JSON array by using PHP's json_encode() from backend like this example:
<!doctype html>
<html>
<script type="text/javascript">
var json = <?php echo json_encode(array(1 => '123', 'abc' => 'abd', 2 => 5));?>;
console.log(json[1]);
console.log(json.abc);
</script>
</html>
No quotation marks means an eval() of whatever was printed out. This is a quick hack that we utilised often to quickly add initial values to our AJAX page.
I know this is old, but I recently found myself searching for this. None of the answers here worked for my case, because my values had quotes in them. The idea here is to base64 encode the array before echo'ing to the page. That way the quotes don't conflict.
< ?php
$names = ['first' => "some'name"];
?>
var names = JSON.parse(atob('< ?php echo base64_encode(json_encode($names)); ?>'));
console.log(names['first']);
I recommend using the jQuery library. The minified version only has 31 kB in size and provides lots of useful functions.
For parsing JSON, simply do
var obj = jQuery.parseJSON ( ' {"name" : "John"} ' );
You can now access everything easily:
alert ( obj.name );
Note: jQuery uses the browser's native JSON parser - if available - which is very quick and much safer then using the eval ()
method.
Edit: To get data from the server side to the client side, there are two possibilities:
1.) Use an AJAX request (quite simple with jQuery):
$.ajax ( {
url: "yourscript.php",
dataType: "json",
success: function ( data, textStatus, jqXHR ) {
// process the data, you only need the "data" argument
// jQuery will automatically parse the JSON for you!
}
} );
2.) Write the JSON object into the Javascript source code at page generation:
<?php
$json = json_encode ( $your_array, JSON_FORCE_OBJECT );
?>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var json_obj = jQuery.parseJSON ( ' + <?php echo $json; ?> + ' );
//]]>
</script>