-1

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:

enter image description here

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?
夏期劇場
  • 17,821
  • 44
  • 135
  • 217
  • Hi @mickmackusa , why is that not clear to you? The one and only same `$fruits` Array was assigned in the first line of PHP file above. – 夏期劇場 Aug 01 '18 at 04:23
  • Of course.,.... – 夏期劇場 Aug 01 '18 at 04:26
  • is this on chrome? what version, works just fine on me http://prntscr.com/kd6wwf – Kevin Aug 01 '18 at 04:35
  • doesn't matter though, you already know they are the same, is there something in your code business logic that doesn't work in relation to that issue? – Kevin Aug 01 '18 at 04:37
  • Hi @Ghost, it is latest Chrome version. But the same on any other browsers. So it's not really about browser. You said it worked for you, as in the direct PHP echo shows you the "key-value" correctly? – 夏期劇場 Aug 01 '18 at 04:37
  • @夏期劇場 there's nothing wrong with it, just to be sure, check out the rendered echo via view source, like so: http://prntscr.com/kd6xu3 – Kevin Aug 01 '18 at 04:39
  • Looks perhaps like an `object` versus `array` issue. I'll see if I can dig up an educational reference. Does `JSON_FORCE_OBJECT` make any impact? – mickmackusa Aug 01 '18 at 04:41
  • @Ghost it's wrong :) Because you're losing "keys" in the key-value Array. – 夏期劇場 Aug 01 '18 at 04:42
  • @夏期劇場 haven't you seen the screenshot i just showed? the hardcoded echo shows you the same. check it on your end and see if its the same – Kevin Aug 01 '18 at 04:44
  • 1
    This is very strange @夏期劇場 , I tried it here and it returned the same value . However please try the following : `var fruits_php = JSON.parse(''); //<--NO AJAX` – Ashraf Aug 01 '18 at 04:45
  • @夏期劇場 ,Would you please give us some more information about your chrome `chrome://version/` – Ashraf Aug 01 '18 at 04:47
  • 1
    Not a duplicate, but relevant reading: https://stackoverflow.com/q/11195692/2943403 – mickmackusa Aug 01 '18 at 05:01

3 Answers3

1

While I couldn't replicate your example, I do have some ideas. It looks json_encode is converting an associative array to an indexed array.

You could try converting your array to an object:

$fruits = (object) array(
    'a' => 'apple',
    'b' => 'banana',
    'c' => 'coconut',
);

Or setting the force object flag on the json_encode function:

json_encode( $fruits, JSON_FORCE_OBJECT );

What version of php are you running btw?

ngearing
  • 1,325
  • 11
  • 18
0

Try JSON.parse() as shown here

var fruits_php = JSON.parse(<?php echo json_encode($fruits); ?>);
chethan
  • 32
  • 7
-1

Remove header parameter from ajax request and just console log like this

console.log( fruits_ajax );
  • You're not really looking into the question. – 夏期劇場 Aug 01 '18 at 04:15
  • so you want same php structure array in ajax response ? – Rahul Kalal Aug 01 '18 at 04:17
  • Why "key" are lost in direct PHP to Javascript assignment. (We're not talking about Ajax here) – 夏期劇場 Aug 01 '18 at 04:18
  • Something is wrong in your code, key will never lost. and apart from ajax it will change response to object, if you want your array as well in response then you can pass true parameter like this echo json_encode($result,true); – Rahul Kalal Aug 01 '18 at 04:22
  • "Something is wrong in your code". What a constructive answer. Everyone is here on StackOverFlow because there's something wrong in what they're doing, and hence looking for a solution. Nevermind, you don't even seem to understand the problem here, but someone else did. Therefore i've already gotten the correct answer. Try to solve the real problem next time for other people instead of keep flaming on unnecessary things. Since you're a beginner here, you may wish to look into this as well: https://stackoverflow.com/help/how-to-answer – 夏期劇場 Aug 01 '18 at 06:03