1

I can't get it to work despite all the sources. I try the following :

<?php
$list_array = array();
foreach ($this->resultatTypeMail as $mailType) {
    $nom          = $mailType->getNom();
    $objet        = $mailType->getObjet();
    $list_array[] = array(
        'Name'   => $nom,
        'Object' => $objet,
    );
    echo "<script type='text/javascript'>alert('$nom');</script>"; // this is OK
    echo "<script type='text/javascript'>alert('$objet');</script>"; // this is OK
}
?>
<script type="text/javascript">
 var js_array = [<?php echo json_encode( $list_array ); ?>];
 alert(js_array[0]); // This returns undefined
</script>

I get satisfying results on $nom and $objet when I alert them.

Problem : js_array[0] returns undefined

Note that I'm not in UTF-8. I'm not sure it's relevant though.

EDIT : A big picture of my goal is to get an array of custom php objet to be usable in JS.

13
  • 1
    replace var js_array = [<?php echo json_encode( $list_array ) ?>]; with var js_array = [<?php echo json_encode( $list_array ); ?>]; and check Commented Mar 9, 2017 at 15:52
  • I believe json_encode encodes arrays that have string values as array keys to JSON objects, rather than arrays. Commented Mar 9, 2017 at 15:54
  • 1
    I've checked my previous comment and it's true. Your solution is to use array_values, so it's properly converted to an array. Alternatively in your javascript use js_array.Name Commented Mar 9, 2017 at 16:00
  • 1
    close php before <script> after foreach Commented Mar 9, 2017 at 16:09
  • 1
    print_r($list_array) see the results after foreach Commented Mar 9, 2017 at 16:18

3 Answers 3

1

Just remove the [] from var js_array = line and it will work:

wrong:

var js_array = [<?php echo json_encode( array_values($list_array) ); ?>];

right:

var js_array = <?php echo json_encode( array_values($list_array) ); ?>;

Working code:

<?php

class MailType {
   function __construct($n, $o) {
       $this->nom = $n;
       $this->objet = $o;
   }

    private $nom;
    private $objet;

    public function getNom() {
        return $this->nom;
    }

    public function getObjet() {
        return $this->objet;
    }

}

$list_array = array();
$resultatTypeMail = array(new MailType('John', 'obj1'), new MailType('Mary', 'obj2'));
foreach ($resultatTypeMail as $mailType) {
    $nom          = $mailType->getNom();
    $objet        = $mailType->getObjet();
    $list_array[] = array(
        'Name'   => $nom,
        'Object' => $objet,
    );
    //echo "<script type='text/javascript'>alert('$nom');</script>"; // this is OK
    //echo "<script type='text/javascript'>alert('$objet');</script>"; // this is OK
}
?>
<script type="text/javascript">
 var js_array = <?php echo json_encode( $list_array ) ?>;
 alert(js_array[0].Name); // This returns John
</script>

You can see it running here: http://phpfiddle.org/main/code/5xei-ybpn

(press F9 or click on 'Run - F9' to Run)

Sign up to request clarification or add additional context in comments.

5 Comments

I said that in my answer and doesn't seem to work for the OP... Also the [ ] are not wrong and the alert should work anyway with them...
@MikO sorry my former comment, I mixed up the answers.
Your code works, I confirm. I'll try switching it to my need to see what's happening and I'll report it here.
I marked your answer as accepted even though I believe all of them are right, and answer my original question. Turns out you guys couldn't solve my problem as my array was not fetch properly, but your answers lead me to the real problem. Thank you all !
Could you share with us, what the real problem was ?
1

In PHP an array that has string keys gets converted to an object when parsed with json_encode.

You could either use array_keys to force the creation of an array, or use the object notation in your javascript

<?php
$list_array = array();
foreach ($this->resultatTypeMail as $mailType) {
    $nom          = $mailType->getNom();
    $objet        = $mailType->getObjet();
    $list_array[] = array(
        'Name'   => $nom,
        'Object' => $objet,
    );
    echo "<script type='text/javascript'>alert('$nom');</script>"; // this is OK
    echo "<script type='text/javascript'>alert('$objet');</script>"; // this is OK
}
<script type="text/javascript">
 var js_array = [<?php echo json_encode( array_values($list_array) ); ?>];
 alert(js_array[0]); 
</script>

Or

<?php
$list_array = array();
foreach ($this->resultatTypeMail as $mailType) {
    $nom          = $mailType->getNom();
    $objet        = $mailType->getObjet();
    $list_array[] = array(
        'Name'   => $nom,
        'Object' => $objet,
    );
    echo "<script type='text/javascript'>alert('$nom');</script>"; // this is OK
    echo "<script type='text/javascript'>alert('$objet');</script>"; // this is OK
}
<script type="text/javascript">
 var js_array = [<?php echo json_encode( array_values($list_array) ); ?>];
 alert(js_array.Name); 
</script>

3 Comments

since the OP has surrounded the JSON with brackets [ ], the result should be an array containing only 1 item with the whole JSON string in it, which may not be what the OP wants, but alert(js_array[0]) should work without the need of array_values or anything... I don't think this is the solution...
I still get 'undefined' with both solutions :/
I tested your code here and you have 3 errors: you forgot the closing ?> tag in both versions and the 2nd version still alerts undefined.
1

I think you have multiple issues: you're missing the ; after the json_encode() line (which is not actually required); you're surrounding the result of json_encode() with brackets (which should work but I expect it's not what you want); and the most important, you're missing the closing PHP ?> tag before printing the JS...

This works for me:

<?php
    // your PHP code here...
?>

<script type="text/javascript">
   var js_array = <?php echo json_encode($list_array); ?>;
   alert(js_array[0]); // This works for me!
</script>

It looks like the issue may be in the encoding as you say - it seems that json_encode only works with UTF-8! From the json_encode() docs:

All string data must be UTF-8 encoded.

So I think you'll have to convert your strings to UTF-8 before putting them into the array, something like:

$list_array[] = array(
    'Name'   => utf8_encode($nom),
    'Object' => utf8_encode($objet),
);

I think just that should work - otherwise you can try this from the comments in the same json_encode() docs; or this other question to get more ideas...

4 Comments

before ?> ; is optional
I edited according to your wise points, but still 'undefined' for me
true! it's been so long since I don't work in a plain PHP script that I can't remember last time I used a closing tag anyway :)
Man it really has to be an issue with encoding. I'm using iso 8859-1, I'll try to see if switching to UTF 8 solves my problem... Would be a problematic though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.