In some cases you may find that you want to deliver AJAX content in some way or another inside your component or module. Some components use some complicated AJAX libraries and that is fine. Sometimes you have less demanding needs and would like to be able to just incorporate it into right into your component. However, that becomes problematic in the Joomla! system since component code is wrapped by the template. I'll explain.
In laymen's terms, AJAX works by javascript opening up an invisible internet browser and visiting a URL that you tell it. It then takes whatever output it would get from that URL if it were seeing it in a browser (after all the backend code has run) and will do what you tell it to do with that output in the main page you are calling from. For example, let's say I have a form where someone enters their postal code and I want to display their tax rate based on what they entered. I could add code to my component that handles a special task of "ajax" and then my AJAX URL could be constructed like this "/index.php?com_mycomponent&task=ajax&postal=90210". The problem in the Joomla! environment is that when that URL gets hit in that invisible javascript browser, it is going to have the whole Joomla site template wrapped around the little bit of code displaying the tax rate. On the main page it would look like I just added my whole page in the middle of my whole page. If you are using AJAX to fill in something like a drop down list in a form, or other elements with specific needs, the code just won't work. The key thing with a URL that is AJAX-ready is that if you visit that page in your browser, you should see exactly and ONLY the stuff you want to import into your main page.
So how to get around this? Well, the simplest way I found, in the context of keeping your code neatly inside your component, is to use two php functions to eliminate all the rest of the template output. So, in your function which is called to deliver the AJAX stuff, you would have something like this:
function getAjaxStuff ($arg) {
// do the things you need to get your results
// by this time Joomla has loaded up a bunch of output and ob_clean() will throw it out
// this is only HTML output we are talking about, not session permissions, etc.
ob_clean();
// now echo your results to the page
echo $myOutput;
// now we don't want any more HTML to be added that might mess up the result so we just quit
die();
}
Hopefully that is helpful to someone who was trying to accomplish something similar. If any more knowledgable folks see where this could be improved please feel free to reply with suggestions.
How to deliver AJAX-ready pages from a component Topic is solved
Forum rules