AJAX in Drupal 7
All the Functions for use with Drupal's Ajax framework are situated at /includes/ajax.in
Drupal's Ajax framework is used to dynamically update parts of a page's HTML based on data from the server.
Upon a specified event, such as a button click, a callback function is triggered which performs server-side logic and may return updated markup, which is then replaced on-the-fly with no page refresh necessary.
The function ajax_commands_* where * is a place holder for further function names is a basically Ajax framework commands that we need to use frequently to update the code.
Sample Self calling Function :
(function($) {
$(document).ready(function(){
--------Your code here to execute upon document ready--------
});
})(jQuery);
Sample functions in Drupal AJAX to achieve Ajax feature to edit comments...
1.
// Function to create simple form element in page..
function comment_example_form($form, &$form_state,$comment){
$form = array();
$form['status-comment-edit'] = array(
'#type' => 'textarea',
'#rows' => 3,
'#required' => TRUE,
'#default_value' => $comment->comment,
);
$form['save'] = array(
'#type' => 'submit',
'#value' => t('Update'),
);
$form['#cid'] = $comment->cid;
return $form;
}2.
// Function to get and render form element in $form field and
// adding ajax command to plug-in HTML code in that form on page
// Note, the return array with type and command
function fbss_comments_edit($comment) {
$form_build = drupal_get_form("comment_example_form", $comment);
$form = drupal_render($form_build);
$commands[] = ajax_command_html('.comment-content'.$comment->cid.'',$form);
return array('#type' => 'ajax', '#commands' => $commands);
}3.
// Function to submit the data to be DB on clicking the submit button...
function comment_example_form_submit($form, &$form_state){
db_update('fbss_comments')
->fields(array('comment' => $form_state['values']['status-comment-edit']))
->condition('cid', $form['#cid'])
->execute();
$c = fbss_comments_load($form['#cid']);
module_invoke_all('fbss_comments_after_save', $c, TRUE);
if ($_GET['destination'] && $_GET['destination'] != 'fbss_comments/js/refresh') {
$form_state['redirect'] = $_GET['destination'];
} else {
$form_state['redirect'] = '';
}
drupal_set_message(t('Status comment has been successfully edited.'));
}
Sample functions in Drupal AJAX to achieve Ajax feature on button submit...
1.
// Function to create simple form element in page..
function comment_example_form($form, &$form_state,$comment){
$form = array();
$form['comment'] = array(
'#type' => 'textfield',
'#title' => 'Enter Value :',
'#required' => TRUE,
);
$form['save'] = array(
'#type' => 'submit',
'#value' => t('Update'),
'#ajax' => array(
'callback' => 'test_ajax_form_action',
'effect' => 'fade',
),
);
$form['#cid'] = $comment->cid;
return $form;
}2.
// Function to submit the data to be DB on clicking the submit button...
function test_ajax_form_action(){
db_update('fbss_comments')
->fields(array('comment' => $form_state['values']['comment']))
->condition('cid', $form['#cid'])
->execute();
if ($_GET['destination'] && $_GET['destination'] != 'fbss_comments/js/refresh') {
$form_state['redirect'] = $_GET['destination'];
} else {
$form_state['redirect'] = '';
}
drupal_set_message(t('Status comment has been successfully edited.'));
}
Drupal's Ajax framework is used to dynamically update parts of a page's HTML based on data from the server. Upon a specified event, such as a button click, a callback function is triggered which performs server-side logic and may return updated markup, which is then replaced on-the-fly with no page refresh necessary.
This framework creates a PHP macro language that allows the server to instruct JavaScript to perform actions on the client browser. When using forms, it can be used with the #ajax property. The #ajax property can be used to bind events to the Ajax framework. By default, #ajax uses 'system/ajax' as its path for submission and thus calls ajax_form_callback() and a defined #ajax['callback'] function. However, you may optionally specify a different path to request or a different callback function to invoke, which can return updated HTML or can also return a richer set of Ajax framework commands.
To implement Ajax handling in a form, add '#ajax' to the form definition of a field. That field will trigger an Ajax event when it is clicked (or changed, depending on the kind of field). #ajax supports the following parameters (either 'path' or 'callback' is required at least):
#ajax['callback']:
The callback to invoke to handle the server side of the Ajax event, which will receive a $form and $form_state as arguments, and returns a renderable array (most often a form or form fragment), an HTML string, or an array of Ajax commands. If returning a renderable array or a string, the value will replace the original element named in #ajax['wrapper'], and theme_status_messages() will be prepended to that element. (If the status messages are not wanted, return an array of Ajax commands instead.) #ajax['wrapper'] If an array of Ajax commands is returned, it will be executed by the calling code.
#ajax['path']:
The menu path to use for the request. This is often omitted and the default is used. This path should map to a menu page callback that returns data using ajax_render(). Defaults to 'system/ajax', which invokes ajax_form_callback(), eventually calling the function named in #ajax['callback']. If you use a custom path, you must set up the menu entry and handle the entire callback in your own code.
#ajax['wrapper']:
The CSS ID of the area to be replaced by the content returned by the #ajax['callback'] function. The content returned from the callback will replace the entire element named by #ajax['wrapper']. The wrapper is usually created using #prefix and #suffix properties in the form. Note that this is the wrapper ID, not a CSS selector. So to replace the element referred to by the CSS selector #some-selector on the page, use #ajax['wrapper'] = 'some-selector', not '#some-selector'.
#ajax['effect']:
The jQuery effect to use when placing the new HTML. Defaults to no effect. Valid options are 'none', 'slide', or 'fade'.
#ajax['speed']:
The effect speed to use. Defaults to 'slow'. May be 'slow', 'fast' or a number in milliseconds which represents the length of time the effect should run.
#ajax['event']:
The JavaScript event to respond to. This is normally selected automatically for the type of form widget being used, and is only needed if you need to override the default behavior.
#ajax['prevent']:
A JavaScript event to prevent when 'event' is triggered. Defaults to 'click' for #ajax on #type 'submit', 'button', and 'image_button'. Multiple events may be specified separated by spaces. For example, when binding #ajax behaviors to form buttons, pressing the ENTER key within a textfield triggers the 'click' event of the form's first submit button. Triggering Ajax in this situation leads to problems, like breaking autocomplete textfields. Because of that, Ajax behaviors are bound to the 'mousedown' event on form buttons by default. However, binding to 'mousedown' rather than 'click' means that it is possible to trigger a click by pressing the mouse, holding the mouse button down until the Ajax request is complete and the button is re-enabled, and then releasing the mouse button. For this case, 'prevent' can be set to 'click', so an additional event handler is bound to prevent such a click from triggering a non-Ajax form submission. This also prevents a textfield's ENTER press triggering a button's non-Ajax form submission behavior.
#ajax['method']:
The jQuery method to use to place the new HTML. Defaults to 'replaceWith'. May be: 'replaceWith', 'append', 'prepend', 'before', 'after', or 'html'. See the jQuery manipulators documentation for more information on these methods.
#ajax['progress']:
Choose either a throbber or progress bar that is displayed while awaiting a response from the callback, and add an optional message. Possible keys: 'type', 'message', 'url', 'interval'.
More information is available in the Form API Reference
AJAX-enabled forms in Drupal 7 offer dynamic form behavior with no page reloads and are easy to create and manipulate. They are a simple extension of the Drupal Form API.
To create an AJAX-enabled form, you:
- Mark a form element as AJAX-enabled using the #ajax property. This form element will now trigger a background AJAX call when it is changed or clicked.
- The #ajax['wrapper'] property includes the HTML ID of a page section that should be replaced (or altered in some other way).
- The #ajax['callback'] tells the Form system what callback should be called after the AJAX call happens and the form is rebuilt
- Create a callback function (named by the #ajax['callback']). This is generally a very simple function which does nothing but select and return the portion of the form that is to be replaced on the original page.
:For EXAMPLE:
/**
* AJAX-enabled select element causes replacement of a set of checkboxes
* based on the selection.
*/
function ajax_example_autocheckboxes($form, &$form_state) {
$default = !empty($form_state['values']['howmany_select']) ? $form_state['values']['howmany_select'] : 1;
$form['howmany_select'] = array(
'#title' => t('How many checkboxes do you want?'),
'#type' => 'select',
'#options' => array(1 => 1, 2 => 2, 3 => 3, 4 => 4),
'#default_value' => $default,
'#ajax' => array(
'callback' => 'ajax_example_autocheckboxes_callback',
'wrapper' => 'checkboxes-div',
'method' => 'replace',
'effect' => 'fade',
),
);
$form['checkboxes_fieldset'] = array(
'#title' => t("Generated Checkboxes"),
// The prefix/suffix provide the div that we're replacing, named by
// #ajax['wrapper'] above.
'#prefix' => '',
'#suffix' => '',
'#type' => 'fieldset',
'#description' => t('This is where we get automatically generated checkboxes'),
);
$num_checkboxes = !empty($form_state['values']['howmany_select']) ? $form_state['values']['howmany_select'] : 1;
for ($i = 1; $i <= $num_checkboxes; $i++) {
$form['checkboxes_fieldset']["checkbox$i"] = array(
'#type' => 'checkbox',
'#title' => "Checkbox $i",
);
}
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
/**
* Callback element needs only select the portion of the form to be updated.
* Since #ajax['callback'] return can be HTML or a renderable array (or an
* array of commands), we can just return a piece of the form.
*/
function ajax_example_autocheckboxes_callback($form, $form_state) {
return $form['checkboxes_fieldset'];
}
Here,
- The form is presented to the user, as any form would be.
- In the form, a div with an HTML ID of 'checkboxes-div' wraps $form['checkboxes']. This is done with
$form['checkboxes']['#prefix'] and $form['checkboxes']['#suffix']. - If the user changes $form['howmany_select'], a background request is made to the server, causing the form to be rebuilt.
- The form is rebuilt, with as many checkboxes as were requested by $form['howmany_select'].
- ajax_example_autocheckboxes_callback() is called. It selects the piece of the form which is to be replaced on the page
(almost always the same as what's in #ajax['wrapper']). - The portion returned is rendered, sent back to the page, and the div with id 'checkboxes-div' is replaced on the page.
// Add extra function to execute prior validations so as to merge the two entries...
array_unshift($form['#validate'], 'merge_infi_recipients_to_forward');
-------------------------------------------------------------------------------------------------
:: All Basic AJAX functions and its explanations as of in ajax.in located as /includes/ ::
-------------------------------------------------------------------------------------------------
| function ajax_render($commands = array()) | Renders a commands array into JSON. | $commands is a list of macro commands generated by the use of ajax_command_*() functions |
| function ajax_get_form() | Gets a form submitted via #ajax during an Ajax callback. This will load a form from the form cache used during Ajax operations. It pulls the form info from $_POST. |
Returns An array containing the $form and $form_state. Use the list() function to break these apart: * @code * list($form, $form_state, $form_id, $form_build_id) = ajax_get_form(); * @endcode |
| function ajax_form_callback() | Menu callback; handles Ajax requests for the #ajax Form API property. | Add extra function to execute prior validations so as to merge the two entries... array_unshift($form['#validate'], 'merge_infi_recipients_to_forward'); This rebuilds the form from cache and invokes the defined #ajax['callback'] to return an Ajax command structure for JavaScript. In case no 'callback' has been defined, nothing will happen. The Form API #ajax property can be set both for buttons This function is also the canonical example of how to |
| function ajax_base_page_theme() | Theme callback for Ajax requests. | Many different pages can invoke an Ajax request to system/ajax or another generic Ajax path. It is almost always desired for an Ajax response to be rendered using the same theme as the base page, because most themes are built with the assumption that they control the entire page, so if the CSS for two themes are both loaded for a given page, they may conflict with each other. For example, Bartik is Drupal's default theme, and Seven is Drupal's default administration theme.Depending on whether the "Use the administration theme when editing or creating content" checkbox is checked, the node edit form may be displayed in either theme, but the Ajax response to the Field module's "Add another item" button should be rendered using the same theme as the rest of the page. Therefore, system_menu() sets the 'theme callback' for 'system/ajax' to this function, and it is recommended that modules implementing other generic Ajax paths do the same. |
| function ajax_deliver($page_callback_result) | Packages and sends the result of a page callback as an Ajax response. | This function is the equivalent of drupal_deliver_html_page(), but for Ajax requests. Like that function, it: * - Adds needed HTTP headers. * - Prints rendered output. * - Performs end-of-request tasks. * @param $page_callback_result - The result of a page callback. Can be one of: - NULL: to indicate no content. - An integer menu status constant: to indicate an error condition. - A string of HTML content. - A renderable array of content. |
| function ajax_prepare_response($page_callback_result) | Converts the return value of a page callback into an Ajax commands array. | * @param $page_callback_result - The result of a page callback. Can be one of: - NULL: to indicate no content. - An integer menu status constant: to indicate an error condition. - A string of HTML content. - A renderable array of content. * @return - An Ajax commands array that can be passed to ajax_render(). |
| function ajax_footer() | Performs end-of-Ajax-request tasks. | This function is the equivalent of drupal_page_footer(), but for Ajax requests. |
| function ajax_process_form($element, &$form_state) | Form element processing handler for the #ajax form property. | * @param $element An associative array containing the properties of the element. * @return The processed element. |
| function ajax_pre_render_element($element) | Adds Ajax information about an element to communicate with JavaScript. | If #ajax['path'] is set on an element, this additional JavaScript is added to the page header to attach the Ajax behaviors. See ajax.js for more information. * @param $element An associative array containing the properties of the element. Properties used: - #ajax['event'] - #ajax['prevent'] - #ajax['path'] - #ajax['options'] - #ajax['wrapper'] - #ajax['parameters'] - #ajax['effect'] * @return The processed element with the necessary JavaScript attached to it. |
| function ajax_command_alert($text) | Creates a Drupal Ajax 'alert' command. | The 'alert' command instructs the client to display a JavaScript alert dialog box. This command is implemented by Drupal.ajax.prototype.commands.alert() defined in misc/ajax.js. * @param $text The message string to display to the user. * @return An array suitable for use with the ajax_render() function. |
| function ajax_command_insert($selector, $html, $settings = NULL) | Creates a Drupal Ajax 'insert' command using the method in #ajax['method']. | This command instructs the client to insert the given HTML using whichever jQuery DOM manipulation method has been specified in the #ajax['method'] variable of the element that triggered the request. This command is implemented by Drupal.ajax.prototype.commands.insert() defined in misc/ajax.js. * @param $selector A jQuery selector string. If the command is a response to a request from an #ajax form element then this value can be NULL. * @param $html The data to use with the jQuery method. * @param $settings An optional array of settings that will be used for this command only. * @return An array suitable for use with the ajax_render() function. |
| function ajax_command_replace($selector, $html, $settings = NULL) | Creates a Drupal Ajax 'insert/replaceWith' command. | The 'insert/replaceWith' command instructs the client to use jQuery's replaceWith() method to replace each element matched matched by the given selector with the given HTML. This command is implemented by Drupal.ajax.prototype.commands.insert() defined in misc/ajax.js. * @param $selector A jQuery selector string. If the command is a response to a request from an #ajax form element then this value can be NULL. * @param $html The data to use with the jQuery replaceWith() method. * @param $settings An optional array of settings that will be used for this command only. * @return An array suitable for use with the ajax_render() function. |
| function ajax_command_html($selector, $html, $settings = NULL) | Creates a Drupal Ajax 'insert/html' command. | The 'insert/html' command instructs the client to use jQuery's html() method to set the HTML content of each element matched by the given selector while leaving the outer tags intact. This command is implemented by Drupal.ajax.prototype.commands.insert() defined in misc/ajax.js. * @param $selector A jQuery selector string. If the command is a response to a request from an #ajax form element then this value can be NULL. * @param $html The data to use with the jQuery html() method. * @param $settings An optional array of settings that will be used for this command only. * @return An array suitable for use with the ajax_render() function. |
| function ajax_command_prepend($selector, $html, $settings = NULL) | Creates a Drupal Ajax 'insert/prepend' command. | The 'insert/prepend' command instructs the client to use jQuery's prepend() method to prepend the given HTML content to the inside each element matched by the given selector. This command is implemented by Drupal.ajax.prototype.commands.insert() defined in misc/ajax.js. * @param $selector A jQuery selector string. If the command is a response to a request from an #ajax form element then this value can be NULL. * @param $html The data to use with the jQuery prepend() method. * @param $settings An optional array of settings that will be used for this command only. * @return An array suitable for use with the ajax_render() function. |
| function ajax_command_append($selector, $html, $settings = NULL) | Creates a Drupal Ajax 'insert/append' command. | The 'insert/append' command instructs the client to use jQuery's append() method to append the given HTML content to the inside of each element matched by the given selector. This command is implemented by Drupal.ajax.prototype.commands.insert() defined in misc/ajax.js. * @param $selector A jQuery selector string. If the command is a response to a request from an #ajax form element then this value can be NULL. * @param $html The data to use with the jQuery append() method. * @param $settings An optional array of settings that will be used for this command only. * @return An array suitable for use with the ajax_render() function. |
| function ajax_command_after($selector, $html, $settings = NULL) | Creates a Drupal Ajax 'insert/after' command. | The 'insert/after' command instructs the client to use jQuery's after() method to insert the given HTML content after each element matched by the given selector. This command is implemented by Drupal.ajax.prototype.commands.insert() defined in misc/ajax.js. * @param $selector A jQuery selector string. If the command is a response to a request from an #ajax form element then this value can be NULL. * @param $html The data to use with the jQuery after() method. * @param $settings An optional array of settings that will be used for this command only. * @return An array suitable for use with the ajax_render() function. |
| function ajax_command_before($selector, $html, $settings = NULL) | Creates a Drupal Ajax 'insert/before' command. | The 'insert/before' command instructs the client to use jQuery's before() method to insert the given HTML content before each of elements matched by the given selector. This command is implemented by Drupal.ajax.prototype.commands.insert() defined in misc/ajax.js. * @param $selector A jQuery selector string. If the command is a response to a request from an #ajax form element then this value can be NULL. * @param $html The data to use with the jQuery before() method. * @param $settings An optional array of settings that will be used for this command only. * @return An array suitable for use with the ajax_render() function. |
| function ajax_command_remove($selector) | Creates a Drupal Ajax 'remove' command. | The 'remove' command instructs the client to use jQuery's remove() method to remove each of elements matched by the given selector, and everything within them. This command is implemented by Drupal.ajax.prototype.commands.remove() defined in misc/ajax.js. * @param $selector A jQuery selector string. If the command is a response to a request from an #ajax form element then this value can be NULL. * @return An array suitable for use with the ajax_render() function. |
| function ajax_command_changed($selector, $asterisk = '') | Creates a Drupal Ajax 'changed' command. | This command instructs the client to mark each of the elements matched by the given selector as 'ajax-changed'. This command is implemented by Drupal.ajax.prototype.commands.changed() defined in misc/ajax.js. * @param $selector A jQuery selector string. If the command is a response to a request from an #ajax form element then this value can be NULL. * @param $asterisk An optional CSS selector which must be inside $selector. If specified, an asterisk will be appended to the HTML inside the $asterisk selector. * @return An array suitable for use with the ajax_render() function. |
| function ajax_command_css($selector, $argument) | Creates a Drupal Ajax 'css' command. | The 'css' command will instruct the client to use the jQuery css() method to apply the CSS arguments to elements matched by the given selector. This command is implemented by Drupal.ajax.prototype.commands.css() defined in misc/ajax.js. * @param $selector A jQuery selector string. If the command is a response to a request from an #ajax form element then this value can be NULL. * @param $argument An array of key/value pairs to set in the CSS for the selector. * @return An array suitable for use with the ajax_render() function. |
| function ajax_command_settings($argument, $merge = FALSE) | Creates a Drupal Ajax 'settings' command. | The 'settings' command instructs the client either to use the given array as the settings for ajax-loaded content or to extend Drupal.settings with the given array, depending on the value of the $merge parameter. This command is implemented by Drupal.ajax.prototype.commands.settings() defined in misc/ajax.js. * @param $argument An array of key/value pairs to add to the settings. This will be utilized for all commands after this if they do not include their own settings array. * @param $merge Whether or not the passed settings in $argument should be merged into the global Drupal.settings on the page. By default (FALSE), the settings that are passed to Drupal.attachBehaviors will not include the global Drupal.settings. * @return An array suitable for use with the ajax_render() function. |
| function ajax_command_data($selector, $name, $value) | Creates a Drupal Ajax 'data' command. | The 'data' command instructs the client to attach the name=value pair of data to the selector via jQuery's data cache. This command is implemented by Drupal.ajax.prototype.commands.data() defined in misc/ajax.js. * @param $selector A jQuery selector string. If the command is a response to a request from an #ajax form element then this value can be NULL. * @param $name The name or key (in the key value pair) of the data attached to this selector. * @param $value The value of the data. Not just limited to strings can be any format. * @return An array suitable for use with the ajax_render() function. |
| function ajax_command_invoke($selector, $method, array $arguments = array()) | Creates a Drupal Ajax 'invoke' command. | The 'invoke' command will instruct the client to invoke the given jQuery method with the supplied arguments on the elements matched by the given selector. Intended for simple jQuery commands, such as attr(), addClass(), removeClass(), toggleClass(), etc. This command is implemented by Drupal.ajax.prototype.commands.invoke() defined in misc/ajax.js. * @param $selector A jQuery selector string. If the command is a response to a request from an #ajax form element then this value can be NULL. * @param $method The jQuery method to invoke. * @param $arguments (optional) A list of arguments to the jQuery $method, if any. * @return An array suitable for use with the ajax_render() function. |
| function ajax_command_restripe($selector) | Creates a Drupal Ajax 'restripe' command. | The 'restripe' command instructs the client to restripe a table. This is usually used after a table has been modified by a replace or append command. This command is implemented by Drupal.ajax.prototype.commands.restripe() defined in misc/ajax.js. * @param $selector A jQuery selector string. * @return An array suitable for use with the ajax_render() function. |
Add new comment