I want to get firm with AJAX and Laravel 5. I have no problems with sending data via ajax and post to the backend. But I have problems handling the updated data.
An example:
The user can change his username on a profile page. The updated username is sent via ajax and post to the backend where the UserController handles the request. After storing the data in the database the new username should be sent to the frontend. One way is to use the return response()->json(['username' => $user->username]);
But know I have to find and update every html-element with javascript where the old username is shown. This seems to be a little bit extensive (e.g. in the navbar, in the page-title etc).
Is there an other way? For example reload only some parts of the view?
This is my ajax-function:
<script>
$(document).ready(function() {
$('#submit-userdatas').click(function () {
$.ajax({
url: 'ajax/updateUserdata',
type: 'post',
data: {
'_token': $('input[name=_token]').val(),
'user_id': $('input[name=user_id]').val(),
'username': $('input[name=username]').val(),
'email': $('input[name=email]').val(),
'vorname': $('input[name=vorname]').val(),
'nachname': $('input[name=nachname]').val(),
'password': $('input[name=password]').val(),
'password_confirmation': $('input[name=password_confirmation]').val()
},
dataType: 'json',
success: function (data) {
if (data.success) {
// find every element and replace the old username
} else {
// show some errors
}
}
});
});
});
</script>
My UserController with update-method:
public static function updateUser($userdata = []){
try{
$user = self::findOrFail($userdata['user_id']);
foreach((array)$userdata as $key => $value){
if(strlen($value) > 0){
if($key == 'password'){
$user->$key = bcrypt($value);
} else {
$user->$key = $value;
}
}
}
$user->save();
return response()->json(['success' => true, 'username' => $user->username]);
} catch(ModelNotFoundException $ex){
return response()->json(['success' => false, 'error' => $ex->getMessage()]);
}
}
Thanks!
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire