1

I have a JSON file that is loaded this way (it reffers a list business into a Google Map):

    var _latitude = 40.4379543;
var _longitude = -3.6795367;
var jsonPath = 'assets/json/items.json.php';

// Load JSON data and create Google Maps

$.getJSON(jsonPath)
    .done(function(json) {
        createHomepageGoogleMap(_latitude,_longitude,json);
    })
    .fail(function( jqxhr, textStatus, error ) {
        console.log(error);
    })
;

And the items.json.php have this:

{
"data": [
    {
        "id": <?php echo 1; ?>,
        "category": "real_estate",
        "title": "<?php echo "q"; ?>",
        "location": "<?php echo "a"; ?>",
        "latitude": 51.541599,
        "longitude": -0.112588,
        "url": "item-detail.html",
        "type": "Apartment",
        "type_icon": "assets/icons/store/apparel/umbrella-2.png",
        "rating": 4,
        "gallery":
            [
                "assets/img/items/1.jpg",
                "assets/img/items/5.jpg",
                "assets/img/items/4.jpg"
            ],
        "features":
            [
                "Free Parking",
                "Cards Accepted",
                "Wi-Fi",
                "Air Condition",
                "Reservations",
                "Teambuildings",
                "Places to seat"
            ],
        "date_created": "2014-11-03",
        "price": "$2500",
        "featured": 0,
        "color": "",
        "person_id": 1,
        "year": 1980,
        "special_offer": 0,
        "item_specific":
            {
                "bedrooms": 4,
                "bathrooms": 2,
                "rooms": 4,
                "garages": 1,
                "area": 240
            },
        "description": "asasasas odio nibh, luctus non pulvinar a, ultricies ac diam. Donec neque massa, viverra interdum eros ut, imperdiet pellentesque mauris. Proin sit amet scelerisque risus. Donec semper semper erat ut mollis. Curabitur suscipit, justo eu dignissim lacinia, ante sapien pharetra duin consectetur eros augue sed ex. Donec a odio rutrum, hendrerit sapien vitae, euismod arcu.",
        "last_review": "Curabitur odio nibh, luctus non pulvinar a, ultricies ac diam. Donec neque massa, viverra interdum eros ut, imperdiet",
        "last_review_rating": 5
    }
]
}

It works fine, but if I include loops, it fails:

{
"data": [
<?php
    $qtodos = $mysqli->query("SELECT * FROM negocios");
    if($qtodos->num_rows != 0) {
    while($todos = $qtodos -> fetch_assoc()) {
?>
        {
            "id": <?php echo $todos['idnegocios']; ?>,
            "category": "real_estate",
            "title": "<?php echo $todos['nombre']; ?>",
            "location": "<?php echo $todos['direccion']; ?>",
            "latitude": 51.541599,
            "longitude": -0.112588,
            "url": "item-detail.html",
            "type": "Apartment",
            "type_icon": "assets/icons/store/apparel/umbrella-2.png",
            "rating": 4,
            "gallery":
                [
                    "assets/img/items/1.jpg",
                    "assets/img/items/5.jpg",
                    "assets/img/items/4.jpg"
                ],
            "features":
                [
                    "Free Parking",
                    "Cards Accepted",
                    "Wi-Fi",
                    "Air Condition",
                    "Reservations",
                    "Teambuildings",
                    "Places to seat"
                ],
            "date_created": "2014-11-03",
            "price": "$2500",
            "featured": 0,
            "color": "",
            "person_id": 1,
            "year": 1980,
            "special_offer": 0,
            "item_specific":
                {
                    "bedrooms": 4,
                    "bathrooms": 2,
                    "rooms": 4,
                    "garages": 1,
                    "area": 240
                },
            "description": "asasasas odio nibh, luctus non pulvinar a, ultricies ac diam. Donec neque massa, viverra interdum eros ut, imperdiet pellentesque mauris. Proin sit amet scelerisque risus. Donec semper semper erat ut mollis. Curabitur suscipit, justo eu dignissim lacinia, ante sapien pharetra duin consectetur eros augue sed ex. Donec a odio rutrum, hendrerit sapien vitae, euismod arcu.",
            "last_review": "Curabitur odio nibh, luctus non pulvinar a, ultricies ac diam. Donec neque massa, viverra interdum eros ut, imperdiet",
            "last_review_rating": 5
        },
<?php
    }
}
?>
    ]
}

The console log is this:

SyntaxError: Unexpected token <
at Object.parse (native)
at o.parseJSON (http://localhost/Proyectos/directorio/assets/js/jquery-2.1.0.min.js:4:4701)
at e.parseJSON (http://localhost/Proyectos/directorio/assets/js/jquery-migrate-1.2.1.min.js:2:2943)
at vc (http://localhost/Proyectos/directorio/assets/js/jquery-2.1.0.min.js:4:6789)
at x (http://localhost/Proyectos/directorio/assets/js/jquery-2.1.0.min.js:4:10194)
at XMLHttpRequest.o.ajaxTransport.l.cors.a.crossDomain.send.b (http://localhost/Proyectos/directorio/assets/js/jquery-2.1.0.min.js:4:14159)

My question is: Why if I include a loop, it fails, and if I include a simply echo with PHP, it don't fail?

5
  • Can you include the generated json, or at least to make sure the generated json seems to be valid? Commented Jul 9, 2015 at 11:10
  • 2
    Create a PHP array and use the function json_encode(). Don't write JSON yourself. And }, <?php is the problem, no comma after last value in an array in JSON. Commented Jul 9, 2015 at 11:11
  • The response seems to be invalid json(seems to contain <). Checkout the response json. If you are using chrome, then after getJSON is called checkout the sources tab in Developers Tools and search for the response json file name. Commented Jul 9, 2015 at 11:11
  • 1
    Listen to @OIS - I'm just going to reiterate what he said to reinforce his advice: don't write JSON yourself. json_encode() will do a far better, easier and quicker job for you. If you need to to json_encode() objects, have a look at the JsonSerializable interface (although you don't need it given your above example, it's good to know about). Commented Jul 9, 2015 at 11:17
  • Also <?php echo $todos['idnegocios']; ?> is probably not surrounded by quotes ... so yeah, just to reiterate, do not make JSON yourself. I feel like there should be a reference post for this type of questions which just says use json_encode() ... Commented Jul 9, 2015 at 11:20

2 Answers 2

2

try this way. use json_encode()

items.json.php

<?php
$qtodos = $mysqli->query("SELECT * FROM negocios");
if($qtodos->num_rows != 0) {
    while($todos = $qtodos -> fetch_assoc()) {
        $google_data = array(
            "id"=> $todos['idnegocios'],
            "category"=> "real_estate",
            "title"=> $todos['nombre'],
            "location"=> $todos['direccion'],
            "latitude"=> 51.541599,
            "longitude"=> -0.112588,
            "url"=> "item-detail.html",
            "type"=> "Apartment",
            "type_icon"=> "assets/icons/store/apparel/umbrella-2.png",
            "rating"=> 4,
            "gallery"=>array(
                "assets/img/items/1.jpg",
                "assets/img/items/5.jpg",
                "assets/img/items/4.jpg"),
            "features"=>
            .....
            ..
    );
    }
}

echo json_encode($google_data);
?>
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, this way, the "{ "data": [" of the beggining is deleted? I did it as you wrote and had the same error: SyntaxError: Unexpected token <
use this echo json_encode(array("data"=> $google_data));
It seems that was not the problem. Still appearing the same error: SyntaxError: Unexpected token <. It seems that in this json can't introduce loops.
0

It failed because an error appears at the start of the file. I forgot to require de config file in this file.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.