Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine
This tutorial has a new version, check it out!

Adding the AJAX Touch: JavaScript

Keep on Learning!

If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.

Start your All-Access Pass
Buy just this tutorial for $12.00

Adding the AJAX Touch: JavaScript

Stop. We haven’t touched JavaScript yet. But, because the attend and unattend endpoints can return JSON, our app is fully ready for some AJAX. The attend/unattend button will be a lot cooler with it anyways, so let’s add some JavaScript.

Click Event to Send AJAX

I’ll give both links a js-attend-toggle class that we can look for in jQuery:

{# src/Yoda/EventBundle/Resources/views/Event/show.html.twig #}
{# ... #}

    {% if entity.hasAttendee(app.user) %}
        <a href="{{ path('event_unattend', {'id': entity.id}) }}"
            class="btn btn-warning btn-xs js-attend-toggle">

            Oh no! I can't go anymore!
    {% else %}
        <a href="{{ path('event_attend', {'id': entity.id}) }}"
            class="btn btn-success btn-xs js-attend-toggle">

            I totally want to go!
    {% endif %}

Adding the JavaScript

Wait! We can’t write jQuery without, ya know, including jQuery. So open up the base template and add it inside the javascripts block. I’m just going to use a CDN:

{# app/Resources/views/base.html.twig #}
{# ... #}

{% block javascripts %}
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
{% endblock %}

To add JavaScript on just this page, we can override this block and call the parent() function. I’ll paste in some jQuery magic that makes an AJAX call when the links are clicked. You can get this magic from the attend-javascript.js file in the code download:

{# src/Yoda/EventBundle/Resources/views/Event/show.html.twig #}
{# ... #}

{% block javascripts %}
    {{ parent() }}

        $(document).ready(function() {
            $('.js-attend-toggle').on('click', function(e) {
                // prevents the browser from "following" the link

                var $anchor = $(this);
                var url = $(this).attr('href')+'.json';

                $.post(url, null, function(data) {
                    if (data.attending) {
                        var message = 'See you there!';
                    } else {
                        var message = 'We\'ll miss you!';

                    $anchor.after('<span class="label label-default">&#10004; '+message+'</span>');
{% endblock %}

I know. In a perfect world, this should live in an external JavaScript file. I’ll leave that to you.

Let’s try our new AJAX magic! Ooh, fancy. The link disappears and we get a cute message.

The code is simple enough: we listen on a click of either link, send an AJAX request, then hide the link and show a message. To get the URL, I’m using the href then adding .json to the end of it. That’s actually kinda hacky. There’s a sweet bundle called FOSJsRoutingBundle that can do this much better. It let’s you actually generate Symfony routes right in JavaScript.

It’s easy to use, so include it in your projects!

Leave a comment!

Login or Register to join the conversation
Neal O. Avatar
Neal O. Avatar Neal O. | posted 5 years ago

One question on the AJAX call should the page be refreshing to show that you have attended/unattended after the ajax call. Currently it just sticks on the See you there/We'll miss you message a manual refresh is required to see the update to the number of Attendees.


Hey Neal!

That part (the See you there/We'll miss you) should update too actually - though it's just done with a little manual process in JavaScript. Check out the second code-block here: https://knpuniversity.com/s.... The trick is just that we look for the JSON coming back: we create a message based on the "attending" in that response, then push the message onto the link tag. It's gotta be some minor JS issue right here :).


Default user avatar
Default user avatar ouerghi yassine | posted 5 years ago

Nice tutorial :D

Cat in space

"Houston: no signs of life"
Start the conversation!

What PHP libraries does this tutorial use?

// composer.json
    "require": {
        "php": ">=5.3.3",
        "symfony/symfony": "~2.4", // v2.4.2
        "doctrine/orm": "~2.2,>=2.2.3", // v2.4.2
        "doctrine/doctrine-bundle": "~1.2", // v1.2.0
        "twig/extensions": "~1.0", // v1.0.1
        "symfony/assetic-bundle": "~2.3", // v2.3.0
        "symfony/swiftmailer-bundle": "~2.3", // v2.3.5
        "symfony/monolog-bundle": "~2.4", // v2.5.0
        "sensio/distribution-bundle": "~2.3", // v2.3.4
        "sensio/framework-extra-bundle": "~3.0", // v3.0.0
        "sensio/generator-bundle": "~2.3", // v2.3.4
        "incenteev/composer-parameter-handler": "~2.0", // v2.1.0
        "doctrine/doctrine-fixtures-bundle": "~2.2.0", // v2.2.0
        "ircmaxell/password-compat": "~1.0.3", // 1.0.3
        "phpunit/phpunit": "~4.1", // 4.1.0
        "stof/doctrine-extensions-bundle": "~1.1.0" // v1.1.0