1

I fetch some information from DB - shown here:

$link = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $handle = $link->prepare("SELECT dropAddress FROM mv_bookingEst WHERE userID='$userID'"); 
    $handle->execute();
    $result = $handle->fetchAll(\PDO::FETCH_OBJ);
    //print_r($result);
    $x = 0;
    foreach($result as $obj){
         $resultArray[$x] = $obj->dropAddress;
         $x++;
    }

and then in my javscript:

var count = "<?php echo json_encode($resultArray); ?>";

However I get the following error:

Syntax error: unexpected number --> var count = "["-33.8935642, 151.20227810000006","-33.857653, 151.20853699999998 ...

If I replace json_encode($resultArray) with echo ($resultArray[0]) the values pass fine. Not sure how to fix it because everything I've read uses this method. TIA

1
  • 3
    Did you try taking the quotes out from around the php block in the javascript? Commented Jan 23, 2016 at 23:22

1 Answer 1

1
var count = "<?php echo json_encode($resultArray); ?>";

You are returning the result of the json_encode inside of a JavaScript string. Your syntax error shows this:

Syntax error: unexpected number --> var count = "["-33.8935642, 151.20227810000006","-33.857653, 151.20853699999998 ...

Unless there's a failure in coversion, json_encode returns valid JavaScript syntax, so you should just use it as-is without any adornments in your javascript:

var count = <?php echo json_encode($resultArray); ?>;

If you want to take into consideration the possibility of failure, then you can use this instead:

var count = <?php
     $tmp = json_encode($resultArray);
     echo ($tmp === false ? 'null' : $tmp);
?>;
Sign up to request clarification or add additional context in comments.

6 Comments

If I do var count = <?php echo json_encode($resultArray); ?>; without the "" it gives me an error - Uncaught SyntaxError: Unexpected token < This is what it looks like in the console... var count = <br /> @jbafford
I'd need to see the actual output in the html to offer a suggestion on that.
If you look at the images I just added to the question you can see, unless it something else you're after? @jbafford
You (attempted to) made an edit to my answer with your clarification, rather than updating your question or adding that as a comment. Please don't do that, as it doesn't actually improve the answer. That said, please actually read the html content you're getting: it's an error complaining about an undefined variable. You need to correct that error for it to work correctly.
Sorry @jbafford - was meant to edit my original question - its not undefined, it works if I use resultArray[0] and store it to a JS variable. Just not when I use json_encode
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.