简体   繁体   中英

Joomla - How to connect to db after receiving data with Ajax in php file

I am buiding a component for Joomla 1.6.

I have a problem regarding a connection to the database.

I have sent data to a php file called rating.php with ajax; The data is sent without problem to the file. However, the data are not sent if I leave the line

defined('_JEXEC') or die('Restricted access');

but I get a 'restricted access' message.

Secondly, even when I comment out the previous check, I can not connect to my database inside this php file, obviously because I can't call the Joomla variables (like getDBO()) inside the file. What can I do to solve these 2 problems ?

Thank you

Joomla will only set _JEXEC when you are browsing your site through index.php. In other words, Joomla will not do anything with files that are "outside" of Joomla. _JEXEC will not be set and the database will not be connected to.

To solve the problem, I would include a Joomla page so that the database will be loaded:

<?php
ob_start();
require 'index.php';
ob_end_clean();
// Rating code
?>

This code includes the homepage of your site, and uses output buffering to not actually output your site. You do not need to check for _JEXEC, because the only reason it is used is to make sure that someone is not directly accessing a file without going through Joomla. In your case, _JEXEC is irrelevant.

To make your script faster, replace the index.php with a link to an inner page that has minimal content. Homepages tend to be slower than an inner page.

I have not tested this code, but it should work.

If you're developing a component, it's always a good idea to make your requests through "index.php", instead of some other file. This way you are sure the framework is loaded and you can use any of its features while processing the request. Another advantage is easier maintenance (especially on big extensions), because it is easier to follow the workflow when you have the same entrypoint for all the requests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM