Adrian Hansson Adrian Hansson - 6 months ago 35
PHP Question

Sending Php-array to JavaScript-variable. Get a SyntaxError: Unexpected token :

I'm trying to send an array from php into a variable in my Javascript, but I get an

Unexpected token :-error

My line in JavaScript, enclosed in script-tag in the php-document:

arrayProductTypesFromDB = <?php echo json_encode(getProductTypes()); ?>;

My code for the php function called upon above:

function getProductTypes(){
//here I have code which fetches from database and makes $result into an stdClass-object. This works fine, as I can successfully use that object within php
foreach ($result as $r) {
echo 'id: ' . $r->id . ", type: " . $r->type_name . ", ins: " . $r->nbr_ins . "<br>"; //this works fine

$array = json_decode(json_encode($result), true); //this turns it into an array, and this works fine within php
echo $array[0]['id']; //no problem here
return $array; //this is what I send to JavaScript.. and it doesn't work.


You are doing echo here

echo $array[0]['id']; 

and then also doing


it means it is outputting two times. Hence unexpected token error. Calling the getProductTypes() function will output to strings.