Ajax

Url

Before you continue, be sure to have taken a good look at the previous javascript code. Mind the parameters we're calling:

data: {
    fork: { module: 'MiniBlog', action: 'ThisIsAwesome' },
    post_id: arg
},

Because we're on the frontend, we call the frontend ajax.php supply it with a couple of arguments. The first two are always mandatory:

  • module → the module in which our action file is located
  • action → the name of the action file, without the php-extension

Because we're working in a multilingual site, the language argument is mandatory as well, although you might not need to use it in the action itself. We fetched the language through splitting the url that's currently opened in our browser.

  • language → the language code (nl, en, fr, ...)

Other arguments are action depended. In case of the this_is_awesome action, we need to supply the id of the blog post (post_id) of which we want to increment the awesomeness.

Action

The action file itself is a .php file located in the ajax-folder. The structure of an Ajax action is the same as an other action file, meaning, there has to be a public “execute” function.

namespace Frontend\Modules\MiniBlog\Ajax;

use Frontend\Core\Engine\Base\AjaxAction as FrontendBaseAJAXAction;
use Frontend\Modules\MiniBlog\Engine\Model as FrontendMiniBlogModel;

class ThisIsAwesome extends FrontendBaseAJAXAction
{
    public function execute()
    {
        $post_id = $this->getRequest()->request->getInt('post_id');

        if ($post_id === 0) {
            $this->output(self::BAD_REQUEST, null, 'invalid post_id-parameter.');
        }

        FrontendMiniBlogModel::addAwesomeness($post_id);

        $this->output(self::OK);
    }
}

The difference with other types of actions can be found when given special attention to the naming of the class.

ApplicationModuleAjaxAction

Also note that the class extends Frontend\Core\Engine\Base\AjaxAction. This is necessary to define constants such as "self::OK" and the output-method.

Depending on the post_id being valid or not, the addAwesomeness method defined in the model is called, and the output-method is called. This function outputs JSON data which is read by the Javascript success-function we saw earlier.