ajax.inc 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  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. drupal_alter('js', $scripts);
  290. if (!empty($scripts['settings'])) {
  291. $settings = $scripts['settings'];
  292. array_unshift($commands, ajax_command_settings(drupal_array_merge_deep_array($settings['data']), TRUE));
  293. }
  294. // Allow modules to alter any Ajax response.
  295. drupal_alter('ajax_render', $commands);
  296. return drupal_json_encode($commands);
  297. }
  298. /**
  299. * Gets a form submitted via #ajax during an Ajax callback.
  300. *
  301. * This will load a form from the form cache used during Ajax operations. It
  302. * pulls the form info from $_POST.
  303. *
  304. * @return
  305. * An array containing the $form, $form_state, $form_id, $form_build_id and an
  306. * initial list of Ajax $commands. Use the list() function to break these
  307. * apart:
  308. * @code
  309. * list($form, $form_state, $form_id, $form_build_id, $commands) = ajax_get_form();
  310. * @endcode
  311. */
  312. function ajax_get_form() {
  313. $form_state = form_state_defaults();
  314. $form_build_id = $_POST['form_build_id'];
  315. // Get the form from the cache.
  316. $form = form_get_cache($form_build_id, $form_state);
  317. if (!$form) {
  318. // If $form cannot be loaded from the cache, the form_build_id in $_POST
  319. // must be invalid, which means that someone performed a POST request onto
  320. // system/ajax without actually viewing the concerned form in the browser.
  321. // This is likely a hacking attempt as it never happens under normal
  322. // circumstances, so we just do nothing.
  323. watchdog('ajax', 'Invalid form POST data.', array(), WATCHDOG_WARNING);
  324. drupal_exit();
  325. }
  326. // When a page level cache is enabled, the form-build id might have been
  327. // replaced from within form_get_cache. If this is the case, it is also
  328. // necessary to update it in the browser by issuing an appropriate Ajax
  329. // command.
  330. $commands = array();
  331. if (isset($form['#build_id_old']) && $form['#build_id_old'] != $form['#build_id']) {
  332. // If the form build ID has changed, issue an Ajax command to update it.
  333. $commands[] = ajax_command_update_build_id($form);
  334. $form_build_id = $form['#build_id'];
  335. }
  336. // Since some of the submit handlers are run, redirects need to be disabled.
  337. $form_state['no_redirect'] = TRUE;
  338. // When a form is rebuilt after Ajax processing, its #build_id and #action
  339. // should not change.
  340. // @see drupal_rebuild_form()
  341. $form_state['rebuild_info']['copy']['#build_id'] = TRUE;
  342. $form_state['rebuild_info']['copy']['#action'] = TRUE;
  343. // The form needs to be processed; prepare for that by setting a few internal
  344. // variables.
  345. $form_state['input'] = $_POST;
  346. $form_id = $form['#form_id'];
  347. return array($form, $form_state, $form_id, $form_build_id, $commands);
  348. }
  349. /**
  350. * Menu callback; handles Ajax requests for the #ajax Form API property.
  351. *
  352. * This rebuilds the form from cache and invokes the defined #ajax['callback']
  353. * to return an Ajax command structure for JavaScript. In case no 'callback' has
  354. * been defined, nothing will happen.
  355. *
  356. * The Form API #ajax property can be set both for buttons and other input
  357. * elements.
  358. *
  359. * This function is also the canonical example of how to implement
  360. * #ajax['path']. If processing is required that cannot be accomplished with
  361. * a callback, re-implement this function and set #ajax['path'] to the
  362. * enhanced function.
  363. *
  364. * @see system_menu()
  365. */
  366. function ajax_form_callback() {
  367. list($form, $form_state, $form_id, $form_build_id, $commands) = ajax_get_form();
  368. drupal_process_form($form['#form_id'], $form, $form_state);
  369. // We need to return the part of the form (or some other content) that needs
  370. // to be re-rendered so the browser can update the page with changed content.
  371. // Since this is the generic menu callback used by many Ajax elements, it is
  372. // up to the #ajax['callback'] function of the element (may or may not be a
  373. // button) that triggered the Ajax request to determine what needs to be
  374. // rendered.
  375. if (!empty($form_state['triggering_element'])) {
  376. $callback = $form_state['triggering_element']['#ajax']['callback'];
  377. }
  378. if (!empty($callback) && is_callable($callback)) {
  379. $result = $callback($form, $form_state);
  380. if (!(is_array($result) && isset($result['#type']) && $result['#type'] == 'ajax')) {
  381. // Turn the response into a #type=ajax array if it isn't one already.
  382. $result = array(
  383. '#type' => 'ajax',
  384. '#commands' => ajax_prepare_response($result),
  385. );
  386. }
  387. $result['#commands'] = array_merge($commands, $result['#commands']);
  388. return $result;
  389. }
  390. }
  391. /**
  392. * Theme callback for Ajax requests.
  393. *
  394. * Many different pages can invoke an Ajax request to system/ajax or another
  395. * generic Ajax path. It is almost always desired for an Ajax response to be
  396. * rendered using the same theme as the base page, because most themes are built
  397. * with the assumption that they control the entire page, so if the CSS for two
  398. * themes are both loaded for a given page, they may conflict with each other.
  399. * For example, Bartik is Drupal's default theme, and Seven is Drupal's default
  400. * administration theme. Depending on whether the "Use the administration theme
  401. * when editing or creating content" checkbox is checked, the node edit form may
  402. * be displayed in either theme, but the Ajax response to the Field module's
  403. * "Add another item" button should be rendered using the same theme as the rest
  404. * of the page. Therefore, system_menu() sets the 'theme callback' for
  405. * 'system/ajax' to this function, and it is recommended that modules
  406. * implementing other generic Ajax paths do the same.
  407. *
  408. * @see system_menu()
  409. * @see file_menu()
  410. */
  411. function ajax_base_page_theme() {
  412. if (!empty($_POST['ajax_page_state']['theme']) && !empty($_POST['ajax_page_state']['theme_token'])) {
  413. $theme = $_POST['ajax_page_state']['theme'];
  414. $token = $_POST['ajax_page_state']['theme_token'];
  415. // Prevent a request forgery from giving a person access to a theme they
  416. // shouldn't be otherwise allowed to see. However, since everyone is allowed
  417. // to see the default theme, token validation isn't required for that, and
  418. // bypassing it allows most use-cases to work even when accessed from the
  419. // page cache.
  420. if ($theme === variable_get('theme_default', 'bartik') || drupal_valid_token($token, $theme)) {
  421. return $theme;
  422. }
  423. }
  424. }
  425. /**
  426. * Packages and sends the result of a page callback as an Ajax response.
  427. *
  428. * This function is the equivalent of drupal_deliver_html_page(), but for Ajax
  429. * requests. Like that function, it:
  430. * - Adds needed HTTP headers.
  431. * - Prints rendered output.
  432. * - Performs end-of-request tasks.
  433. *
  434. * @param $page_callback_result
  435. * The result of a page callback. Can be one of:
  436. * - NULL: to indicate no content.
  437. * - An integer menu status constant: to indicate an error condition.
  438. * - A string of HTML content.
  439. * - A renderable array of content.
  440. *
  441. * @see drupal_deliver_html_page()
  442. */
  443. function ajax_deliver($page_callback_result) {
  444. // Browsers do not allow JavaScript to read the contents of a user's local
  445. // files. To work around that, the jQuery Form plugin submits forms containing
  446. // a file input element to an IFRAME, instead of using XHR. Browsers do not
  447. // normally expect JSON strings as content within an IFRAME, so the response
  448. // must be customized accordingly.
  449. // @see http://malsup.com/jquery/form/#file-upload
  450. // @see Drupal.ajax.prototype.beforeSend()
  451. $iframe_upload = !empty($_POST['ajax_iframe_upload']);
  452. // Emit a Content-Type HTTP header if none has been added by the page callback
  453. // or by a wrapping delivery callback.
  454. if (is_null(drupal_get_http_header('Content-Type'))) {
  455. if (!$iframe_upload) {
  456. // Standard JSON can be returned to a browser's XHR object, and to
  457. // non-browser user agents.
  458. // @see http://www.ietf.org/rfc/rfc4627.txt?number=4627
  459. drupal_add_http_header('Content-Type', 'application/json; charset=utf-8');
  460. }
  461. else {
  462. // Browser IFRAMEs expect HTML. With most other content types, Internet
  463. // Explorer presents the user with a download prompt.
  464. drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
  465. }
  466. }
  467. // Let ajax.js know that this response is safe to process.
  468. ajax_set_verification_header();
  469. // Print the response.
  470. $commands = ajax_prepare_response($page_callback_result);
  471. $json = ajax_render($commands);
  472. if (!$iframe_upload) {
  473. // Standard JSON can be returned to a browser's XHR object, and to
  474. // non-browser user agents.
  475. print $json;
  476. }
  477. else {
  478. // Browser IFRAMEs expect HTML. Browser extensions, such as Linkification
  479. // and Skype's Browser Highlighter, convert URLs, phone numbers, etc. into
  480. // links. This corrupts the JSON response. Protect the integrity of the
  481. // JSON data by making it the value of a textarea.
  482. // @see http://malsup.com/jquery/form/#file-upload
  483. // @see http://drupal.org/node/1009382
  484. print '<textarea>' . $json . '</textarea>';
  485. }
  486. // Perform end-of-request tasks.
  487. ajax_footer();
  488. }
  489. /**
  490. * Converts the return value of a page callback into an Ajax commands array.
  491. *
  492. * @param $page_callback_result
  493. * The result of a page callback. Can be one of:
  494. * - NULL: to indicate no content.
  495. * - An integer menu status constant: to indicate an error condition.
  496. * - A string of HTML content.
  497. * - A renderable array of content.
  498. *
  499. * @return
  500. * An Ajax commands array that can be passed to ajax_render().
  501. */
  502. function ajax_prepare_response($page_callback_result) {
  503. $commands = array();
  504. if (!isset($page_callback_result)) {
  505. // Simply delivering an empty commands array is sufficient. This results
  506. // in the Ajax request being completed, but nothing being done to the page.
  507. }
  508. elseif (is_int($page_callback_result)) {
  509. switch ($page_callback_result) {
  510. case MENU_NOT_FOUND:
  511. $commands[] = ajax_command_alert(t('The requested page could not be found.'));
  512. break;
  513. case MENU_ACCESS_DENIED:
  514. $commands[] = ajax_command_alert(t('You are not authorized to access this page.'));
  515. break;
  516. case MENU_SITE_OFFLINE:
  517. $commands[] = ajax_command_alert(filter_xss_admin(variable_get('maintenance_mode_message',
  518. t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal'))))));
  519. break;
  520. }
  521. }
  522. elseif (is_array($page_callback_result) && isset($page_callback_result['#type']) && ($page_callback_result['#type'] == 'ajax')) {
  523. // Complex Ajax callbacks can return a result that contains an error message
  524. // or a specific set of commands to send to the browser.
  525. $page_callback_result += element_info('ajax');
  526. $error = $page_callback_result['#error'];
  527. if (isset($error) && $error !== FALSE) {
  528. if ((empty($error) || $error === TRUE)) {
  529. $error = t('An error occurred while handling the request: The server received invalid input.');
  530. }
  531. $commands[] = ajax_command_alert($error);
  532. }
  533. else {
  534. $commands = $page_callback_result['#commands'];
  535. }
  536. }
  537. else {
  538. // Like normal page callbacks, simple Ajax callbacks can return HTML
  539. // content, as a string or render array. This HTML is inserted in some
  540. // relationship to #ajax['wrapper'], as determined by which jQuery DOM
  541. // manipulation method is used. The method used is specified by
  542. // #ajax['method']. The default method is 'replaceWith', which completely
  543. // replaces the old wrapper element and its content with the new HTML.
  544. $html = is_string($page_callback_result) ? $page_callback_result : drupal_render($page_callback_result);
  545. $commands[] = ajax_command_insert(NULL, $html);
  546. // Add the status messages inside the new content's wrapper element, so that
  547. // on subsequent Ajax requests, it is treated as old content.
  548. $commands[] = ajax_command_prepend(NULL, theme('status_messages'));
  549. }
  550. return $commands;
  551. }
  552. /**
  553. * Sets a response header for ajax.js to trust the response body.
  554. *
  555. * It is not safe to invoke Ajax commands within user-uploaded files, so this
  556. * header protects against those being invoked.
  557. *
  558. * @see Drupal.ajax.options.success()
  559. */
  560. function ajax_set_verification_header() {
  561. $added = &drupal_static(__FUNCTION__);
  562. // User-uploaded files cannot set any response headers, so a custom header is
  563. // used to indicate to ajax.js that this response is safe. Note that most
  564. // Ajax requests bound using the Form API will be protected by having the URL
  565. // flagged as trusted in Drupal.settings, so this header is used only for
  566. // things like custom markup that gets Ajax behaviors attached.
  567. if (empty($added)) {
  568. drupal_add_http_header('X-Drupal-Ajax-Token', '1');
  569. // Avoid sending the header twice.
  570. $added = TRUE;
  571. }
  572. }
  573. /**
  574. * Performs end-of-Ajax-request tasks.
  575. *
  576. * This function is the equivalent of drupal_page_footer(), but for Ajax
  577. * requests.
  578. *
  579. * @see drupal_page_footer()
  580. */
  581. function ajax_footer() {
  582. // Even for Ajax requests, invoke hook_exit() implementations. There may be
  583. // modules that need very fast Ajax responses, and therefore, run Ajax
  584. // requests with an early bootstrap.
  585. if (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update')) {
  586. module_invoke_all('exit');
  587. }
  588. // Commit the user session. See above comment about the possibility of this
  589. // function running without session.inc loaded.
  590. if (function_exists('drupal_session_commit')) {
  591. drupal_session_commit();
  592. }
  593. }
  594. /**
  595. * Form element processing handler for the #ajax form property.
  596. *
  597. * @param $element
  598. * An associative array containing the properties of the element.
  599. *
  600. * @return
  601. * The processed element.
  602. *
  603. * @see ajax_pre_render_element()
  604. */
  605. function ajax_process_form($element, &$form_state) {
  606. $element = ajax_pre_render_element($element);
  607. if (!empty($element['#ajax_processed'])) {
  608. $form_state['cache'] = TRUE;
  609. }
  610. return $element;
  611. }
  612. /**
  613. * Adds Ajax information about an element to communicate with JavaScript.
  614. *
  615. * If #ajax['path'] is set on an element, this additional JavaScript is added
  616. * to the page header to attach the Ajax behaviors. See ajax.js for more
  617. * information.
  618. *
  619. * @param $element
  620. * An associative array containing the properties of the element.
  621. * Properties used:
  622. * - #ajax['event']
  623. * - #ajax['prevent']
  624. * - #ajax['path']
  625. * - #ajax['options']
  626. * - #ajax['wrapper']
  627. * - #ajax['parameters']
  628. * - #ajax['effect']
  629. *
  630. * @return
  631. * The processed element with the necessary JavaScript attached to it.
  632. */
  633. function ajax_pre_render_element($element) {
  634. // Skip already processed elements.
  635. if (isset($element['#ajax_processed'])) {
  636. return $element;
  637. }
  638. // Initialize #ajax_processed, so we do not process this element again.
  639. $element['#ajax_processed'] = FALSE;
  640. // Nothing to do if there is neither a callback nor a path.
  641. if (!(isset($element['#ajax']['callback']) || isset($element['#ajax']['path']))) {
  642. return $element;
  643. }
  644. // Add a reasonable default event handler if none was specified.
  645. if (isset($element['#ajax']) && !isset($element['#ajax']['event'])) {
  646. switch ($element['#type']) {
  647. case 'submit':
  648. case 'button':
  649. case 'image_button':
  650. // Pressing the ENTER key within a textfield triggers the click event of
  651. // the form's first submit button. Triggering Ajax in this situation
  652. // leads to problems, like breaking autocomplete textfields, so we bind
  653. // to mousedown instead of click.
  654. // @see http://drupal.org/node/216059
  655. $element['#ajax']['event'] = 'mousedown';
  656. // Retain keyboard accessibility by setting 'keypress'. This causes
  657. // ajax.js to trigger 'event' when SPACE or ENTER are pressed while the
  658. // button has focus.
  659. $element['#ajax']['keypress'] = TRUE;
  660. // Binding to mousedown rather than click means that it is possible to
  661. // trigger a click by pressing the mouse, holding the mouse button down
  662. // until the Ajax request is complete and the button is re-enabled, and
  663. // then releasing the mouse button. Set 'prevent' so that ajax.js binds
  664. // an additional handler to prevent such a click from triggering a
  665. // non-Ajax form submission. This also prevents a textfield's ENTER
  666. // press triggering this button's non-Ajax form submission behavior.
  667. if (!isset($element['#ajax']['prevent'])) {
  668. $element['#ajax']['prevent'] = 'click';
  669. }
  670. break;
  671. case 'password':
  672. case 'textfield':
  673. case 'textarea':
  674. $element['#ajax']['event'] = 'blur';
  675. break;
  676. case 'radio':
  677. case 'checkbox':
  678. case 'select':
  679. $element['#ajax']['event'] = 'change';
  680. break;
  681. case 'link':
  682. $element['#ajax']['event'] = 'click';
  683. break;
  684. default:
  685. return $element;
  686. }
  687. }
  688. // Attach JavaScript settings to the element.
  689. if (isset($element['#ajax']['event'])) {
  690. $element['#attached']['library'][] = array('system', 'jquery.form');
  691. $element['#attached']['library'][] = array('system', 'drupal.ajax');
  692. $settings = $element['#ajax'];
  693. // Assign default settings.
  694. $settings += array(
  695. 'path' => 'system/ajax',
  696. 'options' => array(),
  697. );
  698. // @todo Legacy support. Remove in Drupal 8.
  699. if (isset($settings['method']) && $settings['method'] == 'replace') {
  700. $settings['method'] = 'replaceWith';
  701. }
  702. // Change path to URL.
  703. $settings['url'] = url($settings['path'], $settings['options']);
  704. unset($settings['path'], $settings['options']);
  705. // Add special data to $settings['submit'] so that when this element
  706. // triggers an Ajax submission, Drupal's form processing can determine which
  707. // element triggered it.
  708. // @see _form_element_triggered_scripted_submission()
  709. if (isset($settings['trigger_as'])) {
  710. // An element can add a 'trigger_as' key within #ajax to make the element
  711. // submit as though another one (for example, a non-button can use this
  712. // to submit the form as though a button were clicked). When using this,
  713. // the 'name' key is always required to identify the element to trigger
  714. // as. The 'value' key is optional, and only needed when multiple elements
  715. // share the same name, which is commonly the case for buttons.
  716. $settings['submit']['_triggering_element_name'] = $settings['trigger_as']['name'];
  717. if (isset($settings['trigger_as']['value'])) {
  718. $settings['submit']['_triggering_element_value'] = $settings['trigger_as']['value'];
  719. }
  720. unset($settings['trigger_as']);
  721. }
  722. elseif (isset($element['#name'])) {
  723. // Most of the time, elements can submit as themselves, in which case the
  724. // 'trigger_as' key isn't needed, and the element's name is used.
  725. $settings['submit']['_triggering_element_name'] = $element['#name'];
  726. // If the element is a (non-image) button, its name may not identify it
  727. // uniquely, in which case a match on value is also needed.
  728. // @see _form_button_was_clicked()
  729. if (isset($element['#button_type']) && empty($element['#has_garbage_value'])) {
  730. $settings['submit']['_triggering_element_value'] = $element['#value'];
  731. }
  732. }
  733. // Convert a simple #ajax['progress'] string into an array.
  734. if (isset($settings['progress']) && is_string($settings['progress'])) {
  735. $settings['progress'] = array('type' => $settings['progress']);
  736. }
  737. // Change progress path to a full URL.
  738. if (isset($settings['progress']['path'])) {
  739. $settings['progress']['url'] = url($settings['progress']['path']);
  740. unset($settings['progress']['path']);
  741. }
  742. $element['#attached']['js'][] = array(
  743. 'type' => 'setting',
  744. 'data' => array(
  745. 'ajax' => array($element['#id'] => $settings),
  746. 'urlIsAjaxTrusted' => array(
  747. $settings['url'] => TRUE,
  748. ),
  749. ),
  750. );
  751. // Indicate that Ajax processing was successful.
  752. $element['#ajax_processed'] = TRUE;
  753. }
  754. return $element;
  755. }
  756. /**
  757. * @} End of "defgroup ajax".
  758. */
  759. /**
  760. * @defgroup ajax_commands Ajax framework commands
  761. * @{
  762. * Functions to create various Ajax commands.
  763. *
  764. * These functions can be used to create arrays for use with the
  765. * ajax_render() function.
  766. */
  767. /**
  768. * Creates a Drupal Ajax 'alert' command.
  769. *
  770. * The 'alert' command instructs the client to display a JavaScript alert
  771. * dialog box.
  772. *
  773. * This command is implemented by Drupal.ajax.prototype.commands.alert()
  774. * defined in misc/ajax.js.
  775. *
  776. * @param $text
  777. * The message string to display to the user.
  778. *
  779. * @return
  780. * An array suitable for use with the ajax_render() function.
  781. */
  782. function ajax_command_alert($text) {
  783. return array(
  784. 'command' => 'alert',
  785. 'text' => $text,
  786. );
  787. }
  788. /**
  789. * Creates a Drupal Ajax 'insert' command using the method in #ajax['method'].
  790. *
  791. * This command instructs the client to insert the given HTML using whichever
  792. * jQuery DOM manipulation method has been specified in the #ajax['method']
  793. * variable of the element that triggered the request.
  794. *
  795. * This command is implemented by Drupal.ajax.prototype.commands.insert()
  796. * defined in misc/ajax.js.
  797. *
  798. * @param $selector
  799. * A jQuery selector string. If the command is a response to a request from
  800. * an #ajax form element then this value can be NULL.
  801. * @param $html
  802. * The data to use with the jQuery method.
  803. * @param $settings
  804. * An optional array of settings that will be used for this command only.
  805. *
  806. * @return
  807. * An array suitable for use with the ajax_render() function.
  808. */
  809. function ajax_command_insert($selector, $html, $settings = NULL) {
  810. return array(
  811. 'command' => 'insert',
  812. 'method' => NULL,
  813. 'selector' => $selector,
  814. 'data' => $html,
  815. 'settings' => $settings,
  816. );
  817. }
  818. /**
  819. * Creates a Drupal Ajax 'insert/replaceWith' command.
  820. *
  821. * The 'insert/replaceWith' command instructs the client to use jQuery's
  822. * replaceWith() method to replace each element matched matched by the given
  823. * selector with the given HTML.
  824. *
  825. * This command is implemented by Drupal.ajax.prototype.commands.insert()
  826. * defined in misc/ajax.js.
  827. *
  828. * @param $selector
  829. * A jQuery selector string. If the command is a response to a request from
  830. * an #ajax form element then this value can be NULL.
  831. * @param $html
  832. * The data to use with the jQuery replaceWith() method.
  833. * @param $settings
  834. * An optional array of settings that will be used for this command only.
  835. *
  836. * @return
  837. * An array suitable for use with the ajax_render() function.
  838. *
  839. * See
  840. * @link http://docs.jquery.com/Manipulation/replaceWith#content jQuery replaceWith command @endlink
  841. */
  842. function ajax_command_replace($selector, $html, $settings = NULL) {
  843. return array(
  844. 'command' => 'insert',
  845. 'method' => 'replaceWith',
  846. 'selector' => $selector,
  847. 'data' => $html,
  848. 'settings' => $settings,
  849. );
  850. }
  851. /**
  852. * Creates a Drupal Ajax 'insert/html' command.
  853. *
  854. * The 'insert/html' command instructs the client to use jQuery's html()
  855. * method to set the HTML content of each element matched by the given
  856. * selector while leaving the outer tags intact.
  857. *
  858. * This command is implemented by Drupal.ajax.prototype.commands.insert()
  859. * defined in misc/ajax.js.
  860. *
  861. * @param $selector
  862. * A jQuery selector string. If the command is a response to a request from
  863. * an #ajax form element then this value can be NULL.
  864. * @param $html
  865. * The data to use with the jQuery html() method.
  866. * @param $settings
  867. * An optional array of settings that will be used for this command only.
  868. *
  869. * @return
  870. * An array suitable for use with the ajax_render() function.
  871. *
  872. * @see http://docs.jquery.com/Attributes/html#val
  873. */
  874. function ajax_command_html($selector, $html, $settings = NULL) {
  875. return array(
  876. 'command' => 'insert',
  877. 'method' => 'html',
  878. 'selector' => $selector,
  879. 'data' => $html,
  880. 'settings' => $settings,
  881. );
  882. }
  883. /**
  884. * Creates a Drupal Ajax 'insert/prepend' command.
  885. *
  886. * The 'insert/prepend' command instructs the client to use jQuery's prepend()
  887. * method to prepend the given HTML content to the inside each element matched
  888. * by the given selector.
  889. *
  890. * This command is implemented by Drupal.ajax.prototype.commands.insert()
  891. * defined in misc/ajax.js.
  892. *
  893. * @param $selector
  894. * A jQuery selector string. If the command is a response to a request from
  895. * an #ajax form element then this value can be NULL.
  896. * @param $html
  897. * The data to use with the jQuery prepend() method.
  898. * @param $settings
  899. * An optional array of settings that will be used for this command only.
  900. *
  901. * @return
  902. * An array suitable for use with the ajax_render() function.
  903. *
  904. * @see http://docs.jquery.com/Manipulation/prepend#content
  905. */
  906. function ajax_command_prepend($selector, $html, $settings = NULL) {
  907. return array(
  908. 'command' => 'insert',
  909. 'method' => 'prepend',
  910. 'selector' => $selector,
  911. 'data' => $html,
  912. 'settings' => $settings,
  913. );
  914. }
  915. /**
  916. * Creates a Drupal Ajax 'insert/append' command.
  917. *
  918. * The 'insert/append' command instructs the client to use jQuery's append()
  919. * method to append the given HTML content to the inside of each element matched
  920. * by the given selector.
  921. *
  922. * This command is implemented by Drupal.ajax.prototype.commands.insert()
  923. * defined in misc/ajax.js.
  924. *
  925. * @param $selector
  926. * A jQuery selector string. If the command is a response to a request from
  927. * an #ajax form element then this value can be NULL.
  928. * @param $html
  929. * The data to use with the jQuery append() method.
  930. * @param $settings
  931. * An optional array of settings that will be used for this command only.
  932. *
  933. * @return
  934. * An array suitable for use with the ajax_render() function.
  935. *
  936. * @see http://docs.jquery.com/Manipulation/append#content
  937. */
  938. function ajax_command_append($selector, $html, $settings = NULL) {
  939. return array(
  940. 'command' => 'insert',
  941. 'method' => 'append',
  942. 'selector' => $selector,
  943. 'data' => $html,
  944. 'settings' => $settings,
  945. );
  946. }
  947. /**
  948. * Creates a Drupal Ajax 'insert/after' command.
  949. *
  950. * The 'insert/after' command instructs the client to use jQuery's after()
  951. * method to insert the given HTML content after each element matched by
  952. * the given selector.
  953. *
  954. * This command is implemented by Drupal.ajax.prototype.commands.insert()
  955. * defined in misc/ajax.js.
  956. *
  957. * @param $selector
  958. * A jQuery selector string. If the command is a response to a request from
  959. * an #ajax form element then this value can be NULL.
  960. * @param $html
  961. * The data to use with the jQuery after() method.
  962. * @param $settings
  963. * An optional array of settings that will be used for this command only.
  964. *
  965. * @return
  966. * An array suitable for use with the ajax_render() function.
  967. *
  968. * @see http://docs.jquery.com/Manipulation/after#content
  969. */
  970. function ajax_command_after($selector, $html, $settings = NULL) {
  971. return array(
  972. 'command' => 'insert',
  973. 'method' => 'after',
  974. 'selector' => $selector,
  975. 'data' => $html,
  976. 'settings' => $settings,
  977. );
  978. }
  979. /**
  980. * Creates a Drupal Ajax 'insert/before' command.
  981. *
  982. * The 'insert/before' command instructs the client to use jQuery's before()
  983. * method to insert the given HTML content before each of elements matched by
  984. * the given selector.
  985. *
  986. * This command is implemented by Drupal.ajax.prototype.commands.insert()
  987. * defined in misc/ajax.js.
  988. *
  989. * @param $selector
  990. * A jQuery selector string. If the command is a response to a request from
  991. * an #ajax form element then this value can be NULL.
  992. * @param $html
  993. * The data to use with the jQuery before() method.
  994. * @param $settings
  995. * An optional array of settings that will be used for this command only.
  996. *
  997. * @return
  998. * An array suitable for use with the ajax_render() function.
  999. *
  1000. * @see http://docs.jquery.com/Manipulation/before#content
  1001. */
  1002. function ajax_command_before($selector, $html, $settings = NULL) {
  1003. return array(
  1004. 'command' => 'insert',
  1005. 'method' => 'before',
  1006. 'selector' => $selector,
  1007. 'data' => $html,
  1008. 'settings' => $settings,
  1009. );
  1010. }
  1011. /**
  1012. * Creates a Drupal Ajax 'remove' command.
  1013. *
  1014. * The 'remove' command instructs the client to use jQuery's remove() method
  1015. * to remove each of elements matched by the given selector, and everything
  1016. * within them.
  1017. *
  1018. * This command is implemented by Drupal.ajax.prototype.commands.remove()
  1019. * defined in misc/ajax.js.
  1020. *
  1021. * @param $selector
  1022. * A jQuery selector string. If the command is a response to a request from
  1023. * an #ajax form element then this value can be NULL.
  1024. *
  1025. * @return
  1026. * An array suitable for use with the ajax_render() function.
  1027. *
  1028. * @see http://docs.jquery.com/Manipulation/remove#expr
  1029. */
  1030. function ajax_command_remove($selector) {
  1031. return array(
  1032. 'command' => 'remove',
  1033. 'selector' => $selector,
  1034. );
  1035. }
  1036. /**
  1037. * Creates a Drupal Ajax 'changed' command.
  1038. *
  1039. * This command instructs the client to mark each of the elements matched by the
  1040. * given selector as 'ajax-changed'.
  1041. *
  1042. * This command is implemented by Drupal.ajax.prototype.commands.changed()
  1043. * defined in misc/ajax.js.
  1044. *
  1045. * @param $selector
  1046. * A jQuery selector string. If the command is a response to a request from
  1047. * an #ajax form element then this value can be NULL.
  1048. * @param $asterisk
  1049. * An optional CSS selector which must be inside $selector. If specified,
  1050. * an asterisk will be appended to the HTML inside the $asterisk selector.
  1051. *
  1052. * @return
  1053. * An array suitable for use with the ajax_render() function.
  1054. */
  1055. function ajax_command_changed($selector, $asterisk = '') {
  1056. return array(
  1057. 'command' => 'changed',
  1058. 'selector' => $selector,
  1059. 'asterisk' => $asterisk,
  1060. );
  1061. }
  1062. /**
  1063. * Creates a Drupal Ajax 'css' command.
  1064. *
  1065. * The 'css' command will instruct the client to use the jQuery css() method
  1066. * to apply the CSS arguments to elements matched by the given selector.
  1067. *
  1068. * This command is implemented by Drupal.ajax.prototype.commands.css()
  1069. * defined in misc/ajax.js.
  1070. *
  1071. * @param $selector
  1072. * A jQuery selector string. If the command is a response to a request from
  1073. * an #ajax form element then this value can be NULL.
  1074. * @param $argument
  1075. * An array of key/value pairs to set in the CSS for the selector.
  1076. *
  1077. * @return
  1078. * An array suitable for use with the ajax_render() function.
  1079. *
  1080. * @see http://docs.jquery.com/CSS/css#properties
  1081. */
  1082. function ajax_command_css($selector, $argument) {
  1083. return array(
  1084. 'command' => 'css',
  1085. 'selector' => $selector,
  1086. 'argument' => $argument,
  1087. );
  1088. }
  1089. /**
  1090. * Creates a Drupal Ajax 'settings' command.
  1091. *
  1092. * The 'settings' command instructs the client either to use the given array as
  1093. * the settings for ajax-loaded content or to extend Drupal.settings with the
  1094. * given array, depending on the value of the $merge parameter.
  1095. *
  1096. * This command is implemented by Drupal.ajax.prototype.commands.settings()
  1097. * defined in misc/ajax.js.
  1098. *
  1099. * @param $argument
  1100. * An array of key/value pairs to add to the settings. This will be utilized
  1101. * for all commands after this if they do not include their own settings
  1102. * array.
  1103. * @param $merge
  1104. * Whether or not the passed settings in $argument should be merged into the
  1105. * global Drupal.settings on the page. By default (FALSE), the settings that
  1106. * are passed to Drupal.attachBehaviors will not include the global
  1107. * Drupal.settings.
  1108. *
  1109. * @return
  1110. * An array suitable for use with the ajax_render() function.
  1111. */
  1112. function ajax_command_settings($argument, $merge = FALSE) {
  1113. return array(
  1114. 'command' => 'settings',
  1115. 'settings' => $argument,
  1116. 'merge' => $merge,
  1117. );
  1118. }
  1119. /**
  1120. * Creates a Drupal Ajax 'data' command.
  1121. *
  1122. * The 'data' command instructs the client to attach the name=value pair of
  1123. * data to the selector via jQuery's data cache.
  1124. *
  1125. * This command is implemented by Drupal.ajax.prototype.commands.data()
  1126. * defined in misc/ajax.js.
  1127. *
  1128. * @param $selector
  1129. * A jQuery selector string. If the command is a response to a request from
  1130. * an #ajax form element then this value can be NULL.
  1131. * @param $name
  1132. * The name or key (in the key value pair) of the data attached to this
  1133. * selector.
  1134. * @param $value
  1135. * The value of the data. Not just limited to strings can be any format.
  1136. *
  1137. * @return
  1138. * An array suitable for use with the ajax_render() function.
  1139. *
  1140. * @see http://docs.jquery.com/Core/data#namevalue
  1141. */
  1142. function ajax_command_data($selector, $name, $value) {
  1143. return array(
  1144. 'command' => 'data',
  1145. 'selector' => $selector,
  1146. 'name' => $name,
  1147. 'value' => $value,
  1148. );
  1149. }
  1150. /**
  1151. * Creates a Drupal Ajax 'invoke' command.
  1152. *
  1153. * The 'invoke' command will instruct the client to invoke the given jQuery
  1154. * method with the supplied arguments on the elements matched by the given
  1155. * selector. Intended for simple jQuery commands, such as attr(), addClass(),
  1156. * removeClass(), toggleClass(), etc.
  1157. *
  1158. * This command is implemented by Drupal.ajax.prototype.commands.invoke()
  1159. * defined in misc/ajax.js.
  1160. *
  1161. * @param $selector
  1162. * A jQuery selector string. If the command is a response to a request from
  1163. * an #ajax form element then this value can be NULL.
  1164. * @param $method
  1165. * The jQuery method to invoke.
  1166. * @param $arguments
  1167. * (optional) A list of arguments to the jQuery $method, if any.
  1168. *
  1169. * @return
  1170. * An array suitable for use with the ajax_render() function.
  1171. */
  1172. function ajax_command_invoke($selector, $method, array $arguments = array()) {
  1173. return array(
  1174. 'command' => 'invoke',
  1175. 'selector' => $selector,
  1176. 'method' => $method,
  1177. 'arguments' => $arguments,
  1178. );
  1179. }
  1180. /**
  1181. * Creates a Drupal Ajax 'restripe' command.
  1182. *
  1183. * The 'restripe' command instructs the client to restripe a table. This is
  1184. * usually used after a table has been modified by a replace or append command.
  1185. *
  1186. * This command is implemented by Drupal.ajax.prototype.commands.restripe()
  1187. * defined in misc/ajax.js.
  1188. *
  1189. * @param $selector
  1190. * A jQuery selector string.
  1191. *
  1192. * @return
  1193. * An array suitable for use with the ajax_render() function.
  1194. */
  1195. function ajax_command_restripe($selector) {
  1196. return array(
  1197. 'command' => 'restripe',
  1198. 'selector' => $selector,
  1199. );
  1200. }
  1201. /**
  1202. * Creates a Drupal Ajax 'update_build_id' command.
  1203. *
  1204. * This command updates the value of a hidden form_build_id input element on a
  1205. * form. It requires the form passed in to have keys for both the old build ID
  1206. * in #build_id_old and the new build ID in #build_id.
  1207. *
  1208. * The primary use case for this Ajax command is to serve a new build ID to a
  1209. * form served from the cache to an anonymous user, preventing one anonymous
  1210. * user from accessing the form state of another anonymous users on Ajax enabled
  1211. * forms.
  1212. *
  1213. * @param $form
  1214. * The form array representing the form whose build ID should be updated.
  1215. */
  1216. function ajax_command_update_build_id($form) {
  1217. return array(
  1218. 'command' => 'updateBuildId',
  1219. 'old' => $form['#build_id_old'],
  1220. 'new' => $form['#build_id'],
  1221. );
  1222. }
  1223. /**
  1224. * Creates a Drupal Ajax 'add_css' command.
  1225. *
  1226. * This method will add css via ajax in a cross-browser compatible way.
  1227. *
  1228. * This command is implemented by Drupal.ajax.prototype.commands.add_css()
  1229. * defined in misc/ajax.js.
  1230. *
  1231. * @param $styles
  1232. * A string that contains the styles to be added.
  1233. *
  1234. * @return
  1235. * An array suitable for use with the ajax_render() function.
  1236. *
  1237. * @see misc/ajax.js
  1238. */
  1239. function ajax_command_add_css($styles) {
  1240. return array(
  1241. 'command' => 'add_css',
  1242. 'data' => $styles,
  1243. );
  1244. }