2

I'm facing strange problem when reading Laravel's json response. Here is my code:

    $.ajax({
        url: 'getallpoints',
        type: 'get',
        dataType: 'json',
        success: function(r){

            var lat = r.lat;
            var lng = r.lng;
            var status = r.status;

            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(lat,lng),
                map: map
            });
        }
    });

Here is my Laravel code

In routes.php

Route::get('/getallpoints', 'PointController@getallpoints');

In PointController.php

class PointController extends BaseController {

public function getAllPoints(){

    return Point::all();
}
}

I'm getting undefined for these:

var lat = r.lat;
var lng = r.lng;

I also tried Response::json(Point::all()) but the same error.

halfer
  • 18,701
  • 13
  • 79
  • 158
Ashutosh
  • 3,511
  • 7
  • 41
  • 82
  • Please, consider reading this http://stackoverflow.com/questions/15602129/returning-an-eloquent-model-as-json-in-laravel-4 – peter.babic Jul 18 '14 at 10:00
  • @delmadord I checked that already, tried all the possibilities. It looks like Laravel returns json data as can be seen in firebug but javascript is having problem. I even used $.parseJSON but didn't work – Ashutosh Jul 18 '14 at 10:21

1 Answers1

1

return Point::all(); will return an array of data, not one point, therefore you have to iterate through that data in your success callback:

...
success: function(data){
    for (var i = 0; i < data.length; i++) {
        var r = data[i];
        ...
    }
}
...
Kestutis
  • 592
  • 7
  • 13
  • Thanks Kestutis, you made my day – Ashutosh Jul 18 '14 at 14:59
  • No problem at all. When working with APIs I find it very useful to test them with [Postman](https://chrome.google.com/webstore/detail/postman-rest-client-packa/fhbjgbiflinjbdggehcddcbncdddomop) first and only then deal with responses in JavaScript – Kestutis Jul 18 '14 at 16:14