Search form

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
@link ajax_commands Ajax framework commands @endlink.

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'].

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
@link forms_api_reference.html Form API Reference @endlink

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:

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 Ajax commands array may be constructed like this:

Actually, a better way often to use $form_state['triggering_element']['#parents'].

In an AJAX callback, the $form_state['triggering_element'] array contains all the information about the form element that triggered the AJAX action. These include the expected #type and #default_value fields and all the fields filled in by the Form API by default, but it also includes the #name, #parents, and #array_parents fields. These last three can be used to determine what element of a form triggered the action.

The #name field might work for simple forms. It has the name of the element, as a string. In a complex form, though, it might be difficult to work with, as it can be something like '#name' => 'packages[11][pkg_type]'. You'd have to parse that.

The #parents or #array_parents fields are much easier to work with. They each contain an array listing the form elements containing the activating element (including itself). So, you can get something like '#parents' => array('packages', 11, 'pkg_type'), so $form_state['triggering_element']['#parents'][1] will give 11, which is the index of the subform in this example.

Here's some working code. The dpm() call requires the Devel module, and allows you to look at everything in $form_state while you're figuring this out. Remove it when you're done debugging.

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, so we bind to mousedown instead of click.

Look at the HTML that's returned -- if your wrapper ID isn't the same as what you're replacing, or if your replacement doesn't also include the ID, the second time will fail because the wrapper doesn't exist!

The description above is hard to understand. For the vast majority of cases, this is all you need to know when you wish to write AJAX:

The usual purpose of AJAX is to dynamically and automatically update (replace) part of a form in response to user input. This is faster and looks cleaner than making the user hit a Submit button and reload the whole page.

An AJAX-ready form defines segments of itself that can be replaced. Each form element that should cause an AJAX action defines a callback function to generate the replacement data and names the part of the form that should be replaced during the action.

During an AJAX action, the Web server calls your normal form function which regenerates the whole form, even if you don't need the whole thing. The form function is called with $form_state fully populated, including $form_state['values'], which contains the current values of user input (as though the user hit a Submit button).

After the form is regenerated, the new form and the current form state are passed to an AJAX callback function you define. This callback function usually returns the new version of element of the form that should be updated.

Once you know that, it's quite easy to use AJAX. This is what you do:

Write your form generation function such that any elements that might change in response to user input take $form_state, especially $form_state['values'], into account. Test if the value is set and use it if it is. For example, the following snippet uses the input of a text field to set the display of an item field. Note that it also uses $form_state to get the '#default_value' field.

To define a portion of the form that should be updated, wrap it in an HTML div with an id property. Use the #prefix and #suffix to do this. So, for the example above, we might want to replace the response field. Define it like this to do so:

To configure a form element to trigger AJAX events, attach an #ajax element to it. The element is itself an array which must define the callback function with its 'callback' value and the part of the form (div) that should be replaced with its 'wrapper' value. If we want updates to happen when the user updates the name field, it might look like this:

Finally, write the callback function. If the main form function is written to build the form using $form_state, then the callback is simple. It gets the entire rebuilt form with updated values, and it only has to return the element that is supposed to change. In this case:

The function can generate the form element any way you like, but this is the easiest way to do it and is compatible if Javascript is turned off. If the function needs to know which form element triggered it, it can refer to $form_state['triggering_element']['#array_parents'].

That's it. Making a form work with AJAX isn't much more difficult than making it work without AJAX.

What's the best way to make an entire form submit via ajax, running the _submit and _validate handlers as normal (so errors are displayed, form items are marked red, etc), then updating some arbitrary markup on the page once submission is successful? Creating an effect similar to how the old ajax module worked for D6.

I can't seem to find this use case anywhere in the documentation or examples module even though it seems very straight forward and typical.

Attaching #ajax to the submit button isn't enough, the form can only be submitted once and appears to ignore the typical _validate and _submit functions. At least, it doesn't color code anything or display messages.

I ended up doing something like this to get the form to submit and validate via ajax, but it doesn't feel correct. Specifying the form's DOM id as the wrapper to replace is an unstable solution, as that can change with multiple form instances. It also doesn't allow updating any other DOM elements on successful submission.

So, I declared a form to use the #ajax properties and it works when printed directly in a page using print render(drupal_get_form("my_form")) and all that.

However, often times ajax forms will be brought into the page via ajax, like inserting a form into a modal window, or loading the DOM of the form somewhere into the page via $.ajax

I would expect that any ajax behaviors attached to a form injected via ajax would bind when Drupal.attachBehaviors(); is called, like every other part of Drupal, but this is not the case. Ajax enabled forms injected via ajax come through dead, and stay dead.

I have made sure that all required libraries are included, like drupal.ajax and jquery.form.

I did notice that ajax parameters for forms rendered traditionally were stored in Drupal.settings.ajax, and that this settings array was not generated via Drupal.attachBehaviors() for forms that were injected via ajax.

I have created a custom form and addition java script on some field
This is working fine when page load but after submit display some require message it,s fine ,but my additional java script not working ,

The outer closure means you can use $ inside the closure to mean jQuery. The attach function gets called when Drupal is ready to initialise it. The context specifies what part of the page is being re-initialised.

You should also use the .once() function to ensure you don't try to reinitialise part of the HTML that's already been processed.

Your code is only run once, when the page loads. With Ajax the code might have to run again on a piece of HTML that's just been loaded.

I have a problem with a textfield that makes an ajax callback on the blur (losing focus) event. If I enter a value and click elsewhere on the page the field gets disabled until the ajax callback has finished and everything is fine.
However, if I enter a value and then directly click on the submit button, the fields value is empty in $form_state['values'].

So my question is:
Is there any way to make the submit button wait until all ajax callbacks of the form have finished?

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.

In fact if you want to return an array of custom Ajax commands from your #ajax['callback'] you must return an array with the following structure:

First off, I am very new to drupal and still learning! I have an ajax callback working for a drop down menu that activates when it changes. It updates a single table. I am trying to make the wrapper an array so it can update multiple tables. My 2nd table keeps disappearing instead of updating. Would this syntax be correct?
....
'#ajax' => array(
'callback' => '_ajax_field_floor_area_callback',
'wrapper' => array (
'field-area' => 'field-area',
'fire-options' => 'fire-options',
)
),
'#default_value' =>...

In order to update both elements you can either arrange your form elements so they're next to each other and can wrap them in a single wrapper div (and then return both form elements in the callback) or you'll need to dip into the more complicated world of ajax commands.

Your callback will have to build a command array itself. Instead of using NULL in those commands like ajax_command_prepare() does you'd call those functions with the wrappers you wanted to use, because NULL will mean the command defaults to the '#wrapper' provided by the triggering element.

I think the "method" handling gets a little disrupted if you handle it like this, too, which means you'll need to add ajax_command_invoke to invoke the replace effects you need if you don't see the fade in you'd like.

Please be aware that when you are writing your forms that if you have the #ajax property in your form element remember to not include the #attributes property with the id portion set.

Attribute ids set on form elements override their default set form ids and prevent #ajax from functioning. If you want to set a custom css id for form elements requiring that kind of theming consider using prefix and suffix with associated wrapper divs.

This was written to save you some time when you are scratching your head trying to figure this out.

Correct me if I am wrong, but it seems to me that that you can't change the http method the ajax request uses. Or, if there is a way, it's not documented here. You are stuck using POST. Which is especially frustrating since a lot of modules look at GET parameters in the URL for their processing.

I've experienced an odd issue with the $form_state['values'] on a parent form element not passing through to subsequent ajax form elements. I had this working (and it still is) on a live site with a custom image rotate feature (https://theor.org/frd) where the values are passing without any issues. In my development environment where I've updated core and contrib to everything around the time of the 7.41 release, the $form_state['values'] on the button that calls up the ajax based image rotate feature is no longer passing through to the ajax callback. This button is inserted via ajax when an image is uploaded. As you can see on the live site, everything works fine. The $form[input] value for that form element does pass through as does all of the other $form_state['values'] values. I'm using $form_state['input'] as a work around, which works basically in the same manner so that is fine. I don't see any major changes in the core ajax.inc files that would cause this and I've undone everything other than the drupal and contrib update in my dev environment and am still encountering the issue. In other words, it's not a critical issue as this is a highly specific use case, but I wanted to point out this inconsistency. Has anyone else experienced this?

I have populating 4 drop-down list box which has been dependent on each other. All are invisible except top one. if we select value from top drop-down then second one will display and if we select value from second one 3rd on will be displayed.. problem is when i populated all in custom form and hits the back button of browser form doesn't get reset. it displays all drop-down with 0 value, but we expected it should be hidden as its initial stage.
how to reset the form on if anyone hits back button of browser???