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.

JavaScript

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.

JavaScript

My JavaScript code:

JavaScript

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,

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement