Brotzka
Brotzka

Reputation: 2785

Laravel 5 and AJAX responses

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!

Upvotes: 2

Views: 808

Answers (1)

Jonathan Crowe
Jonathan Crowe

Reputation: 5803

Outside of using a front-end framework with 2-way data binding (angular, vue.js, etc) or writing your own you are going to have to manually update the usernames. To make this easier on yourself you could wrap every username in a span with a custom attribute:

<div class="header">
    <div class="user_container">
          <span data-field="username">John Smith</span>
     </div>
</div>

<div class="body">
   Hello, <span data-field="username">John Smith</span>
</div>

And when you receive the response from your ajax just update the custom field:

$(document).ready(function() {
    $('#submit-userdatas').click(function () {
        $.ajax({
            url: 'ajax/updateUserdata',
            type: 'post',
            data: data,                
            success: function (data) {
                if (data.success) {
                    $("[data-field='username']").text(data.username);
                } else {
                    // show some errors
                }
            }
        });
    });
});

Upvotes: 3

Related Questions