-1

I'm trying to retrieve some data from my database with php, store it in a javascript array and then change some DOM element with it. I've managed to retrieve data but now I cannot seem to figure out how to store that data in a javascript array. Here's the code I'm using:

My php variable var_dump($result) gives me:

array(1) { [0]=> array(12) { ["id"]=> string(1) "9" ["name"]=> string(7) "Renessa" ["employee_full_name"]=> string(16) "Renessa Tabassum" ["username"]=> string(11) "emp-renessa" ["password"]=> string(6) "123456" ["email"]=> string(17) "renessa@gmail.com" ["phone"]=> string(11) "01911566321" ["salary"]=> string(5) "15000" ["type"]=> string(6) "Driver" ["gender"]=> string(6) "Female" ["join_date"]=> string(10) "2017-12-16" ["rating"]=> string(1) "0" } }

Now I want to store it in a javascript array, so I did the following:

<script type="text/javascript">

        var searchQuery = new Array();
        <?php foreach($result as $value){ ?>
                searchQuery.push('<?=$value;?>');
        <?php } ?>
        alert(searchQuery);

</script>

But nothing happens. I checked my browser's console tab, but it says

Uncaught SyntaxError: Invalid or unexpected token

on line 34, but that line literally contains nothing.

How do I do this? Thanks in advance! :)

B. Desai
  • 16,414
  • 5
  • 26
  • 47
Arefin
  • 5
  • 3

2 Answers2

0

The PHP code and the JS code are running in different times, the server is finish is php loop before he transfer the result to the browser, and just then the js code is run.

You have to use json_encode function to parse the php array into json, and echo the result to the page, like so:

<script type='text/javascript'>
<?php
    $js_array = json_encode($result);
    echo "var searchQuery = ". $js_array . ";";
?>
</script>
Elad
  • 2,087
  • 1
  • 16
  • 30
-1

Your all data is in array inside array. So if you need only single data assign first index of outer array to variable then apply your logic

<script type="text/javascript">

        var searchQuery = new Array();
        <?php 
            $data = isset($result[0])?$result[0]:array();
           foreach($data as $value){ ?>
                searchQuery.push('<?=$value;?>');
        <?php } ?>
        alert(searchQuery);

B. Desai
  • 16,414
  • 5
  • 26
  • 47