Yes, you can.
Drupal 7 AJAX requires a callback that needs to return the form element that has been updated and needs to be returned to the browser, or alternatively, a string containing HTML, or an array of custom Ajax commands.
One of the AJAX commands is ajax_command_html(), which you can use to insert the HTML returned from a theme function using a template.
You could have code similar to the following one:
function mymodule_ajax($form, &$form_state) {
$form = array();
$form['changethis'] = array(
'#type' => 'select',
'#options' => array(
'one' => 'one',
'two' => 'two',
'three' => 'three',
),
'#ajax' => array(
'callback' => 'mymodule_ajax_callback',
'wrapper' => 'replace_div',
),
);
// This entire form element will be replaced with an updated value.
$form['html_div'] = array(
'#type' => 'markup',
'#prefix' => '<div id="replace_div">',
'#suffix' => '</div>',
);
return $form;
}
function mymodule_ajax_callback($form, $form_state) {
return theme('mymodule_ajax_output', array());
}
The theme function is defined in hook_theme()
as in the following code:
function mymodule_theme($existing, $type, $theme, $path) {
return array(
'mymodule_ajax_output' => array(
'variables' => array(/* the variables that will be passed to the template file */),
'template' => 'mymodule-ajax-output',
),
);
}
To notice that the template filename must match the name of the theme function; you can use hyphens where the theme function name uses underscores, but you cannot have a theme function named "foo" that uses "bar" as name of the template file.
The name of the template file reported from hook_theme()
doesn't include the extension (".tpl.php") that is added from Drupal when looking for the template file.