Updating view after AJAX post without reload

Published 2 years ago by IlyasDeckers

Hey,

I trying to reload a div's content after an AJAX post, I really have no clue about how to do this. I know that I have to update the innerhtml with Jquery but I am stuck here.

 /* ----------------------------------------------
     Like/Dislike
 -----------------------------------------------*/

 $('.like').on('click', function(event) {
     event.preventDefault();

     postId = event.target.dataset['postid'];

     console.log(postId)
     console.log(token) 
     console.log(urlLike)

     $.ajax({
         method: 'POST',
         url: urlLike,
         data: {postId: postId, _token: token},
     })
     .done(function(msg) {
         console.log(msg); // 
     });

This is my html at the moment, with a normal reload the like count gets updated and with a simple if statement the gets an class with active if the post is liked by the user. How would I update this span class after the AJAX call?

    <div class="wis-numbers">
                <?php $likes = $post->likes->count() ?>
                 
                    <span class="like @if ( $post->isLiked ) active @endif" data-postid="{{ $post->id }} data-original-title="@if($likes == 1) Jij vind dit leuk @else Jij en {{ $likes }} anderen vinden dit leuk @endif" data-toggle="tooltip" data-placement="bottom"><i class="zmdi zmdi-thumb-up" data-postid="{{ $post->id }}"></i> {{ $likes }}</span>
            </div>
Khudadad

Make a partial page return it in your ajax response:

    <div >
           <?php $likes = $post->likes->count() ?>
             
                <span class="like @if ( $post->isLiked ) active @endif" data-postid="{{ $post->id }} data-original-title="@if($likes ==     1) Jij vind dit leuk @else Jij en {{ $likes }} anderen vinden dit leuk @endif" data-toggle="tooltip" data-placement="bottom"><i     class="zmdi zmdi-thumb-up" data-postid="{{ $post->id }}"></i> {{ $likes }}</span>
    </div>


$.ajax({
     method: 'POST',
     url: urlLike,
     data: {postId: postId, _token: token},
 })
 .done(function(msg) {
     console.log(msg); // 
$('.wis-numbers').html(msg);
 });
IlyasDeckers

Finaly something that makes sense :)

I have got this working, kind of... I get an error in my response: Trying to get property of non-object (View: /home/vagrant/Code/Code/Mobilix/resources/views/partials/likes-posts.blade.php) This probably is because the partial is loaded inside a foreach statement and it gets rendered before it reaches the foreach. I could pass the variables to the partial from my controller, but this changes all the like counts on the page. This is the whole foreach statement:

@if($posts->all() != 0)
@foreach(array_reverse($posts->all()) as $post)
    <div class="card w-item post" >
        <div class="card-header">
            <div class="media">
                <div class="pull-left">
                    <a href="/profiel/{{ $post->user->id }}/{{ $post->user->first_name }}.{{$post->user->last_name }}"><img class="avatar-img" src="img/profile-pics/1.jpg" alt=""></a>
                </div>

                <ul class="actions">
                <li>
                    <a href="">
                        <i class="zmdi zmdi-refresh-alt"></i>
                    </a>
                </li>
                <!-- <li>
                    <a href="">
                        <i class="zmdi zmdi-download"></i>
                    </a>
                </li> -->
                <li class="dropdown">
                    <a aria-expanded="false" href="" data-toggle="dropdown">
                        <i class="zmdi zmdi-more-vert"></i>
                    </a>
                    <ul class="dropdown-menu dropdown-menu-right">
                    @if(Auth::user() == $post->user)
                        <li>
                            <a href="#" class="edit">Edit</a>
                        </li>
                        <li>
                            <a href="{{ route('post.delete', ['post_id' => $post->id]) }}">Verwijderen</a>
                        </li>
                    @endif
                        <li>
                            <a href="">Ongewenst</a>
                        </li>
                    </ul>
                </li>
            </ul>
                <div class="media-body">
                    <h2><a href="/profiel/{{ $post->user->id }}/{{ $post->user->first_name }}.{{$post->user->last_name }}" style="color:#000">{{ $post->user->first_name }} {{ $post->user->last_name }}</a>
                        <small>Posted {{ $post->created_at->diffForHumans() }}</small>
                        
                    </h2>
                </div>
            </div>
        </div>
        <div class="post-body card-body card-padding">
            <p id="textBody">{!! nl2br(e($post->body)) !!}</p>

           <div class="wi-stats clearfix">
           <div class="wis-numbers"> <!-- comments count -->
                <span data-original-title="{{ $post->comment()->count() }} comments" data-toggle="tooltip" data-placement="bottom"><i class="zmdi zmdi-comments"></i> {{ $post->comment()->count() }}</span>
            </div>
                <?php $likes = $post->likes->count() ?>
                <div class="wis-numbers"> <!-- likes count -->

                    @include('partials.likes-posts')

                </div>
                <div class="wis-commentors">
                @foreach($post->likes() as $likes)
                test
                    <a href=""><img data-original-title="{{ $likes->user->first_name }}" data-toggle="tooltip" data-placement="top" src="img/profile-pics/1.jpg" alt=""></a>
                @endforeach
                </div>
            </div>
        </div>
        <div class="wi-comments">
            <!-- Comment Listing -->
            
            @foreach($post->comment->take(5) as $comment)
            <div class="list-group">
                <div class="list-group-item media">
                    <a href="/profiel/{{ $comment->user->id }}/{{ $comment->user->first_name }}.{{$comment->user->last_name }}" class="pull-left">
                        <img src="img/profile-pics/5.jpg" alt="" class="lgi-img">
                    </a>

                    <div class="media-body">
                        <a href="/profiel/{{ $comment->user->id }}/{{ $comment->user->first_name }}.{{$comment->user->last_name }}" class="lgi-heading">{{ $comment->user->first_name }} {{ $comment->user->last_name }}<small class="c-gray m-l-10">{{ $comment->created_at->diffForHumans() }}</small></a>

                        <small class="lgi-text">{!! nl2br(e($comment->body)) !!}</small>
                    </div>
                </div>
            </div>
            @endforeach 
            @if($post->comment()->count() >= 5)
             <a class="view-more" href="/posts/{{ $post->id }}">View All Comments</a>
             @endif
            <!-- Comment form -->
            <form action="posts/{{ $post->id }}/comment" method="post">
            {{ csrf_field() }}
            <div class="wic-form">
                <textarea placeholder="Write something..." data-ma-action="wall-comment-open" name="body"></textarea>

                <div class="wicf-actions text-right">
                    <button class="btn btn-sm btn-link waves-effect" data-ma-action="wall-comment-close">Cancel</button>
                    <button type="submit" class="btn btn-sm btn-primary waves-effect">Post</button>
                </div>
            </div>
            </form>

        </div>
    </div>
    @endforeach
    @endif 

partials.likes-posts

<?php $likes = $post->likes->count() ?>

<span style="cursor: pointer;" class="like @if( $post->isLiked ) active @endif" data-postid="{{ $post->id }}" data-original-title="{{ $likes }} vind ik leuks" data-toggle="tooltip" data-placement="bottom"><i class="zmdi zmdi-thumb-up" data-postid="{{ $post->id }}"></i> {{ $likes }}</span>

public function likePost(Request $request)
    {
        // Validation
        $this->handleLike('App\Post', $request['postId']);
        


        $html = View::make('partials.likes-posts')->render();

        

        return response()->json(['html' => $html], 200);
    }

    public function handleLike($type, $postId)
    {
        $existing_like = Like::withTrashed()->whereLikeableType($type)->whereLikeableId($postId)->whereUserId(Auth::id())->first();


        if (is_null($existing_like)) {
            Like::create([
                'user_id'       => Auth::id(),
                'likeable_id'   => $postId,
                'likeable_type' => $type,
            ]);
        } else {
            if (is_null($existing_like->deleted_at)) {
                $existing_like->delete();
            } else {
                $existing_like->restore();
            }
        }
    }

Please sign in or create an account to participate in this conversation.