Accessing the Joomla Framework via an AJAX Call

A client had an odd request, the specifics of which probably do not have a lot of application in the real world, but the method in which I achieved the result does offer powerful flexibility when implementing Joomla functionality.

My client wanted the Category Title to appear above the articles that are accessed when clicking “Read more…” from a Category Blog layout. This is a simple configuration option within the Joomla backend. However, they wanted a different Category Title to appear instead of the Category assigned to that article. In this example, the assigned Category was “Portfolio”, but my client wanted it to say “Project Study”. Changing the Category Title via the Category Manager was not an option because “Portfolio” was used in other areas of the site.

I had to find a way to get the category ID of the article, then make an Ajax call that allowed me to access the Joomla framework so I could query the database.

Accomplishing this task took 3 steps.

  1. In Category Blog layouts, the category ID is a parameter in the URL. With SEF URLs turned on, you can still get the parameter using Joomla’s API. Create a Custom HTML module and, using NoNumber’s Sourcerer plugin, create a form that contains the hidden value of the category ID.
    <form id="hiddenurl">
    <?php
    echo "<input name=\"catid\" id=\"catid\" type=\"hidden\" value=\"" . JRequest::getVar('catid') . "\" />";
    ?>
    </form>
  2. Create a PHP file that will be used for the Ajax call. The PHP will contain the code necessary to access the Joomla framework. For my task, I required access to Joomla’s database object, but there’s nothing stopping you from accessing the user object or any object Joomla provides.To access the framework, include the following code:
    define( '_JEXEC', 1 );
    define( ' _VALID_MOS', 1 );
    define( 'JPATH_BASE', '/path/to/Joomla/installation');
    define( 'DS', DIRECTORY_SEPARATOR );
    require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
    require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
    $mainframe =& JFactory::getApplication('site');
    $mainframe->initialise();

    To access the database object, include:$db = &JFactory::getDBO();

    ¬†From there, you can write PHP to accomplish whatever you want. It’s best to use Joomla’s built-in API calls to reduce complexity. For my task, I wrote the following:

    if (empty($_POST["catid"])){
    $return["error"] = true;
    $return["msg"] = "Unidentified category ID.";
    } else {
    $return["error"] = false;
    $db->setQuery('SELECT title FROM #__categories WHERE id='.$_POST["catid"]);
    $category = $db->loadRow();
    if (is_array($category)){
    if ($category[0] == "Portfolio"){
    $category[0] = "Project Study";
    }
    $return["msg"] = $category[0];
    }
    }
    echo json_encode($return);

  3. Create the Javascript function that makes the Ajax call. Using jQuery, I wrote the following:
    $.ajax({
    type: 'POST',
    url: '/path/to/PHP/file',
    dataType: 'json',
    data: { catid: $("#catid").val() },
    success: function(data){
    $('.item-page').prepend(
    $('<h2>').append(
    $('<span>')
    .addClass('subheading-category')
    .text(data.msg)
    )
    )
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    console.log('There was an error.');
    }
    });

    Using the category ID stored in the hidden form field created in the first step, I was able to pass that value to the PHP script using jQuery’s ajax method. Then, from the returned JSON object, I dynamically created the new heading in the DOM.

Again, what I was using this technique for was not elegant, but it offers a method for you to pass data to external PHP pages using an Ajax call while capitalizing on the powerful API Joomla provides.