How To Use Ajax Within Joomla! MVC Framework-IV

This post was written by Ganesh Dutt Sharma on June 1, 2010
Posted Under: Joomla Web Technology

Welcome back dear user. This article is the fourth and last in the series of Ajax within Joomla! Framework. In the last article we discussed about how ajax coding works and what was the flow of the code. We also learnt, how the controller was called. Now in this article, I am gonna discuss how the controller fits in this framework for Ajax. Read on…

The contents of the controller.php file are as below:


class MyComponentController extends JController
    function display()

    function listCities()
          global $mainframe, $option;
          $model =& $this->getModel();

          $lists = array();

          $country_name = JRequest::getVar('country_name');
          $cities = $model->getCities($country_name);//The function should exist in the model in order to be usable.
          echo "<br>The cities listing for country: ".$country_name;
          echo "<table><tr>";
          echo "<td>"."City Code"."</td><td>"."City Name"."</td><td>"."City Attractions"."</td></tr>";
          for($i=0, $n=count($cities); $i < $n; $i++)
                    $city = $cities[$i];
                    echo "<tr>";
                    echo "<td>";
                    echo $city->city_code;
                    echo "</td>";
                    echo "<td>";
                    echo $city->city_name;
                    echo "</td>";
                    echo "<td>";
                    echo $city->city_attractions;
                    echo "</td>";
                    echo "</tr>";
          echo "</table>";


Let’s discuss how the contents of this file work. Just to re-iterate,

  1. The request came from tmpl file to the ajax file.
  2. The request with certain variables is forwarded to the controller from the ajax file.
  3. The controller handles the task.

Now details of the controller.php file.

  1. The controller receives the request from the Ajax file with certain parameters.
  2. From URL, it gets the variable country_name with the help of JRequest class method getVar.
  3. Then controller calls the function: getCities() and passes this function, the “country_name” as follows: $model->getCities($country_name).
  4. Once it gets the results, it passes those results in a table of results. That is simple html.
  5. Once that is done, Ajax is informed of the results by xmlhttp.responseText.
  6. The Ajax passes this data layout to the div element named as “city”.
  7. Now this division is updated with the data obtained from controller and the page has updated data without any refreshing. Something which we wanted separately. :)

Within 3-4 days, I’ll post this component at my website for the ones who want to see the Ajax in Action within Joomla! Framework.