Most of the times I want to add some ajax functionality at the Joomla component I am currently developing.
I assume you follow the Joomla component development guide.
You can either do it at the component’s controller.
For example
<?php // No direct access to this file defined('_JEXEC') or die('Restricted access'); // import Joomla controller library jimport('joomla.application.component.controller'); /** * Hello World Component Controller */ class HelloWorldController extends JController { function display(){ parent::display(); } function testJson() { global $mainframe; $user = JRequest::getVar("user",null,"get","String"); $response = array(); if($user=="gkatzioura"){ $response["name"] = "Emmanouil"; $response["surname"] = "Gkatziouras"; } else if($user == null) { $response["name"] = "Someone"; $response["surname"] = "Somebody"; } echo json_encode($response); $mainframe->close(); } }
And browse the url http://localhost/joomlasite/?option=com_helloword&task=testJson&user=nothing
Another way is creating a view.ajax.php file.
For example
<?php defined( '_JEXEC' ) or die( 'Restricted access' ); jimport( 'joomla.application.component.view'); class HelloWorldViewAjax extends JView { function display($tpl = null){ $user = JRequest::getVar("user",null,"get","String"); $response = array(); if($user=="gkatzioura"){ $response["name"] = "Emmanouil"; $response["surname"] = "Gkatziouras"; } else if($user == null) { $response["name"] = "Someone"; $response["surname"] = "Somebody"; } echo json_encode($response); } }
and hit the url http://localhost/joomlasite/?option=com_helloword&view=ajax&format=ajax