laravel ajax загрузка / выборка данных для просмотра - PullRequest
0 голосов
/ 30 мая 2019

Я сейчас работаю в ajax.пока он работает довольно хорошо, но у меня все еще есть проблемы с загрузкой данных в представление без перезагрузки страницы.То есть как я могу перезагрузить определенное содержимое в div с помощью ajax без перезагрузки страницы?

В моем контроллере укажите, какие из них отображаются в представлении при загрузке страницы.

Контроллер:

 public function index($param)
    {
        $user = User::where('slug', $param)->orWhere('id', $param)->first();

        if ($user) {
            $followers = $user->followers()->where('followers.active', 1)->latest()->paginate(50);
            $profileimages = $AllProfileImages = ProfilesProfileimage::where('profile_id', $user->profile->id)->latest()->get();
        } else {
            return back()->with('success', lang::get('messages.nokonto'));
        }

        return view('profiles.follower', compact('user','followers', 'profileimages'));
    }

На мой взгляд, у меня есть html-код, и я указываю, какие данные должны отображаться.

Просмотр:

@foreach ($user->followers as $follower)
                            <div id="follower_{{$follower->id}}" class="box-icon">
                                <div class="col-md-6 col-sm-12 col-xs-12">
                                    <div class="testimonial">
                                        <figure class="float-left">
                                            @if ($follower->profile->privacy == [1,2] OR $follower->isfollowed(Auth::user()) OR Auth::id() == $follower->id)
                                                <a href="/profile/{{$follower->username}}">
                                                    <img class="rounded avatarcomment img-fluid float-left pt-3 pl-3" src="{{ Storage::url($follower->profile->getProfilePicAttribute()) }}">
                                                </a>
                                            @else
                                                <img class="rounded avatarcomment img-fluid float-left pt-3 pl-3" src="{{ Storage::url($follower->AnonymAvatar) }}">
                                            @endif
                                        </figure>
                                        <div class="float-left pt-6">
                                            <p class="fs-14 pl-5 username bold">@if ($follower->profile->privacy == [1,2] OR $follower->isfollowed(Auth::user()) OR Auth::id() == $follower->id) <a href="/profile/{{ $follower->username }}">{{$follower->username}}</a> @else AC @endif</p>
                                            <p class="mtm-20 pt-5 pl-5 fs-12"><i class="glyphicon glyphicon-map-marker"></i> nah</p>
                                        </div>
                                        <div class="float-right m-0">
                                            @if (Auth::user())
                                                @if (Auth::id() == $follower->id)
                                                @else
                                                    @if ($follower->isfollowed(Auth::user()))
                                                        <div class="btn-group-vertical">
                                                            <button id="follow_button_{{$follower->id}}" type="submit" class="btn btn-primary btn-xs btn-follow @if (Auth::id() == $user->id) mt-10 @else mt-25 @endif" data-id="{{ $follower->id }}" style="display: none;">abonnieren</button>
                                                            <button id="unfollow_button_{{$follower->id}}" type="submit" class="btn btn-default btn-xs btn-unfollow @if (Auth::id() == $user->id) mt-10 @else mt-25 @endif" data-id="{{ $follower->id }}">nicht mehr folgen</button>
                                                        @if (Auth::id() == $user->id)
                                                            <button type="submit" class="btn btn-default btn-xs btn-destroy-follow" data-id="{{ $follower->id }}">entfernen</button>
                                                        @endif
                                                        </div>
                                                    @else
                                                        <div class="btn-group-vertical">
                                                        <button id="follow_button_{{$follower->id}}" type="submit" class="btn btn-primary btn-xs btn-follow @if (Auth::id() == $user->id) mt-10 @else mt-25 @endif" data-id="{{ $follower->id }}">abonnieren</button>
                                                        <button id="unfollow_button_{{$follower->id}}" type="submit" class="btn btn-default btn-xs btn-unfollow @if (Auth::id() == $user->id) mt-10 @else mt-25 @endif" data-id="{{ $follower->id }}" style="display: none;">nicht mehr folgen</button>
                                                        @if (Auth::id() == $user->id)
                                                            <button type="submit" class="btn btn-default btn-xs btn-destroy-follow" data-id="{{ $follower->id }}">entfernen</button>
                                                        @endif
                                                        </div>
                                                    @endif
                                                @endif
                                            @endif
                                        </div>
                                    </div>
                                    <div class="col-md-12">
                                        <hr class="m-0">
                                    </div>
                                </div>
                            </div>
                        @endforeach

Когда пользователь щелкаетКнопка .btn-follow, пользователь добавляется в список подписчиков и данные соответствующим образом сохраняются в базе данных.Как я могу обновить представление или перезагрузить данные, которые пользователь в списке отображается как подписчик?Без этого я перезагружаю всю страницу?

Ajax:

$('body').on('click','.btn-follow',function(e) {
    e.preventDefault();
    var id = $(this).data("id");
    $.ajax({
        type: 'POST',
        url: '/profile/follow/' + id,
        success: function (data) {
            _toastr_new(data.message, "top-full-width", "success", false, '.toastr-notify', 0);
            $("#follow_button_" + id).hide();
            $("#unfollow_button_" + id).show();
        },
        error: function (xhqr, staus, message) {
            var response = JSON.parse(xhqr.responseText);
            var errors = response.errors;
            for (var error_key in errors) {
                var error = errors[error_key];
                _toastr_new(error, "top-full-width", "error", false, '.toastr-notify', 0);
            }
        }
    });
});
...