Symfony - Ajax Control



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 Symfony AJAX programming in this chapter.

Symfony framework provides options to identity whether the request type is AJAX or not. Request class of Symfony HttpFoundation component has a method, isXmlHttpRequest() for this purpose. If an AJAX request is made, the current 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  
} 

Symfony also provides a JSON based Response class, JsonResponse to create the response in JSON format. We can combine these two methods to create a simple and clean AJAX based web application.

AJAX - Working Example

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

Step 1 − Add ajaxAction method in StudentController(src/AppBundle/Controller/StudentController.php).

/** 
   * @Route("/student/ajax") 
*/ 
public function ajaxAction(Request $request) {  
   $students = $this->getDoctrine() 
      ->getRepository('AppBundle:Student') 
      ->findAll();  
      
   if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {  
      $jsonData = array();  
      $idx = 0;  
      foreach($students as $student) {  
         $temp = array(
            'name' => $student->getName(),  
            'address' => $student->getAddress(),  
         );   
         $jsonData[$idx++] = $temp;  
      } 
      return new JsonResponse($jsonData); 
   } else { 
      return $this->render('student/ajax.html.twig'); 
   } 
}         

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

Step 2 − Create a view file ajax.html.twig in Student views directory, app/Resources/views/student/ and add the following code.

{% extends 'base.html.twig' %} 
{% block javascripts %} 
   <script language = "javascript" 
      src = "https://code.jquery.com/jquery-2.2.4.min.js"></script> 
   
   <script language = "javascript">  
      $(document).ready(function(){   
         $("#loadstudent").on("click", function(event){  
            $.ajax({  
               url:        '/student/ajax',  
               type:       'POST',   
               dataType:   'json',  
               async:      true,  
               
               success: function(data, status) {  
                  var e = $('<tr><th>Name</th><th>Address</th></tr>');  
                  $('#student').html('');  
                  $('#student').append(e);  
                  
                  for(i = 0; i < data.length; i++) {  
                     student = data[i];  
                     var e = $('<tr><td id = "name"></td><td id = "address"></td></tr>');
                     
                     $('#name', e).html(student['name']);  
                     $('#address', e).html(student['address']);  
                     $('#student').append(e);  
                  }  
               },  
               error : function(xhr, textStatus, errorThrown) {  
                  alert('Ajax request failed.');  
               }  
            });  
         });  
      });  
   </script> 
{% endblock %}  

{% block stylesheets %} 
   <style> 
      .table { border-collapse: collapse; } 
      .table th, td { 
         border-bottom: 1px solid #ddd; 
         width: 250px; 
         text-align: left; 
         align: left; 
      } 
   </style> 
{% endblock %} 

{% block body %} 
   <a id = "loadstudent" href = "#">Load student information</a>  
   </br> 
   </br>  
   
   <table class = "table">  
      <tbody id = "student"></tbody>  
   </table>     
{% endblock %} 

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

Step 3− Finally, run the application, http://localhost:8000/student/ajax and click the Load student information anchor tab.

Result: Initial Page

Ajax Control Initial Page

Result: Page with Student Information

Ajax Control Final Page
Advertisements