T.D T.D - 1 month ago 8
JSON Question

why JSON return html

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() !!}


edit.blade.php

{!! Form::model($schedule,['method'=>'PATCH','url' => 'schedule/'. $schedule->scheduleID ]) !!}
@include('schedule.form',['submitButtonText'=>'Update'])

{!! Form::close() !!}


Ajax in schedule.form

$.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();

});


loadRoute function in controller

public function loadRoute(Request $request){

$routeID=$request->get('routeID');



$station=Station::where('route_id',$routeID)->get()->toArray();


echo json_encode($station);

}


Edit

routes.php

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');
});


Both create and edit page share the same schedule.form, but the JSON data is returned successfully in create page only, for edit page it return html instead of JSON, and I get this error in console (Uncaught SyntaxError: Unexpected token < in JSON at position 0)

Both page using the same form, but why it doesn't work when comes to edit page?

Answer

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!

Comments