Reputation: 184
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>
Upvotes: 0
Views: 1058
Reputation: 184
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;
}
Upvotes: -1
Reputation: 543
Route::post('category', 'categoryController@create');
change to
Route::post('category', ['as' => 'category', 'uses' => 'categoryController@create']);
Upvotes: 2