I am currently coding a timetable application with PHP.
What I want to do is to have a button for each day of the week and that when a user clicks each button, the tasks listed down for that day are loaded into the browser window using JavaScript.
My current code is:
<?php
class loadTimetable
{
public static function getTimetable( $params )
{
//Obtain a database connection
$db = JFactory::getDbo();
//Retrieve the shout
$query = $db->getQuery(true)
->select($db->quoteName('title'))
->from($db->quoteName('#__timetable'))
->where('day = '. $db->Quote($params));
//Prepare the query
$db->setQuery($query);
// Load the row.
$result = $db->loadResult();
//Return the Hello
return $result;
}
}
$day = date("N");
$timetable = getTimetable($day);
?>
<h1><?php echo $timetable; ?></h1>
The function is inside Joomla and has been tested to work fine. The help I need is how to call that function using Javascript/AJAX.
As far as I can see, all Javascript would have to do is call the function with the selected day (e.g, getTimetable(1)
where 1 is the value for the Monday button in the HTML).
Based on your question and further comments, you should move your code (or its invocation at least) to the component. Only components can be "invoked". There are many options, but to keep it simple you need at least (in the component):
A task in a controller, i.e. a function getTimetable()
that will receive the ajax call;
This can also be done in a subcontroller. In case of a controller, you will invoke it with index.php?option=com_yourcomponent&task=getTimetable&day=2011-09-17
, in case of a subcontroller task=subcontroller.getTimetable
The function you pasted in a module, let's call it timemodule for now, and getTimetable($day)
will need to be public.
The controller:getTimetable()
function will
3.a. parse and sanitize the day parameter input;
3.b. instantiate the module timemodule
3.c. instantiate the view, inject the module, let it load the results from db and
3.d. invoke the view's render()
method
3.e. the exit
statement (so Joomla will not render the template and other modules (all you want is the json/xml output).
There are, of course, many alternatives; in the controller you may set a day variable using setUserState
, then redirect to the view, and use the variable from userstate in the module; it's really a matter of preference, what you want to keep in mind is that the exit
statement should be invoked in the loop that renders output, so if you redirect you'll invoke it in the view's display()
method. You may also append &format=json
to your url to achieve this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With