Community Documentation

Ajax framework

  1. drupal
    1. 7 ajax.inc
    2. 8 ajax.inc

Functions for Drupal's Ajax framework.

Drupal's Ajax framework is used to dynamically update parts of a page's HTML based on data from the server. Upon a specified event, such as a button click, a callback function is triggered which performs server-side logic and may return updated markup, which is then replaced on-the-fly with no page refresh necessary.

This framework creates a PHP macro language that allows the server to instruct JavaScript to perform actions on the client browser. When using forms, it can be used with the #ajax property. The #ajax property can be used to bind events to the Ajax framework. By default, #ajax uses 'system/ajax' as its path for submission and thus calls ajax_form_callback() and a defined #ajax['callback'] function. However, you may optionally specify a different path to request or a different callback function to invoke, which can return updated HTML or can also return a richer set of Ajax framework commands.

Standard form handling is as follows:

  • A form element has a #ajax property that includes #ajax['callback'] and omits #ajax['path']. See below about using #ajax['path'] to implement advanced use-cases that require something other than standard form handling.
  • On the specified element, Ajax processing is triggered by a change to that element.
  • The browser submits an HTTP POST request to the 'system/ajax' Drupal path.
  • The menu page callback for 'system/ajax', ajax_form_callback(), calls drupal_process_form() to process the form submission and rebuild the form if necessary. The form is processed in much the same way as if it were submitted without Ajax, with the same #process functions and validation and submission handlers called in either case, making it easy to create Ajax-enabled forms that degrade gracefully when JavaScript is disabled.
  • After form processing is complete, ajax_form_callback() calls the function named by #ajax['callback'], which returns the form element that has been updated and needs to be returned to the browser, or alternatively, an array of custom Ajax commands.
  • The page delivery callback for 'system/ajax', ajax_deliver(), renders the element returned by #ajax['callback'], and returns the JSON string created by ajax_render() to the browser.
  • The browser unserializes the returned JSON string into an array of command objects and executes each command, resulting in the old page content within and including the HTML element specified by #ajax['wrapper'] being replaced by the new content returned by #ajax['callback'], using a JavaScript animation effect specified by #ajax['effect'].

A simple example of basic Ajax use from the Examples module follows:

<?php
function main_page() {
  return drupal_get_form('ajax_example_simplest');
}

function ajax_example_simplest($form, &$form_state) {
  $form = array();
  $form['changethis'] = array(
    '#type' => 'select',
    '#options' => array(
      'one' => 'one',
      'two' => 'two',
      'three' => 'three',
    ),
    '#ajax' => array(
      'callback' => 'ajax_example_simplest_callback',
      'wrapper' => 'replace_textfield_div',
     ),
  );

  // This entire form element will be replaced with an updated value.
  $form['replace_textfield'] = array(
    '#type' => 'textfield',
    '#title' => t("The default value will be changed"),
    '#description' => t("Say something about why you chose") . "'" .
      (!empty($form_state['values']['changethis'])
      ? $form_state['values']['changethis'] : t("Not changed yet")) . "'",
    '#prefix' => '<div id="replace_textfield_div">',
    '#suffix' => '</div>',
  );
  return $form;
}

function ajax_example_simplest_callback($form, $form_state) {
  // The form has already been submitted and updated. We can return the replaced
  // item as it is.
  return $form['replace_textfield'];
}
?>

In the above example, the 'changethis' element is Ajax-enabled. The default #ajax['event'] is 'change', so when the 'changethis' element changes, an Ajax call is made. The form is submitted and reprocessed, and then the callback is called. In this case, the form has been automatically built changing $form['replace_textfield']['#description'], so the callback just returns that part of the form.

To implement Ajax handling in a form, add '#ajax' to the form definition of a field. That field will trigger an Ajax event when it is clicked (or changed, depending on the kind of field). #ajax supports the following parameters (either 'path' or 'callback' is required at least):

  • #ajax['callback']: The callback to invoke to handle the server side of the Ajax event, which will receive a $form and $form_state as arguments, and returns a renderable array (most often a form or form fragment), an HTML string, or an array of Ajax commands. If returning a renderable array or a string, the value will replace the original element named in #ajax['wrapper'], and theme_status_messages() will be prepended to that element. (If the status messages are not wanted, return an array of Ajax commands instead.) #ajax['wrapper']. If an array of Ajax commands is returned, it will be executed by the calling code.
  • #ajax['path']: The menu path to use for the request. This is often omitted and the default is used. This path should map to a menu page callback that returns data using ajax_render(). Defaults to 'system/ajax', which invokes ajax_form_callback(), eventually calling the function named in #ajax['callback']. If you use a custom path, you must set up the menu entry and handle the entire callback in your own code.
  • #ajax['wrapper']: The CSS ID of the area to be replaced by the content returned by the #ajax['callback'] function. The content returned from the callback will replace the entire element named by #ajax['wrapper']. The wrapper is usually created using #prefix and #suffix properties in the form. Note that this is the wrapper ID, not a CSS selector. So to replace the element referred to by the CSS selector #some-selector on the page, use #ajax['wrapper'] = 'some-selector', not '#some-selector'.
  • #ajax['effect']: The jQuery effect to use when placing the new HTML. Defaults to no effect. Valid options are 'none', 'slide', or 'fade'.
  • #ajax['speed']: The effect speed to use. Defaults to 'slow'. May be 'slow', 'fast' or a number in milliseconds which represents the length of time the effect should run.
  • #ajax['event']: The JavaScript event to respond to. This is normally selected automatically for the type of form widget being used, and is only needed if you need to override the default behavior.
  • #ajax['prevent']: A JavaScript event to prevent when 'event' is triggered. Defaults to 'click' for #ajax on #type 'submit', 'button', and 'image_button'. Multiple events may be specified separated by spaces. For example, when binding #ajax behaviors to form buttons, pressing the ENTER key within a textfield triggers the 'click' event of the form's first submit button. Triggering Ajax in this situation leads to problems, like breaking autocomplete textfields. Because of that, Ajax behaviors are bound to the 'mousedown' event on form buttons by default. However, binding to 'mousedown' rather than 'click' means that it is possible to trigger a click by pressing the mouse, holding the mouse button down until the Ajax request is complete and the button is re-enabled, and then releasing the mouse button. For this case, 'prevent' can be set to 'click', so an additional event handler is bound to prevent such a click from triggering a non-Ajax form submission. This also prevents a textfield's ENTER press triggering a button's non-Ajax form submission behavior.
  • #ajax['method']: The jQuery method to use to place the new HTML. Defaults to 'replaceWith'. May be: 'replaceWith', 'append', 'prepend', 'before', 'after', or 'html'. See the jQuery manipulators documentation for more information on these methods.
  • #ajax['progress']: Choose either a throbber or progress bar that is displayed while awaiting a response from the callback, and add an optional message. Possible keys: 'type', 'message', 'url', 'interval'. More information is available in the Form API Reference

In addition to using Form API for doing in-form modification, Ajax may be enabled by adding classes to buttons and links. By adding the 'use-ajax' class to a link, the link will be loaded via an Ajax call. When using this method, the href of the link can contain '/nojs/' as part of the path. When the Ajax framework makes the request, it will convert this to '/ajax/'. The server is then able to easily tell if this request was made through an actual Ajax request or in a degraded state, and respond appropriately.

Similarly, submit buttons can be given the class 'use-ajax-submit'. The form will then be submitted via Ajax to the path specified in the #action. Like the ajax-submit class above, this path will have '/nojs/' replaced with '/ajax/' so that the submit handler can tell if the form was submitted in a degraded state or not.

When responding to Ajax requests, the server should do what it needs to do for that request, then create a commands array. This commands array will be converted to a JSON object and returned to the client, which will then iterate over the array and process it like a macro language.

Each command item is an associative array which will be converted to a command object on the JavaScript side. $command_item['command'] is the type of command, e.g. 'alert' or 'replace', and will correspond to a method in the Drupal.ajax[command] space. The command array may contain any other data that the command needs to process, e.g. 'method', 'selector', 'settings', etc.

Commands are usually created with a couple of helper functions, so they look like this:

<?php
  $commands = array();
  // Replace the content of '#object-1' on the page with 'some html here'.
  $commands[] = ajax_command_replace('#object-1', 'some html here');
  // Add a visual "changed" marker to the '#object-1' element.
  $commands[] = ajax_command_changed('#object-1');
  // Menu 'page callback' and #ajax['callback'] functions are supposed to
  // return render arrays. If returning an Ajax commands array, it must be
  // encapsulated in a render array structure.
  return array('#type' => 'ajax', '#commands' => $commands);
?>

When returning an Ajax command array, it is often useful to have status messages rendered along with other tasks in the command array. In that case the the Ajax commands array may be constructed like this:

<?php
  $commands = array();
  $commands[] = ajax_command_replace(NULL, $output);
  $commands[] = ajax_command_prepend(NULL, theme('status_messages'));
  return array('#type' => 'ajax', '#commands' => $commands);
?>

See Ajax framework commands

Functions & methods

NameDescription
ajax_base_page_themeTheme callback for Ajax requests.
ajax_deliverPackages and sends the result of a page callback as an Ajax response.
ajax_footerPerforms end-of-Ajax-request tasks.
ajax_form_callbackMenu callback; handles Ajax requests for the #ajax Form API property.
ajax_get_formGets a form submitted via #ajax during an Ajax callback.
ajax_prepare_responseConverts the return value of a page callback into an Ajax commands array.
ajax_pre_render_elementAdds Ajax information about an element to communicate with JavaScript.
ajax_process_formForm element processing handler for the #ajax form property.
ajax_renderRenders a commands array into JSON.

File

includes/ajax.inc, line 8
Functions for use with Drupal's Ajax framework.

Comments

Include ajax.inc manually if not on a form

If you want to use the "use-ajax" or "use-ajax-submit" functionality, outside of a form context, you need to include the javascript files yourself.

Add the following code to include the needed code. (Add it to just the needed pages, or set them to load on every page)

  drupal_add_library('system', 'drupal.ajax');
  drupal_add_library('system', 'jquery.form');

You can also attach it to a

You can also attach it to a render element:

<?php
$element
['#attached'] = array(
 
'library' => array(
    array(
'system', 'drupal.ajax'),
  ),
);
?>

AJAX on a link with no form.

Here's a simple example of all kinds of AJAXy goodness without a form:

$link = array(
  '#type' => 'link',
  '#title' => t('something'),
  '#href' => 'some/path'
    '#ajax' => array(
      'callback' => 'some_callback_function',
      'wrapper' => 'ajax-response-goes-here',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  // Using the onload below is entirely optional; It's just included as
  // a reminder of an easy way to add extra simple jQuery tricks.
  '#attributes' => array(
   'onload' => "jQuery('something-to-hide').hide();",
  ),
);
 
$output = "<div id='ajax-response-goes-here'></div>Some HTML and stuff" . drupal_render($link);

Yes, it's better to use the fancy new RenderAPI's renderable array's when you can, but this can make for an easy way to add AJAX to legacy code.

Typo?

It looks like there's a typo at the #href line. Something missing between the comma and the '#ajax', but I'm not sure what yet.

Just a little come after

Just a little come after 'some/path'

'#href' => 'some/path',
'#ajax' => array(

Here is the code without the typo:

<?php
    $link
= array(
       
'#type' => 'link',
       
'#title' => t('something'),
       
'#href' => 'some/path',
       
'#ajax' => array(
           
'callback' => 'some_callback_function',
           
'wrapper' => 'ajax-response-goes-here',
           
'method' => 'replace',
           
'effect' => 'fade',
        ),
       
// Using the onload below is entirely optional; It's just included as
        // a reminder of an easy way to add extra simple jQuery tricks.
       
'#attributes' => array(
           
'onload' => "jQuery('something-to-hide').hide();",
        ),
    );

$output = "<div id='ajax-response-goes-here'></div>Some HTML and stuff" . drupal_render($link);
?>

a question

What should be written in the callback? On pages without a form.

question

Is it possible to implement this on the standard drupal menu to load a page div instead of all page. And if it is, then how to do that?

Trigger AJAX with enter key

This isn't documented here, but to trigger an AJAX callback using the enter key when focusing on an element, add keypress = TRUE to the #ajax array, e.g.:

<?php
$form
['element'] = array(
 
'#type' => 'textfield',
 
'#title' => 'Title',
 
'#ajax' => array(
   
'callback' => '...',
   
'keypress' => TRUE,
  ),
);
?>

AJAX with multi field

Refering to http://stackoverflow.com/questions/6088455/pass-arguments-to-ajax-callba..., I thought this code could be useful for those who needs to use ajax with a list of fields (ex. products list):

<?php
function multifield_form($form, &$form_state) {
 
$form = array();

  for(
$i = 0; $i < 10; $i++) {
   
$form['row' . $i] = array(
     
'#title' => t('Row: ' . $i),
     
'#type' => 'select',
     
'#options' => array(0, 1, 2),
     
'#ajax' => array(
       
'callback' => 'ajax_multifield_callback',
       
'wrapper' => 'replace_row_div' . $i,
      ),
    );

   
$form['replace_row' . $i] = array(
     
'#type' => 'textfield',
     
'#title' => t("Result row:" . $i),
     
// The prefix/suffix provide the div that we're replacing, named by
      // #ajax['wrapper'] above.
     
'#prefix' => '<div id="replace_row_div' . $i . '">',
     
'#suffix' => '</div>',
    );

    if (!empty(
$form_state['values']['row' . $i])) {
     
$form['replace_row' . $i]['#value'] = $form_state['values']['row' . $i];
    }   
  }
 
  return
$form;
}

function
ajax_multifield_callback($form, $form_state) {
 
// Get field name
 
$fieldname = $form_state['triggering_element']['#name'];
 
// The form has already been submitted and updated. We can return the replaced
  // item as it is.
 
return $form['replace_' . $fieldname];
}
?>

Cheers

This seems really confusing.

submit ajax callback

Thank you for this page. I've been looking for two days on how to get my submit working. Now a few questions.

Are the '#ajax' attributes (callback, wrapper,etc. ) on a submit element taken into account? Is the only 'Drupal' way of handling form submission via ajax done by adding the 'use-ajax-submit' class?

Does using the 'use-ajax-submit' class also disregard the '#submit' handler array?

Does the framework say that when doing form submission via ajax, you have to specify a custom action, define that callback with hook_menu and work it that way?

Thanks, Im just really trying to do this the right way.

I also checked the ajax submit example from the Examples module and it looks like it's 'incorrect' there as well.

I have a problem with my ajax

I have a problem with my ajax enabled button. clicking the button is not calling the callback function as long as there is a required field not yet populated. Once I populated the required fields the ajax functionality works well. Is this normal behavior.

I have a problem with my ajax

I am responding to chalee.

Use '#limit_validation_errors' on the submit button and include only those elements which you want to be validated when someone clicks on that button.

@neeravbm: Thanks for the

@neeravbm: Thanks for the suggestion to use '#limit_validation_errors'. It seems to solve the issue. I'm not able to fully test it because i have another issue. The issue is that the ids of the elements within the wrapper returned by the ajax callback function are being appended by an incremented number on each ajax callback. e.g if an element had id= "element-id-und" it would now have id="element-id-und--1" and on next callback it would have id="element-id-und--2". This is causing problems for me. Is this normal behaviour? Can it be prevented?

I'm trying to attach ajax to

I'm trying to attach ajax to a select list and when something is selected, I want to set a cookie and refresh the entire page. Anyone can help me ? My code is called, but the page refresh does not want to work so far :(

--------------------------------------------------------
JGO | http://www.hosted-power.com
--------------------------------------------------------

Form Submission - reponse to emackn

There is a huge black hole in the documentation regarding ajax form submission - for example $form_state['redirect'] will not work from within a ajax form submit handler, because $form_state['no_redirect'] is set. Using drupal_goto simply results in AJAX 200 http errors.

Still cannot work this out after days of research and attempts. Glad you have also went through the mangler as otherwise I would feel I am the only person banging thier head against the wall.

is there any tutorial on how

is there any tutorial on how to use drupal 7 ajax framework outside the forms elements ??? please if there is link me

Updating One Element From Another

I need to update a form element using AJAX based on the selection of a different form element. It looks like the AJAX api only works when the AJAX callback affects the element its attached to, not a different element.

Is there a way to use the built in AJAX api to do this? Is there any method of getting around the dreaded "An illegal choice has been detected" error in this context?

Ajax form validation *BUT* redirection

Hi,
the site I'm working on uses many inline webform forms (as blocks). Ajax validation is pretty useful, because of the theming constraints I had. If any field is missing, no page reloading is necessary, and this is clean.
But, I would like to redirect the users on a new page after a validation success.
In other words, I would like to perform an Ajax validation but, finally, an ordinary submission. Adding a drupal_goto() in the callback function doesn't work for this task.
The solution I have found for now is to check wether a $form_state['values']['details']['sid'] exists, which means that the validation process was sucessfull. It also means that the submission is finished. I have tried to set an ugly javascript redirection in the response code, but this is really ugly, and the "go back" link returns two steps backwards.
Which solution would you suggest for this situation ?

CTools has an AJAX command

CTools has an AJAX command for redirecting. Enable CTools on your site and add this to the AJAX callback function:

<?php
ctools_include
('ajax');
ctools_add_js('ajax-responder');
$commands[] = ctools_ajax_command_redirect('my/redirect/path');
?>

Respond to AJAX activity in Javascript

I have a module that has some JavaScript which listens for events on my form elements and does various things. The trouble is that if I create the listeners on document.ready(), it doesn't know about the elements that are created by Drupal Ajax.

Let's say I have a fieldset with a list of checkboxes and I want to do something like alert a message when the user clicks one of the boxes. I also have an AJAX enabled button that you can click to add another checkbox to the fieldset.

In this particular case, my JavaScript code works for all checkboxes that are created on page load, but the ones that are created by AJAX when the "Add Checkbox" button is clicked do nothing when they are clicked.

Is there an event that is triggered by Drupal when the AJAX has finished reloading the elements on the page? If I can bind this event, I can refresh my even listeners.

Thoughts?

I have the same issue with ajax generated input fields

But this is with textfields and I'm now assuming the other input fields.
The ones that are ajax generated are not accepting user input and will only return it's default value on submit.

I too would like to now if there is a way to bind an event to the elements once ajax has delivered them to the page or if there is any other way to recognize changes to these fields with or without doing new ajax calls?

I really do not want have to do do ajax calls for every possible field in this form as it is quite dymanic atm.

What about behaviors?

I think you are looking a function like jquery.live, Drupal 6 mimic this functionality with Drupal.behaviors. That way you can attach events to new elements on a page. Hope that helps!

Changing the functionality of Drupal.ajax

Hi,

I would like to ask if its possible though the ajax framework to change the functionality of a link or I should write a new library. Let's say for example that I have two links

<div id="navigation">
   <a href="mymenu/link1" class="use-ajax">Link1</a>
   <a href="mymenu/link2" class="use-ajax">Link2</a>
</div>

where link1,link2 has been defined by a hook_menu mechanism

<?php


function myhook_menu()
{
   
$items['mymenu/%'] = array(
       
//'title' => 'News',
       
'page callback' => 'mycallback',
       
'page arguments' => array(1),
       
'type' => MENU_CALLBACK,
    );   
   
    return
$items;
}

function
mycallback($name,$type="ajax")
{
   
$commands = array();
   
$commands[] = ajax_command_append(
       
'#navigation',
       
'<div class=myclass".name.">'.$name.'</div>'
   
);
   
$page = array(
       
'#type' => 'ajax',
       
'#commands' => $commands);
   
ajax_deliver($page);   
   
}
?>

What the above does is that every time I press a link an ajax request is made and a new div element is added below div#navigation. e.g.

<div id="navigation">
   <a href="mymenu/link1" class="myclasslink1 use-ajax">Link1</a>
   <a href="mymenu/link2" class="myclasslink2 use-ajax">Link2</a>
   <div class="myclasslink1">Link1</div>
   <div class="myclasslink2">Link2</div>
   <div class="myclasslink2">Link2</div>
   <div class="myclasslink2">Link2</div>
   <div class="myclasslink1">Link1</div>
   ....
</div>

What I would like to do is the following

  1. The first time I press a link an ajax request to be made and a new div element to be added
  2. Before adding the new element all the other elements e.g. div.myclasslink2 should get hidden
  3. The second time I press the link instead of an ajax request I would like to show me the div.myclasslink that corresponds to the specific link and which had been brought on the first click.

Is the above possible with the normal mechanism of the framework or should I create my own library?

I have a problem inserting an ajax field in a form_alter

Hello, I'm not sure if it is that the code of my dependent dropdown is wrong (the 'callback' function don't seem to pull any action) although it seems perfectly right or it is that I'm trying to insert this dropdowns in a form_alter (alters the register form and the profile form) using this:

<?php
  $form
['#after_build'][] = 'myform_dependent_dropdown';
?>

Anyhow, it doesn't work and it's been already three days of contemplation... :P

Can anyone guide me in this?

thanks a lot

pop-up on form submit

Hello,

When a non-athenticated user clicks on the "submit" button, I would like to display a pop-up window, so that the user can login or register.
Only then after the user has logged-in or registered, he can post the form.
See working example here that I'd like to reproduce:
http://www.neezz.com/en/annonces/deposer-une-annonce

It seems from the comments above that neither $form_state['redirect'] nor drupal_goto will work.
Is there an example somewhere in the Drupal documentation on an "ajaxified" use of a submit action?

ajax not returning updated form content?

I had a problem of my ajax callback not returning a form component in an updated form. I had forgotten to set $form['rebuild'] in the submit function.

Forms preventing my callback from working

I have js attached to an element in a form that sends it's new value to a callback. For some reason, the callback function never gets hit.

I have experimented and found that callbacks do not work on node edit forms. I assume it has something to do with the new ajax functionality built into forms.

Can anyone tell me how to get around this problem - maybe by disabling this new functionality?

Thanks

Drupal insanity

The default ajax event for submit button is 'mousedown'. This creates problem as keypress inside texfields won't submit the form.

Set the #ajax['event'] = "click" in the submit button, and you can submit the form by hitting enter in one of the textfields

Multiple ajax callback and event

Is there a way to have multiple ajax event binded to a single element ?
For instance :
"Click event" triggers _my_module_click_ajax_callback()
"Hover event" triggers _my_module_hover_ajax_callback()

On the other hand is it possible to attach multiple callback to a single event ? For instance :
"Click event" triggers _my_module1_click_ajax_callback1() and _my_module2_click_ajax_callback2()

Thanks !

Login or register to post comments