Je fais une recherche en direct où l'utilisateur peut rechercher une entreprise. Cela se ferait en utilisant ajax et les résultats d'affichage mais je reçois une erreur qu'il existe une exception TokenMismatchException.Laravel en direct ajax search - token mismatch
Voici mon code:
Ajax:
function search_data(search_value) {
$.ajax({
url: '/searching/' + search_value,
method: 'POST',
headers: {
'X-CSRFToken': $('meta[name="token"]').attr('content')
}
}).done(function(response){
$('#results').html(response); // put the returning html in the 'results' div
});
}
Controller:
public function search($search) {
$search_text = $search;
if ($search_text==NULL) {
$data= Business::all();
} else {
$data=Business::where('name','LIKE', '%'.$search_text.'%')->get();
}
return view('results')->with('results',$data);
}
}
Route ::
Route::get('/', function() {
return view('auth/login');
});
Route::group(['middleware' => ['auth']], function() {
Route::get('tfgm', '[email protected]')->name('tfgm');;
Route::get('odeon', '[email protected]')->name('odeon');;
Route::get('chronicle', '[email protected]_chronicle')->name('chronicle');;
Route::get('smokeyard', '[email protected]')->name('smokeyard');;
Route::get('profile/', '[email protected]')->name('profile');;
Route::get('create/business', '[email protected]')->name('createBusiness');
Route::get('business/list', '[email protected]')->name('viewBusiness');
Route::get('business/{id}', '[email protected]')->name('displayBusiness');
Route::post('/searching/{search}', '[email protected]');
Route::post('update', '[email protected]');
Route::post('create', '[email protected]');
Route::post('image', '[email protected]');
Route::post('test2', '[email protected]');
Route::post('markers', '[email protected]');
Route::post('reviews', '[email protected]');
});
Auth::routes();
Route::get('/home', '[email protected]')->name('home');
Route::get('/redirect/{provider}', '[email protected]');
Route::get('/callback/{provider}', '[email protected]');
master.blade.php
<head>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
<form action="/search" method="get" autocomplete="off" class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" id="search_text" onkeyup="search_data(this.value, 'result');" placeholder="Search">
</div>
<div id="result">
@include('results')
</div>
</div>
</form>
Demandez-vous une middleware correcte à la route? VerifyCsrfToken, EncryptCookies, etc.? – btl
Je suppose que oui, vous pouvez le confirmer en regardant mon post édité – Przemek
''X-CSRFToken': $ ('meta [nom =" token "]'). Attr ('content')' Votre nom ne correspond pas avec meta tag. Vous avez écrit 'csrf-token' dans la balise META. – Ganesh