0

My problem is not work AJAX Laravel For me in ver5.2 how to solve this problem my error:

Route [category] not defined. (View: C:\wamp\www\pc\resources\views\admin\category.blade.php)

my Route file:

Route::group(['middleware' => 'web'], function () {
    Route::auth();
    Route::get('category', 'categoryController@index');
});
Route::group(['middleware' => 'web'], function () {
    Route::auth();
    Route::post('category', 'categoryController@create');
});

my controller:

public function create(messageRequest $request)
{
    try {
        Category::create($request->all());
        return response()->json(array('sms'=>'save Success'));
    }catch (Exception $e){
        return response()->json(array('err'=>'error'));
    }
}

my javascript:

<script>
    $('#submit').on('click', function (e) {
        e.preventDefault();
        var data = $('#create').serialize();
        $.ajax({
            type: 'post',
            url: '{!! URL::route('category') !!}',
            data: data,
            success: function (data) {
                alert(data.sms);
                console.log('data');
            },
            error:function(){
                alert(data.err);
                console.log('data');
            }
        });
    });
</script>

2 Answers 2

2
Route::post('category', 'categoryController@create');

change to

Route::post('category', ['as' => 'category',  'uses' => 'categoryController@create']);
Sign up to request clarification or add additional context in comments.

3 Comments

You should explain why this is a solution: URL::route('category') looks for a named route, and OP didn't name their routes. URL::to('category') would also work for a non-named route.
true, URL::to would be an easier fix but naming routes generally seems like a good idea
Agreed entirely. I just wanted to elaborate on the difference.
-1

in view:

$.ajaxSetup({
headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
});
<meta name="csrf-token" content="{{ csrf_token() }}" />
<input type="hidden" name="_token" value="{{ csrf_token() }}">

in controller:

 /**
 * Determine if the session and input CSRF tokens match.
 *
 * @param \Illuminate\Http\Request $request
 * @return bool
 */
protected function tokensMatch($request)
{
    // If request is an ajax request, then check to see if token matches token provider in
    // the header. This way, we can use CSRF protection in ajax requests also.
    $token = $request->ajax() ? $request->header('X-CSRF-Token') : $request->input('_token');

    return $request->session()->token() == $token;
}

1 Comment

This has nothing to do with your posted question.

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.