AJAX Function

Allow you to easily send and process an an AJAX request while efficiently having the desired elements within the web browser modified as desired. You may create a new AJAX function using the create ajax CLI command, such as:

apex create ajax <PACKAGE> <ALIAS>

apex create ajax my-shop contact

With the above example, this will create a new file located at /src/MyShop/Opus/Ajax/Contact.php, which contains one process() method that is executed when the AJAX function is triggered from within the web browser. Below shows an example AJAX function class:

<?php
declare(strict_types = 1);

namespace App\MyShop\Opus\Ajax;

use Apex\App\Base\Web\Ajax;
use Apex\App\Interfaces\Opus\AjaxInterface;

/**
 * Ajax - Contact
 */
class Contact extends Ajax implements AjaxInterface
{

    /**
     * Process AJAX function
     */
    public function process():void
    {

        // Send e-mail message here...

        // High contact form, and display thank you message
        $ajax->setDisplay'contact_form', 'none');
        $ajax->setDisplay('contact_thankyou', 'display');

        // Send alert message
        $ajax->alert("Thank you!  Your message has been received.");
    }

}

As you can summize from above, this AJAX function will hide the element with id "contact_form", display the element with id "contact_thankyou", and give a quick alert via dialog. For a full list of all methods available within the $ajax object, please visit the Apex\App\Base\Web\Ajax Function Reference section.

Triggering AJAX Functions

AJAX functions can be easily triggered from within any web page by linking to for example:

<a href="javascript:ajaxSend('/<PCAKAGE>/<ALIAS>');">Click Here</a>

Using our example class above, the AJAX function can be triggered with the link:

<a href="javascript:ajaxSend('my-shop/contact');">Contact Us</a>

The ajaxSend() Javascript allows for two additional optional arguments. All three arguments the function allows are described below:

  • function_alias - The AJAX function itself to execute, formatted as <PACKAGE>/<ALIAS>.
  • data - Any additional POST data aside from the form fields you would like to send formatted in URL query (eg. key1=value1&key2=value2).
  • form_fields - A comma delimited list of form field names to include in the POST to the AJAX function. If defined, only these form values will be included in the POST request, and otherwise if not defined, all form fields on the page will be included.

ajaxConfirm()

confirmation dialog will appear with the provided message, and the user must click OK or Cancel. For example:

ajaxConfirm("Are you sure you wish to send the contact form?", 'my-shop/contact');