0

I am used to update a javaScript variable manually each day this way

<script>
    var data = [
            ['Austria','IBM','8284927','UF93NV', '10'],
            ['Spain','Dell','1098193','MN87QA', '4'],
            ...
          ];
    //rest of my code
<script>

I want to pass the values to this variable from an SQL query result using PHP so that I don't need to type several lines each day. I have created this PHP file where I am connecting to my database and storing the result of the query in an array.

 <?php   
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$ser="*******";
$db="*******"; 
$user="*******"; 
$pass="*******";

$dbDB = new PDO("odbc:Driver=ODBC Driver 13 for SQL Server;Server=*******;Database=*******;Port=1456", $user, $pass);

$sth = $dbDB->prepare("SELECT top 2 [Country],[Customer Name],[Purchase Number],[Part Number],[Qty] FROM *******");
$sth->execute();

$result = $sth->fetchAll();

print_r($result);
 ?>  

It's working fine as you see below the result enter image description here

Now I want to pass the values in the variable $result to my variable data inside the javaScript tag using jason_encode. I added the following code in the same PHP file

<script type="text/javascript">
    var data = <?php echo json_encode($result); ?>;
    alert(data.toString());
</script>

But when I added the alert to see the value of my variable data I receive this enter image description here

and my variable should be this way

var data = [
['Austria','Tech Data Service GmbH','3508224010','01HV707', '4'],
['Austria','Tech Data Service GmbH','3508314557','40M7578', '1']
];

Any advises please what am I missing ? Thank you.

kboul
  • 13,836
  • 5
  • 42
  • 53
JuniorDev
  • 433
  • 3
  • 14
  • 30
  • try console.log instead of alert: `console.log("data is:",data);`, press f12 to open the dev tools and check out the console tab. – HMR Oct 14 '17 at 11:17
  • Check what html/js is being generated – Xymanek Oct 14 '17 at 11:17
  • The way you are trying to accomplish it is really bad. I do believe that you need use an AJAX request to get the data. Please, also keep in mind that JS array and array in php are different, you need to use something like JSON to complete transfer. – Majesty Oct 14 '17 at 11:17
  • Please, check how you can fetch data from server using a [native JS script](https://stackoverflow.com/questions/6782230/ajax-passing-data-to-php-script) . – Majesty Oct 14 '17 at 11:28

1 Answers1

2

The data is already there in your variable. To check how it your objects look like, you could use alert(JSON.stringify(data)).

The contents of your data variable won't be arrays in JavaScript as associative arrays in PHP are objects in JSON.

To get the result you want, the simplest solution would be to use $result = $sth->fetchAll(PDO::FETCH_NUM);.

CHItA
  • 72
  • 8