Pierre Dommerc Pierre Dommerc - 16 days ago 6
Javascript Question

refresh data in view after ajax request symfony

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.

Answer

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