Skip to content
Advertisement

Passing PHP array into JavaScript for loop

I am trying to pass some value from a PHP array into JavaScript.

My php variable $contacts_info has the followiing values.

Array ( [0] => Array ( [contact_id] => 20 [type_id] => 2 [contact_type] => Representative Phone [contact_value] => 0987654321 )
        [1] => Array ( [contact_id] => 21 [type_id] => 4 [contact_type] => Shop Address [contact_value] => 0987654321 ) 
        [2] => Array ( [contact_id] => 22 [type_id] => 3 [contact_type] => Emergency Phone [contact_value] => 0987654321 ) 
        [3] => Array ( [contact_id] => 23 [type_id] => 2 [contact_type] => Representative Phone [contact_value] => 0987654321 ) 
        [4] => Array ( [contact_id] => 24 [type_id] => 3 [contact_type] => Emergency Phone [contact_value] => 0987654321 ) 
        [5] => Array ( [contact_id] => 25 [type_id] => 4 [contact_type] => Shop Address [contact_value] => 0987654321 ) ) 1

I am trying to assign a specific value in some Combobox with a for loop using JavaScript. But I am having a problem doing so.

Type: ParseError

Message: syntax error, unexpected '<', expecting ']'

My JavaScript code:

<script>
    var total_counter = "<?php echo $total_contact; ?>";
    var contact_info = "<?php json_encode($contacts_info); ?>";
    for (var i = 0; i <= total_counter - 1; i++) {
        let element = document.getElementById("contact_type_id_" + i);
        element.value = "<?php echo $contacts_info[<script>document.writeln(i);</script>]['type_id'] ?>";
    }
</script>

The problem is in this part <?php echo $contacts_info[<script>document.writeln(i);</script>]['type_id'] ?>. Can anyone please help me with it.

Thank you.

Advertisement

Answer

Please do as follows,

  1. You need to remove double quotes that enclose the PHP script, as "" treats it a string.

  2. <?php echo json_encode($contacts_info); ?> was missing echo as JSON array wasn’t getting echoed such that it can be assigned to the javascript variable contact_info

  3. The variable contact_info already have your JSON array, no need to again get it from PHP variable,

Eventually your code should look like,

 <script>
        var total_counter = <?php echo $total_contact; ?>;
        var contact_info = <?php echo json_encode($contacts_info); ?>;
        for (var i = 0; i <= total_counter - 1; i++) {
            let element = document.getElementById("contact_type_id_" + i);
            element.value = contact_info[i].type_id ;
        }
    </script>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement