I’m looking to find what are the best practices for the following setup.
In one of my templates I am using Jquery’s ajax method to call a custom PHP script I have written that will eventually return some data from my EE database.
Is there anyway to access the EE Classes in my PHP script I’m calling with the ajax request? When I say “EE Classes” I’m referring to the Database class more specifically. In a typical EE template page I would simply use the following:
$query = $this->EE->db->query("SELECT channel_name FROM exp_channels");
if ($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
echo $row['channel_name']."
\n";
}
}This will not work in my custom PHP script as $this->EE will not work in the context of the file. Please advise if there is anyway around this??
Thanks,
[Mod Edit: Moved to the Development and Programming forum]
Hey thanks for the reply.
The PHP script is not actually part of the EE page load like you mentioned. After some thought I’m thinking that the best way to structure this would be to create a template in EE that holds the PHP script that way I have access to the EE instance and classes. For example I create a template group called “services” and inside that group I have any templates that contain the actual PHP scripts that return the required data. I would then call these templates in my JQuery AJAX calls.
Would this be the proper way to set this up?
Would this be the proper way to set this up?
Yes, I would recommend that route over a script outside of EE itself.
Going one step further you could write a simple EE Plugin to handle this as well. This would increase the performance to a degree but that may not be a big deal depending on what you’re doing.
Can you describe how an EE plugin would work in this scenario?
Sure. It would work something like this. While that article is more EE1-focused most of it applies directly to EE2 as well. You would just need to build a plugin you can access with the tag in a template. Then your ajax URL would call an EE template with that tag in it.
I’d recommend that your plugin check for the presence of an AJAX request before processing anything. EE/CI makes this easy with a predefined constant on page load. You could just do something like this in your plugin’s method:
if ( ! AJAX_REQUEST) {
return
}Packet Tide owns and develops ExpressionEngine. © Packet Tide, All Rights Reserved.