This is the second article in the series. In this article I’ll discuss how to use ajax in reality for getting something worthwhile done. Today the file default.php has been discussed.
For our work, we require mainly three files:
- default.php, normally in com_mycomponent/views/mycomponent/default.php
- Ajax file having ajax code. This file for our example will be in: com_mycomponent/js/my_ajax.js
- We’ll use default controller: com_mycomponent/controller.php
Today we’ll discuss the parts of the view template file default.php. The contents are:
<?php defined('_JEXEC') or die('Restricted Access'); jimport('joomla.application.component.helper'); $document =& JFactory::getDocument(); $js = JURI::base().'components/com_mycomponent/js/my_ajax.js'; $document->addScript($js); ?> <form action="" method="post"> <table border=0> <tr> <td><select> <option value=”australia”>Australia</option> <option value=”canada”>Canada</option> <option value=”india”>India</option> <option value=”netherlands”>Netherlands</option> <option value=”usa”>USA</option> </select> </td> </tr> <tr> <td> <input value="List Cities"(); /> </td> </tr> </table> </form> <?php echo "<span id=\"city_loading\"></span>"; echo "<div id=\"cities\"></div>"; ?>
Here is the explaination of different parts of this file:
First we include the file my_ajax.js by using: $document->
addScript($js);
The addScript function is provided by Joomla and is used to place js code including part in the html header of the document.
Then we create small list of countries. I’ve included these cities as a sample. The country name is passed from the form to the javascript of ajax. This name(code) will be used to fetch cities from the database or wherever we’ve stored the data.
The submit button of the form with the label “List Cities” calls the function listCities() from the ajax javascript.
<input type="button" value="List Cities" onClick=listCities(); />
At the end there are two elements: span=city_loading, here you see the progress wheel of the ajax while we are waiting for the results. The other is “cities”, this division is updated when results are received via ajax from the database.
Tomorrow, I’ll discuss about javascript ajax code.
<input type=”button” value=”List Cities” onClick=listCities(); />