0

I wrote this code:

$userAddresses = $database->getUsers("SELECT * FROM Users");

$address = array();
foreach($userAddresses as $user){
    array_push($address, array("address"=> $user['address'],
                               "zipcode" => $user['zipcode']));
}
$locations = array(
            "locations" => $address
);

$jsonLocations = json_encode($locations);

This code returns this json object:

{"locations":[
             {"address":"Sneekermeer 25","zipcode":"2993 RL"},
             {"address":"Boeier 13","zipcode":"2992 AK"}]}

I want to get the length of this array inside JavaScript. So I did this:

var address = '<?php echo $jsonLocations ?>';

After that I called console.log(address.length); to check the length but some how it counts all the chars (108 I think) in the address variable and returns that as length. address.locations.length also doesn't work.

Could someone help me out?

2
  • 1
    what do you mean by length? what it should be showed? Commented Aug 3, 2017 at 9:57
  • 1
    Note the quotes on your address line. It's a string. Commented Aug 3, 2017 at 9:57

4 Answers 4

2

You can use JSON.parse()

var address = JSON.parse('<?php echo $jsonLocations ?>');

console.log(address.length); //  will give you length;
Sign up to request clarification or add additional context in comments.

1 Comment

If you go this route, you have to double-encode it, see @Geoffrey's post.
1

Thats because the string needs to be decoded to an object. You can do this one of two ways.

Non recommended:

var address = <?= $jsonLocations ?>;

Or more correctly and safer:

var address = JSON.parse('<?= addslashes(json_encode($jsonLocations)) ?>');

Do not forget the call to addslashes to prevent any single quotes in your array from breaking the javascript string.

2 Comments

What's wrong with the first method? Looks better (and safer) to me.
@georg It can be used to inject Javascript, not just an object, where as the JSON.parse method will not execute any Javascript, but just load the object. It is why it exists at all.
0

You can either remove the quotes around var address = '<?php echo $jsonLocations ?>'; (i.e var address = <?php echo $jsonLocations ?>;) or use JSON.parse to parse it as a string to an object.

Comments

-1

I have tried the below and its working

var address = '{"locations":[{"address":"Sneekermeer 25","zipcode":"2993 RL"},{"address":"Boeier 13","zipcode":"2992 AK"}]}';
address = JSON.parse(address);
console.log(address.locations.length);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.