0

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?

3
  • 2
    Probably because the server is returning HTML due to some server error or it's actually supposed to do that and you're accessing it incorrectly Commented Oct 30, 2016 at 3:36
  • Is the Ajax in schedule.form section in a blade file or a javascript file? Commented Oct 30, 2016 at 10:01
  • it's in the blade file script section Commented Oct 30, 2016 at 10:21

1 Answer 1

3

I would imagine one of the reasons you're seeing this is because of your loadRoute route 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!

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, thanks! This solved my problem. Forgot to mention, I added the header and token <meta name="_token" content="{!! csrf_token() !!}"/> <script type="text/javascript"> $.ajaxSetup({ headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') } }); But it doesn't work in edit page, I don't actually know that it done by Laravel automatically, still new to it , thanks for help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.