Why is passing a PHP Key-value Array into Javascript via Ajax different from directly echoing out into Javascript Variable?
Here's the example:
<?php
$fruits = array(
"a"=>"apple",
"b"=>"banana",
"c"=>"coconut",
);
if ( isset($_GET["ajax"]) ) {
header('Content-Type: application/json');
echo json_encode( $fruits );
exit;
}
?>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
var fruits_php = <?php echo json_encode($fruits); ?>; //<--NO AJAX (Problem is here!)
console.log( "PHP:", fruits_php );
jQuery( document ).ready(function() {
$.ajax({
url: '?ajax',
type: "GET",
cache: false,
headers: {
'Content-Type':'application/json; charset=utf-8',
'Cache-Control':'no-cache',
},
success: function(fruits_ajax){
console.log( "Ajax:", fruits_ajax ); //<--AJAX
}
});
});
</script>
</head>
</html>
And then they become different:
Basically the "Keys" are gone in PHP->Javascript direct assignment approach.
- Why is that so?
- How do I directly assign into Javascript without losing the original PHP Array structure?