phpjqueryjoomla

How to correctly code a Joomla MVC component to perform jQuery AJAX GETS/POSTS?


So, I've got this spectacular Joomla component that when finished, will bring world peace, and solve world hunger. All I have to do is incorporate the code that gets called via the jquery .ajax calls. I currently have them in an external location so that the AJAX calls can get to them, but am not clear how to correctly place them in the Joomla Component structure.

I've done the research, trust me, but have only found a lot of discussion about "you could try this, or that". Presumably it's because Joomla relies on mootools, so Jquery is generally out of the discussions, but we have this great library of jQuery routines in-house that I'd like to leverage the right way.

It seems to me that a view has to be created for each call, which seems like a lot of unnecessary work/overhead to accomplish it. (Like asking the pilot to check in to his flight with the passengers). It also seems to me that it shouldn't be this difficult, so am confused about what I'm missing, or why there doesn't appear to be a straight answer.

UPDATE WITH SOLUTION Accepted answer from Soren because it answers the question directly, though I hadn't specified Joomla 1.5, I was able to quickly adapt his answer to work.

Honorable mention to Greg P though - his answer opened up a world of other possibilities that i hadn't considered for quick solutions to other projects/challenges that I have.

Here's the url I was able to successfully call from my component to my component using AJAX, and what I added to make it work.

index.php?option=com_mycomponent&format=raw&controller=ajax.raw&task=myfunction

components\com_mycomponent\controllers\ajaxraw.php

<?php
    defined('_JEXEC') or die( 'Restricted access' );
    jimport('joomla.application.component.controller');
    class MycomponentControllerAjaxraw extends JController
    {
        function myfunction()
        {
            echo json_encode("SomethingOrOther");
        }
    }
?>

Solution

  • You should make Ajax calls to

    index.php?option=com_yourcomponent&task=ajax.function_name&format=raw
    

    You then need to make a new controller called ajax.raw.php and inside that you write functions with names that matches the "function_name" in the URL and they will be executed upon calling the URL.

    From within those you can use models $this->getModel(); and views etc. when needed, or even be lazy and put your logic directly in the controller.

    If you do not have a component then give the Joomla Component Creator a try