H.S
H.S

Reputation: 15

Fetch data from database using Ajax/jQuery in Laravel

I want to fetch data (longitude/latitude) from database and return it to draw multiple marker on Google Map using Ajax call.

Below is javascript including ajax :

<script type='text/javascript'>

            (function(){

                var map,marker,latlng,bounds,infowin;
                /* initial locations for map */
                var _lat=5.441771999999999;
                var _lng=100.2936793;

                var id=1;

                function showMap(){
                    /* set the default initial location */
                    latlng={ lat: _lat, lng: _lng };

                    bounds = new google.maps.LatLngBounds();
                    infowin = new google.maps.InfoWindow();

                    /* invoke the map */
                    map = new google.maps.Map( document.getElementById('gmap'), {
                       center:latlng,
                       zoom: 15
                    });

                    /* show the initial marker */
                    marker = new google.maps.Marker({
                       position:latlng,
                       map: map,
                       title: 'Hello World!'
                    });
                    bounds.extend( marker.position );


                   $.ajaxSetup({
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        }
                    });

                    $.ajax({
                        type: 'GET',
                        url: '{{route("voyager.dashboard")}}',
                        data: {id:id},
                        success: function (response){

                           $.each(response, function( i,item ){
                                /* add a marker for each location in response data */ 
                                addMarker( item.latitude, item.longitude, item.location_status );
                            });
                        },
                        error: function(){
                            alert('There was an error loading the data.');

                        }
                    });                 
                }

                /* simple function just to add a new marker */
                function addMarker(lat,lng,title){
                    marker = new google.maps.Marker({/* Cast the returned data as floats using parseFloat() */
                       position:{ lat:parseFloat( lat ), lng:parseFloat( lng ) },
                       map:map,
                       title:title
                    });

                    google.maps.event.addListener( marker, 'click', function(event){
                        infowin.setContent(this.title);
                        infowin.open(map,this);
                        infowin.setPosition(this.position);
                    }.bind( marker ));

                    bounds.extend( marker.position );
                    map.fitBounds( bounds );
                }

                document.addEventListener( 'DOMContentLoaded', showMap, false );
            }());
        </script>

At ajax setting, when I put "dataType:json", function error executed. The output is alert "There was an error loading the data".

This is my controller :

 public function _index(Request $request)
    {
        $locations = Location::select('latitude','longitude','location_status')->get();

        if( $locations ) {
            foreach( $locations as $location ) {
                $markers[]=array( 'latitude'=>$location->latitude, 'longitude'=>$location->longitude, 'location_status'=>$location->location_status );
            }
            return json_encode($markers, JSON_FORCE_OBJECT);     
        }

        return view('vendor.voyager.index');

I tried console.log(response), it display whole javascript code.

Currently error without "dataType:'json'" shown "Uncaught TypeError: Cannot use 'in' operator to search for 'length'..."

I alreday tried this :

$.each(JSON.parse(response), function( i,item )

The error shown "Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse ()..."

This is route at api.php :

Route::group(['middleware' => ['api']], function () {
    Route::get('/', ['uses' => 'VoyagerController@_index',   'as' => 'voyager.dashboard']);
});

I'm not familiar with ajax/jQuery. It's my first time using it. Hope anyone can help me. Thank you in advance.

Upvotes: 1

Views: 1737

Answers (1)

Dimitri Mostrey
Dimitri Mostrey

Reputation: 2340

Change your function to

public function googleMarkers(Request $request)
    {
        $locations = Location::select('latitude','longitude','location_status')->get();

        return response()->json($locations);
}

Your route to

Route::post('/', ['uses' => 'VoyagerController@googleMarkers',   'as' => 'gooogle.markers']);

And as a consequence, your ajax call to

$.ajax({
   type: 'POST',
   url: '{{route("google.markers")}}',
   data: {id:id},

Upvotes: 1

Related Questions