2

I'am new in Ajax and I intregated one ajax request. The purpose is one user can like, unlike an article. Look my code :

controller

public function likeAction(Request $request, Article $article, $slug)
{
    if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
        throw $this->createAccessDeniedException();
    }

    if ($request->isXmlHttpRequest()) {
        $tokenStorage = $this->get('security.token_storage');
        $currentUser = $tokenStorage->getToken()->getUser();
        $likes = $article->getLikes();
        foreach ($likes->getUsers() as $user) {
            if ($user == $currentUser) {
                throw new \Exception('Vous aimez déjà cet article !');
            }
        }
        $likes->addUser($currentUser);
        $likes->setCount($likes->getCount() + 1);
        $em = $this->getDoctrine()->getManager();
        $em->persist($article);
        $em->flush();

        $count = $article->getLikes()->getCount();
        return new JsonResponse(array('data' => $count));
    }
    return $this->redirectToRoute('pm_platform_view', array('slug' => $slug));
}

route

pm_platform_like:
    path:      /like/{slug}
    defaults:
        _controller: PMPlatformBundle:Article:like

view

<a class="btn btn-blue-grey" id="like" role="button"></a>
<span class="counter" id="counter">{{ article.likes.count }}</span>

    <script>
        $( document ).ready(function() {
            $(document).on('click', '#like', function (e) {
                $this = $(this);
                $.ajax({
                    type: 'GET',
                    url: '{{ path('pm_platform_like', {slug: article.slug}) }}',
                    dataType: 'JSON',
                    data: {},
                    success: function() {
                      //refresh article.count here 
                    }
                });
            });
        });
    </script>

Currently the ajax request works and the "like" is persisted in database. But in my view nothing change, I have to "refresh" data, more precisly the like count attribute of article entity after the success of the ajax request. I need help for that.

2
  • You can recall function to get like count in ajax success condition. Commented Nov 22, 2016 at 10:48
  • I don't understand, can you write an example ? Commented Nov 22, 2016 at 10:50

2 Answers 2

2

Assuming you have another ajax request that gets like count.

success: function(response) {
        //Recall function here that gets like count.
        fnGetLikeCount();
    }

Edited:

Can you post that function/ajax request that gets like count?

Edit 2:

Yes you can send response from controller and can assign/set that count in like lable/div or what ever you are using.

Sign up to request clarification or add additional context in comments.

2 Comments

I don't have this ajax request. It think was possible to return the like count in the Json reponse (in the controller) ?
Please see edited answer, you can send response from controller.
1

Your AJAX request is already send total counts in response. So, all you need to update "counter" div with total like count.

objResponse holds response of ajax request and total like count would be stored inobjResponse.data .

success: function(objResponse) {  // "objResponse" is response os ajax request
    $("#counter").html(objResponse.data);
    ^^
}

Full Code

<a class="btn btn-blue-grey" id="like" role="button"></a>
<span class="counter" id="counter">{{ article.likes.count }}</span>

<script>
    $( document ).ready(function() {
        $(document).on('click', '#like', function (e) {
            $this = $(this);
            $.ajax({
                type: 'GET',
                url: '{{ path('pm_platform_like', {slug: article.slug}) }}',
                dataType: 'JSON',
                data: {},
                success: function(objResponse) {  // "objResponse" is response os ajax request
                  //refresh article.countcounter here 
                  $("#counter").html(objResponse.data);
                  ^^
                }
            });
        });
    });
</script>

Read more about ajax

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.