PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Cloning Google Suggest With Ajaxac

Creating The Getsuggestions Action Handler Callback

Now that we have the ability to lookup suggestions from the database, we need to create an action in our application, and a handler to take care of calls to the action. We will deal with actually initiating the action call later.

In AjaxAC, we define an action as a thing that can happen from a subrequest. That is, when you initiate a HTTP subrequest, you perform an action on the application.

We need only one action this application: getsuggestions.

First we need to tell GoogleSuggestCloneJax that the action exists, then we tell it how to handle it.

To tell it the action exists, we use the following code in our constructor (it’ll be included in context further down this page):

Listing 6 listing-6.php
<?php
    $this->registerActions('getsuggestions');
?>

It is called ‘registerActions’ and not ‘registerAction’ because it is possible to register more than one action (each as a separate argument).

Now to create the handler callback. All action handlers use the following naming structure: action_[actionname]. So in this case, the callback is called action_getsuggestions. Action handlers don’t take any parameters.

With the callback, the class now looks like this:

Listing 7 listing-7.php
<?php
    require_once('AjaxACApplication.class.php');
 
    class GoogleSuggestCloneJax extends AjaxACApplication
    {
        // ... other code ... //
 
        function GoogleSuggestCloneJax()
        {
            parent::AjaxACApplication();
            $this->registerActions('getsuggestions');
        }
 
        function action_getsuggestions()
        {
            $suggestions = array();
            $this->getSuggestions($this->getRequestValue('q'), $suggestions);
            $this->sendResponseData('jsarray', $suggestions);
        }
 
        // ... other code ... //
    }
?>

One thing to note here is that the term to fetch suggestions for is in the request parameter ‘q’. In AjaxAC, request parameters are what appear in the ‘get’ string. So realistically, this corresponds to $_GET[‘q’].

Finally with this function, we use the AjaxAC handler for sending subrequest data back. There are several return types available, but we’re just going to send data back as a multidimensional array (each array element will have 2 items: item 0 is the suggestion term, and item 1 is the number of results that term would yield in a search).

In This Article