Functions for use with Drupal's Ajax framework.

File

includes/ajax.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Functions for use with Drupal's Ajax framework.
  5. */
  6. /**
  7. * @defgroup ajax Ajax framework
  8. * @{
  9. * Functions for Drupal's Ajax framework.
  10. *
  11. * Drupal's Ajax framework is used to dynamically update parts of a page's HTML
  12. * based on data from the server. Upon a specified event, such as a button
  13. * click, a callback function is triggered which performs server-side logic and
  14. * may return updated markup, which is then replaced on-the-fly with no page
  15. * refresh necessary.
  16. *
  17. * This framework creates a PHP macro language that allows the server to
  18. * instruct JavaScript to perform actions on the client browser. When using
  19. * forms, it can be used with the #ajax property.
  20. * The #ajax property can be used to bind events to the Ajax framework. By
  21. * default, #ajax uses 'system/ajax' as its path for submission and thus calls
  22. * ajax_form_callback() and a defined #ajax['callback'] function.
  23. * However, you may optionally specify a different path to request or a
  24. * different callback function to invoke, which can return updated HTML or can
  25. * also return a richer set of
  26. * @link ajax_commands Ajax framework commands @endlink.
  27. *
  28. * Standard form handling is as follows:
  29. * - A form element has a #ajax property that includes #ajax['callback'] and
  30. * omits #ajax['path']. See below about using #ajax['path'] to implement
  31. * advanced use-cases that require something other than standard form
  32. * handling.
  33. * - On the specified element, Ajax processing is triggered by a change to
  34. * that element.
  35. * - The browser submits an HTTP POST request to the 'system/ajax' Drupal
  36. * path.
  37. * - The menu page callback for 'system/ajax', ajax_form_callback(), calls
  38. * drupal_process_form() to process the form submission and rebuild the
  39. * form if necessary. The form is processed in much the same way as if it
  40. * were submitted without Ajax, with the same #process functions and
  41. * validation and submission handlers called in either case, making it easy
  42. * to create Ajax-enabled forms that degrade gracefully when JavaScript is
  43. * disabled.
  44. * - After form processing is complete, ajax_form_callback() calls the
  45. * function named by #ajax['callback'], which returns the form element that
  46. * has been updated and needs to be returned to the browser, or
  47. * alternatively, an array of custom Ajax commands.
  48. * - The page delivery callback for 'system/ajax', ajax_deliver(), renders the
  49. * element returned by #ajax['callback'], and returns the JSON string
  50. * created by ajax_render() to the browser.
  51. * - The browser unserializes the returned JSON string into an array of
  52. * command objects and executes each command, resulting in the old page
  53. * content within and including the HTML element specified by
  54. * #ajax['wrapper'] being replaced by the new content returned by
  55. * #ajax['callback'], using a JavaScript animation effect specified by
  56. * #ajax['effect'].
  57. *
  58. * A simple example of basic Ajax use from the
  59. * @link http://drupal.org/project/examples Examples module @endlink follows:
  60. * @code
  61. * function main_page() {
  62. * return drupal_get_form('ajax_example_simplest');
  63. * }
  64. *
  65. * function ajax_example_simplest($form, &$form_state) {
  66. * $form = array();
  67. * $form['changethis'] = array(
  68. * '#type' => 'select',
  69. * '#options' => array(
  70. * 'one' => 'one',
  71. * 'two' => 'two',
  72. * 'three' => 'three',
  73. * ),
  74. * '#ajax' => array(
  75. * 'callback' => 'ajax_example_simplest_callback',
  76. * 'wrapper' => 'replace_textfield_div',
  77. * ),
  78. * );
  79. * // This entire form element will be replaced with an updated value.
  80. * $form['replace_textfield'] = array(
  81. * '#type' => 'textfield',
  82. * '#title' => t("The default value will be changed"),
  83. * '#description' => t("Say something about why you chose") . "'" .
  84. * (!empty($form_state['values']['changethis'])
  85. * ? $form_state['values']['changethis'] : t("Not changed yet")) . "'",
  86. * '#prefix' => '<div id="replace_textfield_div">',
  87. * '#suffix' => '</div>',
  88. * );
  89. * return $form;
  90. * }
  91. *
  92. * function ajax_example_simplest_callback($form, $form_state) {
  93. * // The form has already been submitted and updated. We can return the replaced
  94. * // item as it is.
  95. * return $form['replace_textfield'];
  96. * }
  97. * @endcode
  98. *
  99. * In the above example, the 'changethis' element is Ajax-enabled. The default
  100. * #ajax['event'] is 'change', so when the 'changethis' element changes,
  101. * an Ajax call is made. The form is submitted and reprocessed, and then the
  102. * callback is called. In this case, the form has been automatically
  103. * built changing $form['replace_textfield']['#description'], so the callback
  104. * just returns that part of the form.
  105. *
  106. * To implement Ajax handling in a form, add '#ajax' to the form
  107. * definition of a field. That field will trigger an Ajax event when it is
  108. * clicked (or changed, depending on the kind of field). #ajax supports
  109. * the following parameters (either 'path' or 'callback' is required at least):
  110. * - #ajax['callback']: The callback to invoke to handle the server side of the
  111. * Ajax event, which will receive a $form and $form_state as arguments, and
  112. * returns a renderable array (most often a form or form fragment), an HTML
  113. * string, or an array of Ajax commands. If returning a renderable array or
  114. * a string, the value will replace the original element named in
  115. * #ajax['wrapper'], and
  116. * theme_status_messages()
  117. * will be prepended to that
  118. * element. (If the status messages are not wanted, return an array
  119. * of Ajax commands instead.)
  120. * #ajax['wrapper']. If an array of Ajax commands is returned, it will be
  121. * executed by the calling code.
  122. * - #ajax['path']: The menu path to use for the request. This is often omitted
  123. * and the default is used. This path should map
  124. * to a menu page callback that returns data using ajax_render(). Defaults to
  125. * 'system/ajax', which invokes ajax_form_callback(), eventually calling
  126. * the function named in #ajax['callback']. If you use a custom
  127. * path, you must set up the menu entry and handle the entire callback in your
  128. * own code.
  129. * - #ajax['wrapper']: The CSS ID of the area to be replaced by the content
  130. * returned by the #ajax['callback'] function. The content returned from
  131. * the callback will replace the entire element named by #ajax['wrapper'].
  132. * The wrapper is usually created using #prefix and #suffix properties in the
  133. * form. Note that this is the wrapper ID, not a CSS selector. So to replace
  134. * the element referred to by the CSS selector #some-selector on the page,
  135. * use #ajax['wrapper'] = 'some-selector', not '#some-selector'.
  136. * - #ajax['effect']: The jQuery effect to use when placing the new HTML.
  137. * Defaults to no effect. Valid options are 'none', 'slide', or 'fade'.
  138. * - #ajax['speed']: The effect speed to use. Defaults to 'slow'. May be
  139. * 'slow', 'fast' or a number in milliseconds which represents the length
  140. * of time the effect should run.
  141. * - #ajax['event']: The JavaScript event to respond to. This is normally
  142. * selected automatically for the type of form widget being used, and
  143. * is only needed if you need to override the default behavior.
  144. * - #ajax['prevent']: A JavaScript event to prevent when 'event' is triggered.
  145. * Defaults to 'click' for #ajax on #type 'submit', 'button', and
  146. * 'image_button'. Multiple events may be specified separated by spaces.
  147. * For example, when binding #ajax behaviors to form buttons, pressing the
  148. * ENTER key within a textfield triggers the 'click' event of the form's first
  149. * submit button. Triggering Ajax in this situation leads to problems, like
  150. * breaking autocomplete textfields. Because of that, Ajax behaviors are bound
  151. * to the 'mousedown' event on form buttons by default. However, binding to
  152. * 'mousedown' rather than 'click' means that it is possible to trigger a
  153. * click by pressing the mouse, holding the mouse button down until the Ajax
  154. * request is complete and the button is re-enabled, and then releasing the
  155. * mouse button. For this case, 'prevent' can be set to 'click', so an
  156. * additional event handler is bound to prevent such a click from triggering a
  157. * non-Ajax form submission. This also prevents a textfield's ENTER press
  158. * triggering a button's non-Ajax form submission behavior.
  159. * - #ajax['method']: The jQuery method to use to place the new HTML.
  160. * Defaults to 'replaceWith'. May be: 'replaceWith', 'append', 'prepend',
  161. * 'before', 'after', or 'html'. See the
  162. * @link http://api.jquery.com/category/manipulation/ jQuery manipulators documentation @endlink
  163. * for more information on these methods.
  164. * - #ajax['progress']: Choose either a throbber or progress bar that is
  165. * displayed while awaiting a response from the callback, and add an optional
  166. * message. Possible keys: 'type', 'message', 'url', 'interval'.
  167. * More information is available in the
  168. * @link forms_api_reference.html Form API Reference @endlink
  169. *
  170. * In addition to using Form API for doing in-form modification, Ajax may be
  171. * enabled by adding classes to buttons and links. By adding the 'use-ajax'
  172. * class to a link, the link will be loaded via an Ajax call. When using this
  173. * method, the href of the link can contain '/nojs/' as part of the path. When
  174. * the Ajax framework makes the request, it will convert this to '/ajax/'.
  175. * The server is then able to easily tell if this request was made through an
  176. * actual Ajax request or in a degraded state, and respond appropriately.
  177. *
  178. * Similarly, submit buttons can be given the class 'use-ajax-submit'. The
  179. * form will then be submitted via Ajax to the path specified in the #action.
  180. * Like the ajax-submit class above, this path will have '/nojs/' replaced with
  181. * '/ajax/' so that the submit handler can tell if the form was submitted
  182. * in a degraded state or not.
  183. *
  184. * When responding to Ajax requests, the server should do what it needs to do
  185. * for that request, then create a commands array. This commands array will
  186. * be converted to a JSON object and returned to the client, which will then
  187. * iterate over the array and process it like a macro language.
  188. *
  189. * Each command item is an associative array which will be converted to a
  190. * command object on the JavaScript side. $command_item['command'] is the type
  191. * of command, e.g. 'alert' or 'replace', and will correspond to a method in the
  192. * Drupal.ajax[command] space. The command array may contain any other data that
  193. * the command needs to process, e.g. 'method', 'selector', 'settings', etc.
  194. *
  195. * Commands are usually created with a couple of helper functions, so they
  196. * look like this:
  197. * @code
  198. * $commands = array();
  199. * // Replace the content of '#object-1' on the page with 'some html here'.
  200. * $commands[] = ajax_command_replace('#object-1', 'some html here');
  201. * // Add a visual "changed" marker to the '#object-1' element.
  202. * $commands[] = ajax_command_changed('#object-1');
  203. * // Menu 'page callback' and #ajax['callback'] functions are supposed to
  204. * // return render arrays. If returning an Ajax commands array, it must be
  205. * // encapsulated in a render array structure.
  206. * return array('#type' => 'ajax', '#commands' => $commands);
  207. * @endcode
  208. *
  209. * When returning an Ajax command array, it is often useful to have
  210. * status messages rendered along with other tasks in the command array.
  211. * In that case the Ajax commands array may be constructed like this:
  212. * @code
  213. * $commands = array();
  214. * $commands[] = ajax_command_replace(NULL, $output);
  215. * $commands[] = ajax_command_prepend(NULL, theme('status_messages'));
  216. * return array('#type' => 'ajax', '#commands' => $commands);
  217. * @endcode
  218. *
  219. * See @link ajax_commands Ajax framework commands @endlink
  220. */
  221. /**
  222. * Renders a commands array into JSON.
  223. *
  224. * @param $commands
  225. * A list of macro commands generated by the use of ajax_command_*()
  226. * functions.
  227. */
  228. function ajax_render($commands = array()) {
  229. // Although ajax_deliver() does this, some contributed and custom modules
  230. // render Ajax responses without using that delivery callback.
  231. ajax_set_verification_header();
  232. // Ajax responses aren't rendered with html.tpl.php, so we have to call
  233. // drupal_get_css() and drupal_get_js() here, in order to have new files added
  234. // during this request to be loaded by the page. We only want to send back
  235. // files that the page hasn't already loaded, so we implement simple diffing
  236. // logic using array_diff_key().
  237. foreach (array('css', 'js') as $type) {
  238. // It is highly suspicious if $_POST['ajax_page_state'][$type] is empty,
  239. // since the base page ought to have at least one JS file and one CSS file
  240. // loaded. It probably indicates an error, and rather than making the page
  241. // reload all of the files, instead we return no new files.
  242. if (empty($_POST['ajax_page_state'][$type])) {
  243. $items[$type] = array();
  244. }
  245. else {
  246. $function = 'drupal_add_' . $type;
  247. $items[$type] = $function();
  248. drupal_alter($type, $items[$type]);
  249. // @todo Inline CSS and JS items are indexed numerically. These can't be
  250. // reliably diffed with array_diff_key(), since the number can change
  251. // due to factors unrelated to the inline content, so for now, we strip
  252. // the inline items from Ajax responses, and can add support for them
  253. // when drupal_add_css() and drupal_add_js() are changed to use a hash
  254. // of the inline content as the array key.
  255. foreach ($items[$type] as $key => $item) {
  256. if (is_numeric($key)) {
  257. unset($items[$type][$key]);
  258. }
  259. }
  260. // Ensure that the page doesn't reload what it already has.
  261. $items[$type] = array_diff_key($items[$type], $_POST['ajax_page_state'][$type]);
  262. }
  263. }
  264. // Render the HTML to load these files, and add AJAX commands to insert this
  265. // HTML in the page. We pass TRUE as the $skip_alter argument to prevent the
  266. // data from being altered again, as we already altered it above. Settings are
  267. // handled separately, afterwards.
  268. if (isset($items['js']['settings'])) {
  269. unset($items['js']['settings']);
  270. }
  271. $styles = drupal_get_css($items['css'], TRUE);
  272. $scripts_footer = drupal_get_js('footer', $items['js'], TRUE);
  273. $scripts_header = drupal_get_js('header', $items['js'], TRUE);
  274. $extra_commands = array();
  275. if (!empty($styles)) {
  276. $extra_commands[] = ajax_command_add_css($styles);
  277. }
  278. if (!empty($scripts_header)) {
  279. $extra_commands[] = ajax_command_prepend('head', $scripts_header);
  280. }
  281. if (!empty($scripts_footer)) {
  282. $extra_commands[] = ajax_command_append('body', $scripts_footer);
  283. }
  284. if (!empty($extra_commands)) {
  285. $commands = array_merge($extra_commands, $commands);
  286. }
  287. // Now add a command to merge changes and additions to Drupal.settings.
  288. $scripts = drupal_add_js();
  289. if (!empty($scripts['settings'])) {
  290. $settings = $scripts['settings'];
  291. array_unshift($commands, ajax_command_settings(drupal_array_merge_deep_array($settings['data']), TRUE));
  292. }
  293. // Allow modules to alter any Ajax response.
  294. drupal_alter('ajax_render', $commands);
  295. return drupal_json_encode($commands);
  296. }
  297. /**
  298. * Gets a form submitted via #ajax during an Ajax callback.
  299. *
  300. * This will load a form from the form cache used during Ajax operations. It
  301. * pulls the form info from $_POST.
  302. *
  303. * @return
  304. * An array containing the $form, $form_state, $form_id, $form_build_id and an
  305. * initial list of Ajax $commands. Use the list() function to break these
  306. * apart:
  307. * @code
  308. * list($form, $form_state, $form_id, $form_build_id, $commands) = ajax_get_form();
  309. * @endcode
  310. */
  311. function ajax_get_form() {
  312. $form_state = form_state_defaults();
  313. $form_build_id = $_POST['form_build_id'];
  314. // Get the form from the cache.
  315. $form = form_get_cache($form_build_id, $form_state);
  316. if (!$form) {
  317. // If $form cannot be loaded from the cache, the form_build_id in $_POST
  318. // must be invalid, which means that someone performed a POST request onto
  319. // system/ajax without actually viewing the concerned form in the browser.
  320. // This is likely a hacking attempt as it never happens under normal
  321. // circumstances, so we just do nothing.
  322. watchdog('ajax', 'Invalid form POST data.', array(), WATCHDOG_WARNING);
  323. drupal_exit();
  324. }
  325. // When a page level cache is enabled, the form-build id might have been
  326. // replaced from within form_get_cache. If this is the case, it is also
  327. // necessary to update it in the browser by issuing an appropriate Ajax
  328. // command.
  329. $commands = array();
  330. if (isset($form['#build_id_old']) && $form['#build_id_old'] != $form['#build_id']) {
  331. // If the form build ID has changed, issue an Ajax command to update it.
  332. $commands[] = ajax_command_update_build_id($form);
  333. $form_build_id = $form['#build_id'];
  334. }
  335. // Since some of the submit handlers are run, redirects need to be disabled.
  336. $form_state['no_redirect'] = TRUE;
  337. // When a form is rebuilt after Ajax processing, its #build_id and #action
  338. // should not change.
  339. // @see drupal_rebuild_form()
  340. $form_state['rebuild_info']['copy']['#build_id'] = TRUE;
  341. $form_state['rebuild_info']['copy']['#action'] = TRUE;
  342. // The form needs to be processed; prepare for that by setting a few internal
  343. // variables.
  344. $form_state['input'] = $_POST;
  345. $form_id = $form['#form_id'];
  346. return array($form, $form_state, $form_id, $form_build_id, $commands);
  347. }
  348. /**
  349. * Menu callback; handles Ajax requests for the #ajax Form API property.
  350. *
  351. * This rebuilds the form from cache and invokes the defined #ajax['callback']
  352. * to return an Ajax command structure for JavaScript. In case no 'callback' has
  353. * been defined, nothing will happen.
  354. *
  355. * The Form API #ajax property can be set both for buttons and other input
  356. * elements.
  357. *
  358. * This function is also the canonical example of how to implement
  359. * #ajax['path']. If processing is required that cannot be accomplished with
  360. * a callback, re-implement this function and set #ajax['path'] to the
  361. * enhanced function.
  362. *
  363. * @see system_menu()
  364. */
  365. function ajax_form_callback() {
  366. list($form, $form_state, $form_id, $form_build_id, $commands) = ajax_get_form();
  367. drupal_process_form($form['#form_id'], $form, $form_state);
  368. // We need to return the part of the form (or some other content) that needs
  369. // to be re-rendered so the browser can update the page with changed content.
  370. // Since this is the generic menu callback used by many Ajax elements, it is
  371. // up to the #ajax['callback'] function of the element (may or may not be a
  372. // button) that triggered the Ajax request to determine what needs to be
  373. // rendered.
  374. if (!empty($form_state['triggering_element'])) {
  375. $callback = $form_state['triggering_element']['#ajax']['callback'];
  376. }
  377. if (!empty($callback) && function_exists($callback)) {
  378. $result = $callback($form, $form_state);
  379. if (!(is_array($result) && isset($result['#type']) && $result['#type'] == 'ajax')) {
  380. // Turn the response into a #type=ajax array if it isn't one already.
  381. $result = array(
  382. '#type' => 'ajax',
  383. '#commands' => ajax_prepare_response($result),
  384. );
  385. }
  386. $result['#commands'] = array_merge($commands, $result['#commands']);
  387. return $result;
  388. }
  389. }
  390. /**
  391. * Theme callback for Ajax requests.
  392. *
  393. * Many different pages can invoke an Ajax request to system/ajax or another
  394. * generic Ajax path. It is almost always desired for an Ajax response to be
  395. * rendered using the same theme as the base page, because most themes are built
  396. * with the assumption that they control the entire page, so if the CSS for two
  397. * themes are both loaded for a given page, they may conflict with each other.
  398. * For example, Bartik is Drupal's default theme, and Seven is Drupal's default
  399. * administration theme. Depending on whether the "Use the administration theme
  400. * when editing or creating content" checkbox is checked, the node edit form may
  401. * be displayed in either theme, but the Ajax response to the Field module's
  402. * "Add another item" button should be rendered using the same theme as the rest
  403. * of the page. Therefore, system_menu() sets the 'theme callback' for
  404. * 'system/ajax' to this function, and it is recommended that modules
  405. * implementing other generic Ajax paths do the same.
  406. *
  407. * @see system_menu()
  408. * @see file_menu()
  409. */
  410. function ajax_base_page_theme() {
  411. if (!empty($_POST['ajax_page_state']['theme']) && !empty($_POST['ajax_page_state']['theme_token'])) {
  412. $theme = $_POST['ajax_page_state']['theme'];
  413. $token = $_POST['ajax_page_state']['theme_token'];
  414. // Prevent a request forgery from giving a person access to a theme they
  415. // shouldn't be otherwise allowed to see. However, since everyone is allowed
  416. // to see the default theme, token validation isn't required for that, and
  417. // bypassing it allows most use-cases to work even when accessed from the
  418. // page cache.
  419. if ($theme === variable_get('theme_default', 'bartik') || drupal_valid_token($token, $theme)) {
  420. return $theme;
  421. }
  422. }
  423. }
  424. /**
  425. * Packages and sends the result of a page callback as an Ajax response.
  426. *
  427. * This function is the equivalent of drupal_deliver_html_page(), but for Ajax
  428. * requests. Like that function, it:
  429. * - Adds needed HTTP headers.
  430. * - Prints rendered output.
  431. * - Performs end-of-request tasks.
  432. *
  433. * @param $page_callback_result
  434. * The result of a page callback. Can be one of:
  435. * - NULL: to indicate no content.
  436. * - An integer menu status constant: to indicate an error condition.
  437. * - A string of HTML content.
  438. * - A renderable array of content.
  439. *
  440. * @see drupal_deliver_html_page()
  441. */
  442. function ajax_deliver($page_callback_result) {
  443. // Browsers do not allow JavaScript to read the contents of a user's local
  444. // files. To work around that, the jQuery Form plugin submits forms containing
  445. // a file input element to an IFRAME, instead of using XHR. Browsers do not
  446. // normally expect JSON strings as content within an IFRAME, so the response
  447. // must be customized accordingly.
  448. // @see http://malsup.com/jquery/form/#file-upload
  449. // @see Drupal.ajax.prototype.beforeSend()
  450. $iframe_upload = !empty($_POST['ajax_iframe_upload']);
  451. // Emit a Content-Type HTTP header if none has been added by the page callback
  452. // or by a wrapping delivery callback.
  453. if (is_null(drupal_get_http_header('Content-Type'))) {
  454. if (!$iframe_upload) {
  455. // Standard JSON can be returned to a browser's XHR object, and to
  456. // non-browser user agents.
  457. // @see http://www.ietf.org/rfc/rfc4627.txt?number=4627
  458. drupal_add_http_header('Content-Type', 'application/json; charset=utf-8');
  459. }
  460. else {
  461. // Browser IFRAMEs expect HTML. With most other content types, Internet
  462. // Explorer presents the user with a download prompt.
  463. drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
  464. }
  465. }
  466. // Let ajax.js know that this response is safe to process.
  467. ajax_set_verification_header();
  468. // Print the response.
  469. $commands = ajax_prepare_response($page_callback_result);
  470. $json = ajax_render($commands);
  471. if (!$iframe_upload) {
  472. // Standard JSON can be returned to a browser's XHR object, and to
  473. // non-browser user agents.
  474. print $json;
  475. }
  476. else {
  477. // Browser IFRAMEs expect HTML. Browser extensions, such as Linkification
  478. // and Skype's Browser Highlighter, convert URLs, phone numbers, etc. into
  479. // links. This corrupts the JSON response. Protect the integrity of the
  480. // JSON data by making it the value of a textarea.
  481. // @see http://malsup.com/jquery/form/#file-upload
  482. // @see http://drupal.org/node/1009382
  483. print '<textarea>' . $json . '</textarea>';
  484. }
  485. // Perform end-of-request tasks.
  486. ajax_footer();
  487. }
  488. /**
  489. * Converts the return value of a page callback into an Ajax commands array.
  490. *
  491. * @param $page_callback_result
  492. * The result of a page callback. Can be one of:
  493. * - NULL: to indicate no content.
  494. * - An integer menu status constant: to indicate an error condition.
  495. * - A string of HTML content.
  496. * - A renderable array of content.
  497. *
  498. * @return
  499. * An Ajax commands array that can be passed to ajax_render().
  500. */
  501. function ajax_prepare_response($page_callback_result) {
  502. $commands = array();
  503. if (!isset($page_callback_result)) {
  504. // Simply delivering an empty commands array is sufficient. This results
  505. // in the Ajax request being completed, but nothing being done to the page.
  506. }
  507. elseif (is_int($page_callback_result)) {
  508. switch ($page_callback_result) {
  509. case MENU_NOT_FOUND:
  510. $commands[] = ajax_command_alert(t('The requested page could not be found.'));
  511. break;
  512. case MENU_ACCESS_DENIED:
  513. $commands[] = ajax_command_alert(t('You are not authorized to access this page.'));
  514. break;
  515. case MENU_SITE_OFFLINE:
  516. $commands[] = ajax_command_alert(filter_xss_admin(variable_get('maintenance_mode_message',
  517. t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal'))))));
  518. break;
  519. }
  520. }
  521. elseif (is_array($page_callback_result) && isset($page_callback_result['#type']) && ($page_callback_result['#type'] == 'ajax')) {
  522. // Complex Ajax callbacks can return a result that contains an error message
  523. // or a specific set of commands to send to the browser.
  524. $page_callback_result += element_info('ajax');
  525. $error = $page_callback_result['#error'];
  526. if (isset($error) && $error !== FALSE) {
  527. if ((empty($error) || $error === TRUE)) {
  528. $error = t('An error occurred while handling the request: The server received invalid input.');
  529. }
  530. $commands[] = ajax_command_alert($error);
  531. }
  532. else {
  533. $commands = $page_callback_result['#commands'];
  534. }
  535. }
  536. else {
  537. // Like normal page callbacks, simple Ajax callbacks can return HTML
  538. // content, as a string or render array. This HTML is inserted in some
  539. // relationship to #ajax['wrapper'], as determined by which jQuery DOM
  540. // manipulation method is used. The method used is specified by
  541. // #ajax['method']. The default method is 'replaceWith', which completely
  542. // replaces the old wrapper element and its content with the new HTML.
  543. $html = is_string($page_callback_result) ? $page_callback_result : drupal_render($page_callback_result);
  544. $commands[] = ajax_command_insert(NULL, $html);
  545. // Add the status messages inside the new content's wrapper element, so that
  546. // on subsequent Ajax requests, it is treated as old content.
  547. $commands[] = ajax_command_prepend(NULL, theme('status_messages'));
  548. }
  549. return $commands;
  550. }
  551. /**
  552. * Sets a response header for ajax.js to trust the response body.
  553. *
  554. * It is not safe to invoke Ajax commands within user-uploaded files, so this
  555. * header protects against those being invoked.
  556. *
  557. * @see Drupal.ajax.options.success()
  558. */
  559. function ajax_set_verification_header() {
  560. $added = &drupal_static(__FUNCTION__);
  561. // User-uploaded files cannot set any response headers, so a custom header is
  562. // used to indicate to ajax.js that this response is safe. Note that most
  563. // Ajax requests bound using the Form API will be protected by having the URL
  564. // flagged as trusted in Drupal.settings, so this header is used only for
  565. // things like custom markup that gets Ajax behaviors attached.
  566. if (empty($added)) {
  567. drupal_add_http_header('X-Drupal-Ajax-Token', '1');
  568. // Avoid sending the header twice.
  569. $added = TRUE;
  570. }
  571. }
  572. /**
  573. * Performs end-of-Ajax-request tasks.
  574. *
  575. * This function is the equivalent of drupal_page_footer(), but for Ajax
  576. * requests.
  577. *
  578. * @see drupal_page_footer()
  579. */
  580. function ajax_footer() {
  581. // Even for Ajax requests, invoke hook_exit() implementations. There may be
  582. // modules that need very fast Ajax responses, and therefore, run Ajax
  583. // requests with an early bootstrap.
  584. if (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update')) {
  585. module_invoke_all('exit');
  586. }
  587. // Commit the user session. See above comment about the possibility of this
  588. // function running without session.inc loaded.
  589. if (function_exists('drupal_session_commit')) {
  590. drupal_session_commit();
  591. }
  592. }
  593. /**
  594. * Form element processing handler for the #ajax form property.
  595. *
  596. * @param $element
  597. * An associative array containing the properties of the element.
  598. *
  599. * @return
  600. * The processed element.
  601. *
  602. * @see ajax_pre_render_element()
  603. */
  604. function ajax_process_form($element, &$form_state) {
  605. $element = ajax_pre_render_element($element);
  606. if (!empty($element['#ajax_processed'])) {
  607. $form_state['cache'] = TRUE;
  608. }
  609. return $element;
  610. }
  611. /**
  612. * Adds Ajax information about an element to communicate with JavaScript.
  613. *
  614. * If #ajax['path'] is set on an element, this additional JavaScript is added
  615. * to the page header to attach the Ajax behaviors. See ajax.js for more
  616. * information.
  617. *
  618. * @param $element
  619. * An associative array containing the properties of the element.
  620. * Properties used:
  621. * - #ajax['event']
  622. * - #ajax['prevent']
  623. * - #ajax['path']
  624. * - #ajax['options']
  625. * - #ajax['wrapper']
  626. * - #ajax['parameters']
  627. * - #ajax['effect']
  628. *
  629. * @return
  630. * The processed element with the necessary JavaScript attached to it.
  631. */
  632. function ajax_pre_render_element($element) {
  633. // Skip already processed elements.
  634. if (isset($element['#ajax_processed'])) {
  635. return $element;
  636. }
  637. // Initialize #ajax_processed, so we do not process this element again.
  638. $element['#ajax_processed'] = FALSE;
  639. // Nothing to do if there is neither a callback nor a path.
  640. if (!(isset($element['#ajax']['callback']) || isset($element['#ajax']['path']))) {
  641. return $element;
  642. }
  643. // Add a reasonable default event handler if none was specified.
  644. if (isset($element['#ajax']) && !isset($element['#ajax']['event'])) {
  645. switch ($element['#type']) {
  646. case 'submit':
  647. case 'button':
  648. case 'image_button':
  649. // Pressing the ENTER key within a textfield triggers the click event of
  650. // the form's first submit button. Triggering Ajax in this situation
  651. // leads to problems, like breaking autocomplete textfields, so we bind
  652. // to mousedown instead of click.
  653. // @see http://drupal.org/node/216059
  654. $element['#ajax']['event'] = 'mousedown';
  655. // Retain keyboard accessibility by setting 'keypress'. This causes
  656. // ajax.js to trigger 'event' when SPACE or ENTER are pressed while the
  657. // button has focus.
  658. $element['#ajax']['keypress'] = TRUE;
  659. // Binding to mousedown rather than click means that it is possible to
  660. // trigger a click by pressing the mouse, holding the mouse button down
  661. // until the Ajax request is complete and the button is re-enabled, and
  662. // then releasing the mouse button. Set 'prevent' so that ajax.js binds
  663. // an additional handler to prevent such a click from triggering a
  664. // non-Ajax form submission. This also prevents a textfield's ENTER
  665. // press triggering this button's non-Ajax form submission behavior.
  666. if (!isset($element['#ajax']['prevent'])) {
  667. $element['#ajax']['prevent'] = 'click';
  668. }
  669. break;
  670. case 'password':
  671. case 'textfield':
  672. case 'textarea':
  673. $element['#ajax']['event'] = 'blur';
  674. break;
  675. case 'radio':
  676. case 'checkbox':
  677. case 'select':
  678. $element['#ajax']['event'] = 'change';
  679. break;
  680. case 'link':
  681. $element['#ajax']['event'] = 'click';
  682. break;
  683. default:
  684. return $element;
  685. }
  686. }
  687. // Attach JavaScript settings to the element.
  688. if (isset($element['#ajax']['event'])) {
  689. $element['#attached']['library'][] = array('system', 'jquery.form');
  690. $element['#attached']['library'][] = array('system', 'drupal.ajax');
  691. $settings = $element['#ajax'];
  692. // Assign default settings.
  693. $settings += array(
  694. 'path' => 'system/ajax',
  695. 'options' => array(),
  696. );
  697. // @todo Legacy support. Remove in Drupal 8.
  698. if (isset($settings['method']) && $settings['method'] == 'replace') {
  699. $settings['method'] = 'replaceWith';
  700. }
  701. // Change path to URL.
  702. $settings['url'] = url($settings['path'], $settings['options']);
  703. unset($settings['path'], $settings['options']);
  704. // Add special data to $settings['submit'] so that when this element
  705. // triggers an Ajax submission, Drupal's form processing can determine which
  706. // element triggered it.
  707. // @see _form_element_triggered_scripted_submission()
  708. if (isset($settings['trigger_as'])) {
  709. // An element can add a 'trigger_as' key within #ajax to make the element
  710. // submit as though another one (for example, a non-button can use this
  711. // to submit the form as though a button were clicked). When using this,
  712. // the 'name' key is always required to identify the element to trigger
  713. // as. The 'value' key is optional, and only needed when multiple elements
  714. // share the same name, which is commonly the case for buttons.
  715. $settings['submit']['_triggering_element_name'] = $settings['trigger_as']['name'];
  716. if (isset($settings['trigger_as']['value'])) {
  717. $settings['submit']['_triggering_element_value'] = $settings['trigger_as']['value'];
  718. }
  719. unset($settings['trigger_as']);
  720. }
  721. elseif (isset($element['#name'])) {
  722. // Most of the time, elements can submit as themselves, in which case the
  723. // 'trigger_as' key isn't needed, and the element's name is used.
  724. $settings['submit']['_triggering_element_name'] = $element['#name'];
  725. // If the element is a (non-image) button, its name may not identify it
  726. // uniquely, in which case a match on value is also needed.
  727. // @see _form_button_was_clicked()
  728. if (isset($element['#button_type']) && empty($element['#has_garbage_value'])) {
  729. $settings['submit']['_triggering_element_value'] = $element['#value'];
  730. }
  731. }
  732. // Convert a simple #ajax['progress'] string into an array.
  733. if (isset($settings['progress']) && is_string($settings['progress'])) {
  734. $settings['progress'] = array('type' => $settings['progress']);
  735. }
  736. // Change progress path to a full URL.
  737. if (isset($settings['progress']['path'])) {
  738. $settings['progress']['url'] = url($settings['progress']['path']);
  739. unset($settings['progress']['path']);
  740. }
  741. $element['#attached']['js'][] = array(
  742. 'type' => 'setting',
  743. 'data' => array(
  744. 'ajax' => array($element['#id'] => $settings),
  745. 'urlIsAjaxTrusted' => array(
  746. $settings['url'] => TRUE,
  747. ),
  748. ),
  749. );
  750. // Indicate that Ajax processing was successful.
  751. $element['#ajax_processed'] = TRUE;
  752. }
  753. return $element;
  754. }
  755. /**
  756. * @} End of "defgroup ajax".
  757. */
  758. /**
  759. * @defgroup ajax_commands Ajax framework commands
  760. * @{
  761. * Functions to create various Ajax commands.
  762. *
  763. * These functions can be used to create arrays for use with the
  764. * ajax_render() function.
  765. */
  766. /**
  767. * Creates a Drupal Ajax 'alert' command.
  768. *
  769. * The 'alert' command instructs the client to display a JavaScript alert
  770. * dialog box.
  771. *
  772. * This command is implemented by Drupal.ajax.prototype.commands.alert()
  773. * defined in misc/ajax.js.
  774. *
  775. * @param $text
  776. * The message string to display to the user.
  777. *
  778. * @return
  779. * An array suitable for use with the ajax_render() function.
  780. */
  781. function ajax_command_alert($text) {
  782. return array(
  783. 'command' => 'alert',
  784. 'text' => $text,
  785. );
  786. }
  787. /**
  788. * Creates a Drupal Ajax 'insert' command using the method in #ajax['method'].
  789. *
  790. * This command instructs the client to insert the given HTML using whichever
  791. * jQuery DOM manipulation method has been specified in the #ajax['method']
  792. * variable of the element that triggered the request.
  793. *
  794. * This command is implemented by Drupal.ajax.prototype.commands.insert()
  795. * defined in misc/ajax.js.
  796. *
  797. * @param $selector
  798. * A jQuery selector string. If the command is a response to a request from
  799. * an #ajax form element then this value can be NULL.
  800. * @param $html
  801. * The data to use with the jQuery method.
  802. * @param $settings
  803. * An optional array of settings that will be used for this command only.
  804. *
  805. * @return
  806. * An array suitable for use with the ajax_render() function.
  807. */
  808. function ajax_command_insert($selector, $html, $settings = NULL) {
  809. return array(
  810. 'command' => 'insert',
  811. 'method' => NULL,
  812. 'selector' => $selector,
  813. 'data' => $html,
  814. 'settings' => $settings,
  815. );
  816. }
  817. /**
  818. * Creates a Drupal Ajax 'insert/replaceWith' command.
  819. *
  820. * The 'insert/replaceWith' command instructs the client to use jQuery's
  821. * replaceWith() method to replace each element matched matched by the given
  822. * selector with the given HTML.
  823. *
  824. * This command is implemented by Drupal.ajax.prototype.commands.insert()
  825. * defined in misc/ajax.js.
  826. *
  827. * @param $selector
  828. * A jQuery selector string. If the command is a response to a request from
  829. * an #ajax form element then this value can be NULL.
  830. * @param $html
  831. * The data to use with the jQuery replaceWith() method.
  832. * @param $settings
  833. * An optional array of settings that will be used for this command only.
  834. *
  835. * @return
  836. * An array suitable for use with the ajax_render() function.
  837. *
  838. * See
  839. * @link http://docs.jquery.com/Manipulation/replaceWith#content jQuery replaceWith command @endlink
  840. */
  841. function ajax_command_replace($selector, $html, $settings = NULL) {
  842. return array(
  843. 'command' => 'insert',
  844. 'method' => 'replaceWith',
  845. 'selector' => $selector,
  846. 'data' => $html,
  847. 'settings' => $settings,
  848. );
  849. }
  850. /**
  851. * Creates a Drupal Ajax 'insert/html' command.
  852. *
  853. * The 'insert/html' command instructs the client to use jQuery's html()
  854. * method to set the HTML content of each element matched by the given
  855. * selector while leaving the outer tags intact.
  856. *
  857. * This command is implemented by Drupal.ajax.prototype.commands.insert()
  858. * defined in misc/ajax.js.
  859. *
  860. * @param $selector
  861. * A jQuery selector string. If the command is a response to a request from
  862. * an #ajax form element then this value can be NULL.
  863. * @param $html
  864. * The data to use with the jQuery html() method.
  865. * @param $settings
  866. * An optional array of settings that will be used for this command only.
  867. *
  868. * @return
  869. * An array suitable for use with the ajax_render() function.
  870. *
  871. * @see http://docs.jquery.com/Attributes/html#val
  872. */
  873. function ajax_command_html($selector, $html, $settings = NULL) {
  874. return array(
  875. 'command' => 'insert',
  876. 'method' => 'html',
  877. 'selector' => $selector,
  878. 'data' => $html,
  879. 'settings' => $settings,
  880. );
  881. }
  882. /**
  883. * Creates a Drupal Ajax 'insert/prepend' command.
  884. *
  885. * The 'insert/prepend' command instructs the client to use jQuery's prepend()
  886. * method to prepend the given HTML content to the inside each element matched
  887. * by the given selector.
  888. *
  889. * This command is implemented by Drupal.ajax.prototype.commands.insert()
  890. * defined in misc/ajax.js.
  891. *
  892. * @param $selector
  893. * A jQuery selector string. If the command is a response to a request from
  894. * an #ajax form element then this value can be NULL.
  895. * @param $html
  896. * The data to use with the jQuery prepend() method.
  897. * @param $settings
  898. * An optional array of settings that will be used for this command only.
  899. *
  900. * @return
  901. * An array suitable for use with the ajax_render() function.
  902. *
  903. * @see http://docs.jquery.com/Manipulation/prepend#content
  904. */
  905. function ajax_command_prepend($selector, $html, $settings = NULL) {
  906. return array(
  907. 'command' => 'insert',
  908. 'method' => 'prepend',
  909. 'selector' => $selector,
  910. 'data' => $html,
  911. 'settings' => $settings,
  912. );
  913. }
  914. /**
  915. * Creates a Drupal Ajax 'insert/append' command.
  916. *
  917. * The 'insert/append' command instructs the client to use jQuery's append()
  918. * method to append the given HTML content to the inside of each element matched
  919. * by the given selector.
  920. *
  921. * This command is implemented by Drupal.ajax.prototype.commands.insert()
  922. * defined in misc/ajax.js.
  923. *
  924. * @param $selector
  925. * A jQuery selector string. If the command is a response to a request from
  926. * an #ajax form element then this value can be NULL.
  927. * @param $html
  928. * The data to use with the jQuery append() method.
  929. * @param $settings
  930. * An optional array of settings that will be used for this command only.
  931. *
  932. * @return
  933. * An array suitable for use with the ajax_render() function.
  934. *
  935. * @see http://docs.jquery.com/Manipulation/append#content
  936. */
  937. function ajax_command_append($selector, $html, $settings = NULL) {
  938. return array(
  939. 'command' => 'insert',
  940. 'method' => 'append',
  941. 'selector' => $selector,
  942. 'data' => $html,
  943. 'settings' => $settings,
  944. );
  945. }
  946. /**
  947. * Creates a Drupal Ajax 'insert/after' command.
  948. *
  949. * The 'insert/after' command instructs the client to use jQuery's after()
  950. * method to insert the given HTML content after each element matched by
  951. * the given selector.
  952. *
  953. * This command is implemented by Drupal.ajax.prototype.commands.insert()
  954. * defined in misc/ajax.js.
  955. *
  956. * @param $selector
  957. * A jQuery selector string. If the command is a response to a request from
  958. * an #ajax form element then this value can be NULL.
  959. * @param $html
  960. * The data to use with the jQuery after() method.
  961. * @param $settings
  962. * An optional array of settings that will be used for this command only.
  963. *
  964. * @return
  965. * An array suitable for use with the ajax_render() function.
  966. *
  967. * @see http://docs.jquery.com/Manipulation/after#content
  968. */
  969. function ajax_command_after($selector, $html, $settings = NULL) {
  970. return array(
  971. 'command' => 'insert',
  972. 'method' => 'after',
  973. 'selector' => $selector,
  974. 'data' => $html,
  975. 'settings' => $settings,
  976. );
  977. }
  978. /**
  979. * Creates a Drupal Ajax 'insert/before' command.
  980. *
  981. * The 'insert/before' command instructs the client to use jQuery's before()
  982. * method to insert the given HTML content before each of elements matched by
  983. * the given selector.
  984. *
  985. * This command is implemented by Drupal.ajax.prototype.commands.insert()
  986. * defined in misc/ajax.js.
  987. *
  988. * @param $selector
  989. * A jQuery selector string. If the command is a response to a request from
  990. * an #ajax form element then this value can be NULL.
  991. * @param $html
  992. * The data to use with the jQuery before() method.
  993. * @param $settings
  994. * An optional array of settings that will be used for this command only.
  995. *
  996. * @return
  997. * An array suitable for use with the ajax_render() function.
  998. *
  999. * @see http://docs.jquery.com/Manipulation/before#content
  1000. */
  1001. function ajax_command_before($selector, $html, $settings = NULL) {
  1002. return array(
  1003. 'command' => 'insert',
  1004. 'method' => 'before',
  1005. 'selector' => $selector,
  1006. 'data' => $html,
  1007. 'settings' => $settings,
  1008. );
  1009. }
  1010. /**
  1011. * Creates a Drupal Ajax 'remove' command.
  1012. *
  1013. * The 'remove' command instructs the client to use jQuery's remove() method
  1014. * to remove each of elements matched by the given selector, and everything
  1015. * within them.
  1016. *
  1017. * This command is implemented by Drupal.ajax.prototype.commands.remove()
  1018. * defined in misc/ajax.js.
  1019. *
  1020. * @param $selector
  1021. * A jQuery selector string. If the command is a response to a request from
  1022. * an #ajax form element then this value can be NULL.
  1023. *
  1024. * @return
  1025. * An array suitable for use with the ajax_render() function.
  1026. *
  1027. * @see http://docs.jquery.com/Manipulation/remove#expr
  1028. */
  1029. function ajax_command_remove($selector) {
  1030. return array(
  1031. 'command' => 'remove',
  1032. 'selector' => $selector,
  1033. );
  1034. }
  1035. /**
  1036. * Creates a Drupal Ajax 'changed' command.
  1037. *
  1038. * This command instructs the client to mark each of the elements matched by the
  1039. * given selector as 'ajax-changed'.
  1040. *
  1041. * This command is implemented by Drupal.ajax.prototype.commands.changed()
  1042. * defined in misc/ajax.js.
  1043. *
  1044. * @param $selector
  1045. * A jQuery selector string. If the command is a response to a request from
  1046. * an #ajax form element then this value can be NULL.
  1047. * @param $asterisk
  1048. * An optional CSS selector which must be inside $selector. If specified,
  1049. * an asterisk will be appended to the HTML inside the $asterisk selector.
  1050. *
  1051. * @return
  1052. * An array suitable for use with the ajax_render() function.
  1053. */
  1054. function ajax_command_changed($selector, $asterisk = '') {
  1055. return array(
  1056. 'command' => 'changed',
  1057. 'selector' => $selector,
  1058. 'asterisk' => $asterisk,
  1059. );
  1060. }
  1061. /**
  1062. * Creates a Drupal Ajax 'css' command.
  1063. *
  1064. * The 'css' command will instruct the client to use the jQuery css() method
  1065. * to apply the CSS arguments to elements matched by the given selector.
  1066. *
  1067. * This command is implemented by Drupal.ajax.prototype.commands.css()
  1068. * defined in misc/ajax.js.
  1069. *
  1070. * @param $selector
  1071. * A jQuery selector string. If the command is a response to a request from
  1072. * an #ajax form element then this value can be NULL.
  1073. * @param $argument
  1074. * An array of key/value pairs to set in the CSS for the selector.
  1075. *
  1076. * @return
  1077. * An array suitable for use with the ajax_render() function.
  1078. *
  1079. * @see http://docs.jquery.com/CSS/css#properties
  1080. */
  1081. function ajax_command_css($selector, $argument) {
  1082. return array(
  1083. 'command' => 'css',
  1084. 'selector' => $selector,
  1085. 'argument' => $argument,
  1086. );
  1087. }
  1088. /**
  1089. * Creates a Drupal Ajax 'settings' command.
  1090. *
  1091. * The 'settings' command instructs the client either to use the given array as
  1092. * the settings for ajax-loaded content or to extend Drupal.settings with the
  1093. * given array, depending on the value of the $merge parameter.
  1094. *
  1095. * This command is implemented by Drupal.ajax.prototype.commands.settings()
  1096. * defined in misc/ajax.js.
  1097. *
  1098. * @param $argument
  1099. * An array of key/value pairs to add to the settings. This will be utilized
  1100. * for all commands after this if they do not include their own settings
  1101. * array.
  1102. * @param $merge
  1103. * Whether or not the passed settings in $argument should be merged into the
  1104. * global Drupal.settings on the page. By default (FALSE), the settings that
  1105. * are passed to Drupal.attachBehaviors will not include the global
  1106. * Drupal.settings.
  1107. *
  1108. * @return
  1109. * An array suitable for use with the ajax_render() function.
  1110. */
  1111. function ajax_command_settings($argument, $merge = FALSE) {
  1112. return array(
  1113. 'command' => 'settings',
  1114. 'settings' => $argument,
  1115. 'merge' => $merge,
  1116. );
  1117. }
  1118. /**
  1119. * Creates a Drupal Ajax 'data' command.
  1120. *
  1121. * The 'data' command instructs the client to attach the name=value pair of
  1122. * data to the selector via jQuery's data cache.
  1123. *
  1124. * This command is implemented by Drupal.ajax.prototype.commands.data()
  1125. * defined in misc/ajax.js.
  1126. *
  1127. * @param $selector
  1128. * A jQuery selector string. If the command is a response to a request from
  1129. * an #ajax form element then this value can be NULL.
  1130. * @param $name
  1131. * The name or key (in the key value pair) of the data attached to this
  1132. * selector.
  1133. * @param $value
  1134. * The value of the data. Not just limited to strings can be any format.
  1135. *
  1136. * @return
  1137. * An array suitable for use with the ajax_render() function.
  1138. *
  1139. * @see http://docs.jquery.com/Core/data#namevalue
  1140. */
  1141. function ajax_command_data($selector, $name, $value) {
  1142. return array(
  1143. 'command' => 'data',
  1144. 'selector' => $selector,
  1145. 'name' => $name,
  1146. 'value' => $value,
  1147. );
  1148. }
  1149. /**
  1150. * Creates a Drupal Ajax 'invoke' command.
  1151. *
  1152. * The 'invoke' command will instruct the client to invoke the given jQuery
  1153. * method with the supplied arguments on the elements matched by the given
  1154. * selector. Intended for simple jQuery commands, such as attr(), addClass(),
  1155. * removeClass(), toggleClass(), etc.
  1156. *
  1157. * This command is implemented by Drupal.ajax.prototype.commands.invoke()
  1158. * defined in misc/ajax.js.
  1159. *
  1160. * @param $selector
  1161. * A jQuery selector string. If the command is a response to a request from
  1162. * an #ajax form element then this value can be NULL.
  1163. * @param $method
  1164. * The jQuery method to invoke.
  1165. * @param $arguments
  1166. * (optional) A list of arguments to the jQuery $method, if any.
  1167. *
  1168. * @return
  1169. * An array suitable for use with the ajax_render() function.
  1170. */
  1171. function ajax_command_invoke($selector, $method, array $arguments = array()) {
  1172. return array(
  1173. 'command' => 'invoke',
  1174. 'selector' => $selector,
  1175. 'method' => $method,
  1176. 'arguments' => $arguments,
  1177. );
  1178. }
  1179. /**
  1180. * Creates a Drupal Ajax 'restripe' command.
  1181. *
  1182. * The 'restripe' command instructs the client to restripe a table. This is
  1183. * usually used after a table has been modified by a replace or append command.
  1184. *
  1185. * This command is implemented by Drupal.ajax.prototype.commands.restripe()
  1186. * defined in misc/ajax.js.
  1187. *
  1188. * @param $selector
  1189. * A jQuery selector string.
  1190. *
  1191. * @return
  1192. * An array suitable for use with the ajax_render() function.
  1193. */
  1194. function ajax_command_restripe($selector) {
  1195. return array(
  1196. 'command' => 'restripe',
  1197. 'selector' => $selector,
  1198. );
  1199. }
  1200. /**
  1201. * Creates a Drupal Ajax 'update_build_id' command.
  1202. *
  1203. * This command updates the value of a hidden form_build_id input element on a
  1204. * form. It requires the form passed in to have keys for both the old build ID
  1205. * in #build_id_old and the new build ID in #build_id.
  1206. *
  1207. * The primary use case for this Ajax command is to serve a new build ID to a
  1208. * form served from the cache to an anonymous user, preventing one anonymous
  1209. * user from accessing the form state of another anonymous users on Ajax enabled
  1210. * forms.
  1211. *
  1212. * @param $form
  1213. * The form array representing the form whose build ID should be updated.
  1214. */
  1215. function ajax_command_update_build_id($form) {
  1216. return array(
  1217. 'command' => 'updateBuildId',
  1218. 'old' => $form['#build_id_old'],
  1219. 'new' => $form['#build_id'],
  1220. );
  1221. }
  1222. /**
  1223. * Creates a Drupal Ajax 'add_css' command.
  1224. *
  1225. * This method will add css via ajax in a cross-browser compatible way.
  1226. *
  1227. * This command is implemented by Drupal.ajax.prototype.commands.add_css()
  1228. * defined in misc/ajax.js.
  1229. *
  1230. * @param $styles
  1231. * A string that contains the styles to be added.
  1232. *
  1233. * @return
  1234. * An array suitable for use with the ajax_render() function.
  1235. *
  1236. * @see misc/ajax.js
  1237. */
  1238. function ajax_command_add_css($styles) {
  1239. return array(
  1240. 'command' => 'add_css',
  1241. 'data' => $styles,
  1242. );
  1243. }

Functions

Namesort descending Description
ajax_base_page_theme Theme callback for Ajax requests.
ajax_command_add_css Creates a Drupal Ajax 'add_css' command.
ajax_command_after Creates a Drupal Ajax 'insert/after' command.
ajax_command_alert Creates a Drupal Ajax 'alert' command.
ajax_command_append Creates a Drupal Ajax 'insert/append' command.
ajax_command_before Creates a Drupal Ajax 'insert/before' command.
ajax_command_changed Creates a Drupal Ajax 'changed' command.
ajax_command_css Creates a Drupal Ajax 'css' command.
ajax_command_data Creates a Drupal Ajax 'data' command.
ajax_command_html Creates a Drupal Ajax 'insert/html' command.
ajax_command_insert Creates a Drupal Ajax 'insert' command using the method in #ajax['method'].
ajax_command_invoke Creates a Drupal Ajax 'invoke' command.
ajax_command_prepend Creates a Drupal Ajax 'insert/prepend' command.
ajax_command_remove Creates a Drupal Ajax 'remove' command.
ajax_command_replace Creates a Drupal Ajax 'insert/replaceWith' command.
ajax_command_restripe Creates a Drupal Ajax 'restripe' command.
ajax_command_settings Creates a Drupal Ajax 'settings' command.
ajax_command_update_build_id Creates a Drupal Ajax 'update_build_id' command.
ajax_deliver Packages and sends the result of a page callback as an Ajax response.
ajax_footer Performs end-of-Ajax-request tasks.
ajax_form_callback Menu callback; handles Ajax requests for the #ajax Form API property.
ajax_get_form Gets a form submitted via #ajax during an Ajax callback.
ajax_prepare_response Converts the return value of a page callback into an Ajax commands array.
ajax_pre_render_element Adds Ajax information about an element to communicate with JavaScript.
ajax_process_form Form element processing handler for the #ajax form property.
ajax_render Renders a commands array into JSON.
ajax_set_verification_header Sets a response header for ajax.js to trust the response body.

Comments

As described in the inline documentation:

<?php
$commands
[] = ajax_command_prepend(NULL, theme('status_messages'));
?>

But replace NULL with a proper css selector (see your page.tpl.php). In my case (omega sub-theme):

<?php
// Output drupal messages.
$commands[] = ajax_command_remove('#messages');
$commands[] = ajax_command_prepend('#region-content', '<div id="messages" class="grid-12">' . theme('status_messages') . '</div>');
?>