I'm using Laravel 5.1. I try to get some data in JSON format through the controller, but it return html instead of json.
create.blade.php
{!! Form::open(['url' => 'schedule']) !!}
@include('schedule.form',['submitButtonText'=>'Submit'])
{!! Form::close() !!}
{!! Form::model($schedule,['method'=>'PATCH','url' => 'schedule/'. $schedule->scheduleID ]) !!}
@include('schedule.form',['submitButtonText'=>'Update'])
{!! Form::close() !!}
$.post('../schedule/loadRoute',{routeID:routeID},function(r){
console.log(r);
$.each(JSON.parse(r), function(key, value){
coordinates.push(new google.maps.LatLng(value.lat,value.lon));
if(value.is_station==1){
addMarker(new google.maps.LatLng(value.lat,value.lon),value.name);
}
});
clearMap();
});
public function loadRoute(Request $request){
$routeID=$request->get('routeID');
$station=Station::where('route_id',$routeID)->get()->toArray();
echo json_encode($station);
}
Route::group(
['middleware' => ['web']],
function () {
Route::auth();
Route::get('schedule/getScheduleByRouteID/{routeID}', 'ScheduleController@getScheduleByRouteID');
Route::resource('schedule', 'ScheduleController', ['except' => ['destroy', 'show']]);
Route::post('schedule/loadRoute','ScheduleController@loadRoute');
});
I would imagine one of the reasons you're seeing this is because you're loadRoute
route in underneath the resource
route.
Try changing the order to:
Route::get('schedule/getScheduleByRouteID/{routeID}', 'ScheduleController@getScheduleByRouteID');
Route::post('schedule/loadRoute','ScheduleController@loadRoute');
Route::resource('schedule', 'ScheduleController', ['except' => ['destroy', 'show']]);
https://laravel.com/docs/5.2/controllers#restful-supplementing-resource-controllers
Also, you should return
from a controller not echo
:
public function loadRoute(Request $request)
{
return Station::where('route_id', $request->get('routeID'))->get();
}
In the above Laravel
will automatically json_encode()
the response and add the appropriate headers.
With your $.post
call I would change it to the following:
$.post('{{ url('schedule/loadRoute') }}', {routeID: routeID, _token: '{{ csrf_token() }}'}, function (r) {
console.log(r);
$.each(r, function (key, value) {
coordinates.push(new google.maps.LatLng(value.lat, value.lon));
if (value.is_station == 1) {
addMarker(new google.maps.LatLng(value.lat, value.lon), value.name);
}
});
clearMap();
}, 'json');
This is because Laravel will now be returning a proper json
response with the correct headers so you shouldn't need to JSON.parse()
it. Also, you don't appear to be providing the csrf_token
so that has been added to the data object as well.
Hope this helps!