Joomla component and Json response for ajax requests

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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s