Reactions Work v1.2.6
Add Facebook/linked style reactions to your Craft CMS content
More Craft plugins

Ajax reactions example

This is a simple example that allows a user to post a reaction with Ajax using query. After reacting, you have to write your own code to update the reactions shown.

You have to supply an 'element' variable which may be any Craft CMS element, such as an Entry, User, Category


{# reactions \twentyfourhoursmedia\reactionswork\models\Recording #}
{# element \craft\base\Element #}

{% with %}
    {% set reactions_work = craft.reactions_work %}
    {# reactions_work \twentyfourhoursmedia\reactionswork\services\ReactionsWorkFacade #}

    <div class="alert alert-info">
        {% set total = reactions.countAllReactions %}
        <p>Ajax example</p>
        <h3>{{ total }} reactions</h3>

        {% set canReact = reactions_work.reactable(currentUser, element) %}
        {% set disabledAttr = canReact ? '' : 'disabled="disabled"' %}
        <form method="post" data-xhr-action="{{ reactions_work.ajaxFormUrl(element, currentUser) }}">
            {{ csrfInput() }}
            <input type="hidden" name="react" value="toggle" />
            {% for handle in reactions_work.reactionHandles %}
                {% if not canReact or reactions.canRegister(handle, currentUser) %}
                    <button name="reaction" {{ disabledAttr }} type="submit" class="btn btn-info js-xhr-reaction" value="{{ handle }}">{{ handle }}</button>
                {% endif %}

                {% if reactions.canDeregister(handle, currentUser) %}
                    <button name="reaction" {{ disabledAttr }} type="submit" class="btn btn-danger js-xhr-reaction" value="{{ handle }}">{{ handle }}</button>
                {% endif %}
            {% endfor %}
        </form>

        {% for handle in reactions_work.reactionHandles %}
            <table>
                <tr>
                    <td>
                        <strong>{{ handle }}</strong>
                    </td>
                    <td>
                        {{ reactions.countReactions(handle) }} reactions
                    </td>
                </tr>
            </table>
        {% endfor %}

    </div>

    <script>
        {% js on ready %}
        $(document).on('click', '.js-xhr-reaction', function(e) {
            e.preventDefault();
            var $this = $(this), $form = $this.closest('form'), action = $form.data('xhr-action');
            var formData = $form.serialize() + '&reaction=' + $this.attr('value');
            $.ajax({
                url: action,
                method: 'POST',
                data: formData,
                success: function(response) {
                    alert('The reaction has been posted. Do something like reload the form');
                }
            });
        });
        {% endjs %}

    </script>

{% endwith %}