FuelPHP - Ajax


Advertisements

AJAX is a modern technology in web programming. It provides options to send and receive data in a webpage asynchronously, without refreshing the page. Let us learn about FuelPHP AJAX programming in this chapter.

FuelPHP framework provides options to identity whether the request type is AJAX or not. Input class has a method, is_ajax() for this purpose. If an AJAX request is made, Input::is_ajax method returns true, otherwise false.

This method is used to handle an AJAX request properly on the server side.

if (Input::is_ajax()) {  
   // Ajax request  
} else {  
   // Normal request  
} 

We can use json_encode to return the JSON response. We can combine these two methods to create a simple and clean AJAX based web application.

Working Example

Let us add a new page, ajax/index in employee application and try to fetch the employee information asynchronously.

Step 1 − Create a new controller, Controller_Ajax at fuel/app/classes/controller/ajax.php.

<?php  
   class Controller_Ajax extends Controller { 
   } 

Step 2 − Create a new action, action_index as follows.

<?php  
   class Controller_Ajax extends Controller { 
      public function action_index() { 
         $emps = model_employee::find('all'); 
         $data = array(); 
         $i = 0; 
         
         foreach($emps as $emp) { 
            $data[$i] = array(); 
            $data[$i]['name'] = $emp['name']; 
            $data[$i]['age'] = $emp['age'];  
            $i = $i + 1; 
         }  
         if(\Input::is_ajax()) { 
            echo json_encode($data); 
         } else { 
            return \View::forge("ajax/index"); 
         } 
      } 
   }

Here, if the request is AJAX, we fetch student information, encode it as JSON, and return it. Otherwise, we just render the corresponding view.

Step 3 − Create corresponding view file, fuel/app/views/ajax/index.php as follows.

<html>
   <head>
      <script language = "javascript" src = "/assets/js/jquery-3.2.1.min.js"></script>
      
      <style>
         .table { border-collapse: collapse; }
         .table th, td {
            border-bottom: 1px solid #ddd;
            width: 250px;
            text-align: left;
            align: left;
         }
      </style>
   </head>
   
   <body>
      <a id = "loademployee" href = "#">Load employee information</a>
      </br> 
      </br>

      <table class = "table">
         <tbody id = "employee">
         </tbody>
      </table>
      
      <script language = "javascript">
         $(document).ready(function() {
            $("#loademployee").on("click", function(event) {
               $.ajax ({
                  url:        '/ajax/index',
                  type:       'POST',
                  dataType:   'json',
                  async:      true,

                  success: function(data, status) {
                     var e = $('<tr><th>Name</th><th>Age</th></tr>');
                     $('#employee').html('');
                     $('#employee').append(e);
                     
                     for(i = 0; i < data.length; i++) {
                        employee = data[i];
                        var e = $('<tr><td id = "name"></td><td id = "age"></td></tr>');
                        $('#name', e).html(employee['name']);
                        $('#age', e).html(employee['age']);
                        $('#employee').append(e);
                     }
                  },
                  
                  error : function(xhr, textStatus, errorThrown) {
                     alert('Ajax request failed.');
                  }
               });
            });  
         });
      </script>
   </body>
   
</html>

Here, we have created an anchor tag (id: loademployee) to load the employee information using AJAX call. The AJAX call is done using JQuery. Event attached to loademployee tag activates when a user clicks it. Then, it will fetch the employee information using AJAX call and generate the required HTML code dynamically.

Step 4 − Run the application.

Finally, run the application, http://localhost:8000/ajax/index and click the Load employee information anchor tab.

Result

Anchor Tab
Advertisements