Zend Framework – Ajax


Zend Framework – Ajax


”;


AJAX is a modern technology in web programming. It provides options to send and receive data in a webpage asynchronously, without refreshing the page. Zend framework provides an option to work with the json model through zend-view and zend-json component. Let us learn the Zend AJAX programming in this chapter.

Install json component

The Zend json component can be installed using the Composer command as specified below −

composer require zendframework/zend-json 

Concept

Zend framework provides two methods to easily write an AJAX enabled web application. They are as follows −

  • The isXmlHttpRequest() method in the Request object – If an AJAX request is made, the request object”s isXmlHttpRequest() method returns true, otherwise false. This method is used to handle an AJAX request properly in the server side.

if ($request->isXmlHttpRequest()) { 
   // Ajax request 
} else { 
   // Normal request 
}
  • The Zend/View/Model/JsonModel – The JsonModel is an alternative for ViewModel to be used exclusively for AJAX and the REST API scenarios. The JsonModel along with JsonStrategy (to be configured in the module”s view manager block) encodes the model data into Json and returns it as a response instead of views (phtml).

AJAX – Working Example

Let us add a new ajax page, ajax in the tutorial module and fetch the book information asynchronously. To do this, we should adhere to the following steps.

Step 1: Add JsonStrategy in module configuration

Update the view manager block in the tutorial module configuration file – myapp/module/Tutorial/config/module.config.php. Then, JsonStrategy will work with JsonModel to encode and send the json data.

''view_manager'' => [ 
   ''template_map'' => array
      (''layout/layout'' => __DIR__ . ''/../view/layout/newlayout.phtml''), 
   ''template_path_stack'' => [ 
      ''tutorial'' => __DIR__ . ''/../view'', 
   ], 
   ''strategies'' => array(''ViewJsonStrategy'',), 
],

Step 2: Add ajaxAction method in the TutorialController.php

Add the ajaxAction method in the TutorialController.php with the following code −

public function ajaxAction() { 
   $data = $this->bookTable->fetchAll(); 
   $request = $this->getRequest(); 
   $query = $request->getQuery();  
   if ($request->isXmlHttpRequest() || $query->get(''showJson'') == 1) { 
      $jsonData = array(); 
      $idx = 0; 
      foreach($data as $sampledata) { 
         $temp = array( 
            ''author'' => $sampledata->author, 
            ''title'' => $sampledata->title, 
            ''imagepath'' => $sampledata->imagepath 
         );  
         $jsonData[$idx++] = $temp; 
      } 
      $view = new JsonModel($jsonData); 
      $view->setTerminal(true); 
   } else { 
      $view = new ViewModel(); 
   }  
   return $view; 
} 

Here, ajaxAction will check whether the incoming request is AJAX or not. If the incoming request is AJAX, then the JsonModel will be created. Otherwise, a normal ViewModel will be created.

In both cases, the book information will be fetched from database and populated in the model. If the model is a JsonModel, then JsonStrategy will be invoked and it will encode the data as json and return as response.

The $query->get(”showJson”) == 1 is used for debugging purposes. Just add showJson=1 in the url and the page will display the json data.

Step 3: Add ajax.phtml

Now, add the view script ajax.phtml for the ajaxAction method. This page will have a link with the label – Load book information.

Clicking that link will do an AJAX request, which will fetch the book information as Json data and shows the book information as a formatted table. The AJAX processing is done using the JQuery.

The complete code listing is as follows −

<a id = "loadbook" href = "#">Load book information</a> 
</br> </br> 

<table class = "table"> 
   <tbody id = "book"> 
   </tbody> 
</table>  

<script language = "javascript"> 
$(document).ready(function(){  
   $("#loadbook").on("click", function(event){ 
      $.ajax({ 
         url:        ''/tutorial/ajax'', 
         type:       ''POST'',  
         dataType:   ''json'', 
         async:      true, 
         
         success: function(data, status) { 
            var e = $(''<tr><th>Author</th><th>Title</th><th>Picture</th></tr>''); 
            $(''#book'').html(''''); 
            $(''#book'').append(e); 
            
            for(i = 0; i < data.length; i++) { 
               book = data[i]; 
               var e = $(''<tr><td id = "author"></td><td id = "title"></td>
               <td id="imagepath"><img src = ""/></td></tr>''); 
               $(''#author'', e).html(book[''author'']); 
               $(''#title'', e).html(book[''title'']); 
               $(''#imagepath img'', e).attr(''src'', book[''imagepath'']); 
               $(''#book'').append(e); 
            } 
         }, 
         error : function(xhr, textStatus, errorThrown) { 
            alert(''Ajax request failed.''); 
         } 
      }); 
   }); 
}); 
</script>

Step 4: Run the application

Finally, run the application − http://localhost:8080/tutorial/ajax and click the Load book information link.

The result will be as shown below −

Ajax Page

Ajax Page

Ajax Page with Book Information

Book Information

Ajax page with debugging information

Debugging Information

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *