Ajax

Introduction

The AJAX component allows for defining various actions, which you can afterward hit with HTTP requests in order to create smooth and dynamic JavaScript components for your application.

Basics of AJAX

All application AJAX actions should be defined inside app\Http\ajaxes.php file. This file is included on application bootstrap by the App\Providers\HttpServiceProvider class.

Listening for actions

All you have to do, in order to create action listener, is to call listen method on Ajax facade.

Ajax::listen($action, $callback);
Listening only for autorized or unauthorized actions

By default, AJAX listens for both authorized and unauthorized actions. However, you can narrow that with the third argument.

// Responds only to logged in users
Ajax::listen($action, $callback, ['accessibility' => 'authorized']);

// Responds only to not logged in users
Ajax::listen($action, $callback, ['accessibility' => 'unauthorized']);

Action response

The response callbacks are your field for action. This is where you define what your AJAX actions do. However, remember one thing - you must return results from the callback.

Ajax::listen('five_latest_movies', function() {
    return Post::type('movies')->query([
        'posts_per_page' => '5',
        'order' => 'DESC',
        'orderby' => 'date',
    ]);
});

Response via Closure

For simpler actions, the closure may be entirely sufficient.

Ajax::listen('action', function () {
    return ['message' => 'Out of rum. Why? Why are we out of rum?'];
});

Of course, closure arguments will be automatically resolved from the container.

Ajax::listen('action', function (Posts $posts) {
    return $posts->all();
});

Response via Controller

As same as routes, you can also target your application controllers methods.

// app/Http/ajaxes.php

Ajax::listen('action', 'HomeController@action');
<?php

namespace App\Http\Controllers;

use Assely\Routing\Controller;

class HomeController extends Controller
{
    /**
     * Ajax action response.
     *
     * @return array
     */
    public function action() {
        return ['message' => 'Hide the rum!'];
    }
}
}

Calling actions from JavaScript

Finally, we can reach actions from the frontend. As example we will use jQuery.ajax() to perform an asynchronous HTTP request to our action endpoint.

jQuery.ajax({
    url: Assely.ajax.url,
    dataType: 'json',
    data: {
        // Ajax action name.
        action: 'action',
        // Security nonce token
        nonce: Assely.ajax.nonce,
        // The value you want to pass
        key: 'value'
    }
}).done(function(data, status, response) {
    console.log(data);
});

Protecting actions from CSRF with nonces

Action calls must include a nonce token for protecting against CSRF attacks. Along with action name pass Assely.ajax.nonce value in nonce named key.

{
    action: 'action',
    nonce: Assely.ajax.nonce
}