📜 ⬆️ ⬇️

AJAX in Joomla components! 2.5

Hello, habravchane!
Today I wanted to share the solution that I used to implement AJAX when writing components for Joomla! 2.5.
Immediately I would like to warn angry cries: "Go to Google! use search! it happened before! Bojan! " This decision does not lie on the surface and, even though it is banal, I had to sweat to find it.

Lyrical digression


I also immediately anticipate that the topic is written from the position of a “newcomer to Joomla”.
The task before me was trivial: send an AJAX request from the page, and get an answer in JSON format. Without any suspicions, I scored in the search and instead of a couple of minutes of tying up I was stuck in search of a solution for several hours. Of course, I did not disregard the topic of a respected propovednik . But it turned out right away that this solution does not suit me with the tmpl = component parameter: The answer came in the form of a full-fledged page with all the headers, styles included in these headers, and, in fact, the JSON response that I displayed in the view of my component, inside the body tag , but, as promised, without menus and other magnificence of additional modules. Of course, if I used a frame on the page and gave the same answer to the HTML, everything is fine, but alas. To use crutches in the form of pulling out text from the body tag of the received page, or the second option proposed by propovednik - it is possible, but somehow uncomfortable, I want to find a cleaner solution. And everything did not give me the idea that such a monster as Joomla does not have an elementary solution. Poryskav some more, on the bourgeois forum came across a link . In short: for Joomla 3, they wrote a special component for working with AJAX (I don’t surely even include it in the box-out), but it is compatible with version 2.5. This prompted me to think that at 2.5 there is still no ready-made solution, as is the case with index2.php in version 1.5. But we are not looking for easy ways and the decision to put another component is not for us! Then I decided to see what they used in their component.

Decision


And the decision was elementary.
Suppose in your component there is a special View with its Model, which are responsible for the output of the required JSON or XML. You just need to bring default.php in the tmpl folder of your View to the following view
<?php defined('_JEXEC') or die('Restricted access'); $app = JFactory::getApplication(); JResponse::setHeader('Content-Type', 'text/plain', TRUE); //     echo $this->text; $app->close(); 

where $ this-> text is the data received in the Model of your View.

That's all, thank you for your attention!
')
And finally, a small survey, in order for me to understand whether such material is worthy of publication on the pages of Habr, or not worth exchanging for such trifles.

Source: https://habr.com/ru/post/194746/


All Articles