Laravel Ajax Call To Controller
Solution 1:
This is a complete answer to your question
Use a POST request instead of GET
Because you are updating the user's language it's more secure to use a POST request
// MAKE AJAX CALL
$.ajax( {
// url:'/settings/profile',url:'./test',
method:'POST',
data: {
strLang: newLang
},
success: function( bolUpdated ) {
if( bolUpdated ) {
alert('OK');
}
},
fail: function() {
alert('NO');
}
});
and don't forget to pass the strLang in your post request via the data attribute.
Protect against CSRF attacks
Store the csrf token in a HTML meta tag:
<metaname="csrf-token"content="{{ csrf_token() }}">
Automatically add the token to all request headers:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Create a route to handle your ajax request:
Route::post('test', 'ProfileController@update');
Get strLang via the $request object in your controller:
functionupdate($request) {
$objUser = Auth::User();
// UPDATE LANGUAGE$bolUpdated = $objUser->updateLanguage( $request->strLang );
// RETURNreturn response()->json( $bolUpdated );
}
If you are using HTML5, your settings.profile.blade should look like this:
<select id="accountLanguage" class="form-control" method="GET">
<option value="en" {{ ($strLanguage == 'en') ? 'selected' : '' }} >English</option>
<option value="es" {{ ($strLanguage == 'es') ? 'selected' : '' }} >EspaƱol</option>
<option value="he" {{ ($strLanguage == 'fr') ? 'selected' : '' }} >French</option>
</select>
In your index method, $objUser already contains the lang property
publicfunctionindex() {
$objUser = Auth::User();
return view("application.settings.profile",[
'objUser' => $objUser
]);
}
Getting the new lang from select element:
$('#accountLanguage').change(function () {
initProfileManager(this.value);
});
Solution 2:
Change your route to:
Route::post('test', 'ProfileController@update');
and your ajax object:
method:'POST',
You have to actually pass $strLang somehow, too (since the update() method expects this, as the error message states).
Oh, and you really don't need the method attribute in your select HTML ;)
Solution 3:
You should define language in the route
Route::get('test/{strLang}', 'ProfileController@update');`
as well as pass it as a variable to the url in js code: '/test/' + strLang
Post a Comment for "Laravel Ajax Call To Controller"