Ajax framework

You are here

  1. 7 includes/ajax.inc ajax
  2. 8 core/includes/ajax.inc ajax

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:

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:

  $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:

  $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

Namesort descending Location Description
ajax_base_page_theme includes/ajax.inc Theme callback for Ajax requests.
ajax_deliver includes/ajax.inc Packages and sends the result of a page callback as an Ajax response.
ajax_footer includes/ajax.inc Performs end-of-Ajax-request tasks.
ajax_form_callback includes/ajax.inc Menu callback; handles Ajax requests for the #ajax Form API property.
ajax_get_form includes/ajax.inc Gets a form submitted via #ajax during an Ajax callback.
ajax_prepare_response includes/ajax.inc Converts the return value of a page callback into an Ajax commands array.
ajax_pre_render_element includes/ajax.inc Adds Ajax information about an element to communicate with JavaScript.
ajax_process_form includes/ajax.inc Form element processing handler for the #ajax form property.
ajax_render includes/ajax.inc Renders a commands array into JSON.

File

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

Comments

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 render element:

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

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

<?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);
?>

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.

Hi there,
Why we use it:?

    'callback' => 'some_callback_function',
    'wrapper' => 'ajax-response-goes-here',
    'method' => 'replace',
    'effect' => 'fade',

If all them will be specified later!
As I understand to ajax request we must define menu item, where will be specified callback function:

$items['ajax/comments-form/%'] = array(
'title' => 'AJAX MENU ITEM',
'type' => MENU_CALLBACK,
'page arguments' => array(2),
'page callback' => "modulename_comment_form_ajax_html_callback",
'access arguments' => array('access content'),
'delivery callback' => 'ajax_deliver',
);

In call back function we will cpecify where to put result:

$result = array('#type' => 'ajax');
/**
* ajax_command_replace
* ajax_command_insert
*/
$result['#commands'][] = ajax_command_html( '#add-new-comments-form-box', '<b>form html here</b>' );
# result will be blaced to <b>#add-new-comments-form-box</b>
return $result;

There is no need to create your own menu item for Ajax, Drupal (7, at least) provides one for you. This is why you rely on #ajax and the Ajax API.

This doesn't seem to work outside of a form. I think you do need to use path definitions if you just want to turn a normal link into an ajax function.

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,
  ),
);
?>

My form is being submitted on press of Enter Key,
but issue is, its even submitting on mouse down on outside textArea

How to avoid submit a form on MouseDown?
even i have tried with below script,
'prevent' =>'mousedown',
or
'prevent' =>'click'
on Submit button

<?php
$form
=    array('body' => array(
           
'#type'               => 'text_format',
           
'#rows'               => 1,
           
'#after_build'        => array('custom_messages_check_format_access'),
           
'#ajax'               => array(
                               
'callback' => '...',
                               
'wrapper' => '..',
                               
'effect' => 'fade',
                               
'method' => 'replace',
                               
'keypress' => TRUE,
                                ),
         
'#executes_submit_callback' => TRUE,
                          ),
          );
$form['submit'] = array(
                       
'#type'               => 'submit',
                       
'#value'              => t('Send message'),
                       
'#ajax'               => array(
                               
'callback' => '...',
                               
'wrapper' => '..',
                               
'effect' => 'fade',
                               
'method' => 'replace',
                               
'prevent' => 'mousedown',
                        ),
                    );
?>

please suggest me if am wrong or if i have missed any thing

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

You should do bussiness logic in the form constructor.

See the attached file at:
www.monchacos.com/monchacos/code/creating-forms-template-file-ajax-included

Thank you for that $form_state['triggering_element']['#name'], I was banging my head for an hour, and then saw your comment. Very appreciated, and works like a charm ;)

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.

<?php
function uc_stamps_shipment_edit_update_package($form, $form_state) {
 
dpm($form_state, 'AJAX $form_state');
 
$package_id = $form_state['triggering_element']['#parents'][1];
  return
$form['packages'][$package_id];
}
?>

Be careful. #parents and #array_parents are not always the same (depending on #tree). See the Form API Reference for details, and use dpm() to double-check that they are what you expect.

I was searching for days and then I follow your post from stack-overflow and ultimately it solves my problem.

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

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.

See http://drupal.org/node/216059

Source: ajax_pre_render_element()

i have a select option value , in change create a text field with auto complete feature,
every thing is ok , but autocomplelete of this element not work!!!

part of my code

<?php
            $form
['azlocation']=array(
               
'#type' => 'select',
               
'#title' => 'location',
               
'#options' => array(1,2,3),
               
'#default_value' => 1,
               
'#description' => t('select your news location.'),
               
'#ajax' => array(
                       
'event' => 'change',
                       
'callback' => 'country_select_f',
                       
//'path' =>'roadtonowhere',
                       
'wrapper' => 'city-term',
                       
'method' => 'replace',
                       
'effect' => 'fade',
                ),
                );
       
$form['field_terms_city']= array(
               
'#markup' => '<div id="city-term"></div>');
               

               
        function

country_select_f(&$form, $form_state){
   
$form['city_list_item2'] =array(
           
'#type' => 'textfield',
           
'#title' => t('select city (optional)'),
           
'#autocomplete_path' => 'mycustompath/autocomplete',
           
'#weight' => -1,
           
'#attributes' => array('id' =>'city-term-select'),
    );
?>

where is the problem?

I'm able to use the above to create ajax links, but they only work once. Any ideas on how to make the ajaxified links work again after they've been clicked?

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:

  1. 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.
    <?php
    if (! empty($form_state['values']['nameinput'])) {
     
    // The user has typed in a name
     
    $default_name = check_plain($form_state['values']['nameinput']);
     
    $default_answer = t('Your name is ') . $default_name;
    }
    else {
     
    // The user hasn't typed a name, yet.
     
    $default_name = '';
     
    $default_answer = t('I do not know your name yet.');
    }
    form['nameinput'] = array(
     
    '#type' => 'textfield',
     
    '#title' => 'Name',
     
    '#default_value' => $default_name,
    );
    form['response'] = array(
     
    '#type' => 'item',
     
    '#markup' => $default_answer,
    );
    ?>
  2. 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:
    <?php
    form
    ['response'] = array(
     
    '#type' => 'item',
     
    '#markup' => $default_answer,
     
    '#prefix' => '<div id="replace_this">',
     
    '#suffix' => '</div>',
    );
    ?>
  3. 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:
    <?php
    form
    ['nameinput'] = array(
     
    '#type' => 'textfield',
     
    '#title' => 'Name',
     
    '#default_value' => $default_name,
     
    '#ajax' => array(
       
    'wrapper' => 'replace_this',
       
    'callback' => 'update_name_callback',
      ),
    );
    ?>
  4. 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:
    <?php
    function update_name_callback($form, &$form_state) {
      return
    $form['response'];
    }
    ?>

    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.

function productsearchbar_savesearch_form($form, &$form_state) {

    $form["wrapper"] = array("#markup" => "<div class='inline-messages'></div>");
   
    $form["name"] = array(
      "#type" => "textfield",
      "#required" => true,
      "#title" => "Name"
    );
       
    $form["submit"] = array(
      "#type" => "submit",
      "#value" => "Send",
      "#ajax" => array(
        "callback" => "productsearchbar_savesearch_form_callback",
        "wrapper" => "productsearchbar-savesearch-form",
        "effect" => "fade",
        'keypress' => TRUE,
      )
    );

    return $form;
  }

  function productsearchbar_savesearch_form_callback($form, &$form_state) {
    $messages = theme('status_messages');
   
    if($messages){
      $form["wrapper"] = array("#markup" => "<div class='inline-messages'>$messages</div>");
    }
    return $form;
  }
 
  function productsearchbar_savesearch_form_validate($form, &$form_state) {
    if(empty($form_state['values']['name'])){
      form_set_error('', t('No terms provided')); 
    } 
  }
 
  function productsearchbar_savesearch_form_submit($form, &$form_state) {
    drupal_set_message(t('Your form has been saved.'));
  }

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.

Does anyone have any ideas on this?

This issue is also holding up the solution here: http://stackoverflow.com/questions/11341399/drupal-7-how-to-change-multi...

I wonder (out loud ;-) ) how the Hierarchical Select module handles this.

Hi,

is there similar solution in Drupal 6 ?

BR
Piotr

<?php
function assignment_user_add_form($form,&$form_state)
{
     Global
$countries,$states;
    
$values =isset($form_state['values'])?($form_state['values']):array();
     if(!empty(
$values['country']))
        {
           
$states = db_query('SELECT id,state_name FROM {assignment_state} WHERE cid = :cid',array(':cid'=>$values['country']))->fetchAllKeyed(0,1);
        }
   
$form['name'] = array(
       
'#type' => 'textfield',
       
'#title' => t('Name'),
       
'#default_value' => !empty($values['name']) ? $values['name'] : '',
       
'#description' => 'Please Enter a valid name',
       
'#required' => TRUE,
       
'#weight' => -5
   
);

   

$form['pic'] = array(
       
'#type' => 'managed_file',
       
'#title' => t('Profile Pic'),
       
'#default_value' =>!empty($values['pic']) ? $values['pic'] : '',
       
'#description' => 'Try to upload a thumbnail image',
       
'#upload_validators' => array(
           
'file_validate_extensions' => array('gif png jpg jpeg'),
        ),
       
'#upload_location' => 'private://',
       
'#required' => TRUE,
       
'#weight' => -4,
        );

   

$form['region'] = array(
       
'#type' => 'fieldset',
       
'#title' => t('Region'),
       
'#weight' => -3,
       
'#collapsible' => TRUE,
    );

   

$form['region']['country'] = array(
       
'#type' => 'select',
       
'#title' => t('Country'),
       
'#options' =>$countries,
       
'#default_value' =>!empty($values['country'])?$values['country'] : '',
       
'#ajax' => array(
           
'callback' => '_replace_state_callback',
           
'wrapper' => 'dependent-select-state',
           
'method' => 'replace',
        ),
       
'#required' => TRUE,
       
'#weight' =>-2,
    );

   

$form['region']['state'] = array(
   
'#type' => 'select',
   
'#title' => t('State'),
   
'#options' =>$states,
   
'#default_value' =>!empty($values['state']) ? $values['state'] : '',
   
'#prefix' => '<div id="dependent-select-state" style="float:left;">',
   
'#suffix' => '</div>',
   
'#required' => TRUE,
   
'#weight' =>-1,
    );
   
$form['save'] = array(
       
'#type' => 'submit',
       
'#title' => t('Save'),
        
'#value' => t('Save'),
       
'#weight' => 0,
    );
    return
$form;
}
function
_replace_state_callback($form,&$form_state)
{
     return
$form['region']['state'];
}
?>

I need to change wrapper id dynamically please suggest me that this is possible in drupal ,

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 ,

this is my form code

function youtube_video_form_setp1($form,&$form_state) {
$form = array();
$form['youtube_form'] = array(
'#type' => 'fieldset',
'#title' => t('Share video with us.'),
'#weight' => 5,
'#prefix' => '',
'#suffix' => '',
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['youtube_form']['title'] = array(
'#type' => 'textfield',
'#title' => t('Title'),
'#size' => 60,
'#required' => TRUE,
);
$form['youtube_form']['desc'] = array(
'#title' => t('Description'),
'#type' => 'textarea',
'#description' => t ('Please Enter video Description'),
'#required' => TRUE,
);
$form['youtube_form']['category'] = array(
'#type' => 'select',
'#title' => t('Category'),
'#options' => youtube_video_import_get_taxonomy_value(12),//12 video category id
'#description' => t('Select video category.'),
'#required' => TRUE,
'#prefix' => '',
'#suffix' => '',
);
$form['youtube_form']['new-category'] = array(
'#type' => 'textfield',
'#title' => t('Category title'),
'#required' => TRUE,
'#default_value' =>0,
'#size' => 35,
'#prefix' => '',
'#suffix' => '',
);
$form['return_url'] = array (
'#type' => 'hidden',
'#value' =>'home',
);
$form['youtube_form']['submit'] = array(
'#type' => 'submit',
'#value' => t('Next>>'),
'#ajax' => array(
'callback' => 'youtube_video_form_setp1_process',
'wrapper' => 'youtube-render-second-form',
'method' => 'html',
'effect' => 'fade',
),
);
$form['#attached'] = array(
drupal_get_path('theme', 'danland') . '/scripts/jquery.cycle.all.js' => array(
'type' => 'file',
)
);

/*$form['#attached']['js'] = array(
drupal_get_path('module', 'ajax_example') . '/ajax_example.js' => array(
'type' => 'file',
),*/
return $form;
}

And this is my java script code ..

jQuery(document).ready(function($) {
$('.slideshow').cycle({
fx: 'fade' , timeout: 8000, delay: 2000});

alert('all');
/* js for youtube form*/
jQuery('span#pre-video-category select').change(function() {
cvalue = jQuery(this).val();

if(cvalue == 0 && cvalue!=''){
jQuery('span#new-video-category input[type="text"]').val('');
jQuery('span#new-video-category').show();

}else{
jQuery('span#new-video-category').hide();
jQuery('span#new-video-category input[type="text"]').val(0);
}
});

});

I want to track on span#pre-video-category select
please suggest me
thanks
Anil kumar ravat

Your JS file isn't written the prescribed way. You have to wrap it in a specific structure:

(function($){

Drupal.behavior.yourCodeName = {
attached : function(settings, context) {
// Your initialisation code.
}
}

})(jQuery);

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.

Check any third party module with a JS file to see how it's done.

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?

I found this part of the documentation misleading:

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:

function my_ajax_callback($form, $form_state) {
  $result = array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace($selector1, $html1),
      ajax_command_replace($selector2, $html2),
    ),
  );
  return $result;
}

I worked this out by reading through the code for ajax_prepare_response(): https://api.drupal.org/api/drupal/includes%21ajax.inc/function/ajax_prep....

Hopefully that will help someone.

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

#wrapper should only contain a single string.

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.

If you look into the guts of the ajax system you'll find ajax_prepare_response() which is one of the functions that handles the "easy" way for you. This snippet is basically the part you need to emulate...
https://api.drupal.org/api/drupal/includes%21ajax.inc/function/ajax_prep...

<?php

...
$html = is_string($page_callback_result) ? $page_callback_result : drupal_render($page_callback_result);
   
$commands[] = ajax_command_insert(NULL, $html);
   
// Add the status messages inside the new content's wrapper element, so that
    // on subsequent Ajax requests, it is treated as old content.
   
$commands[] = ajax_command_prepend(NULL, theme('status_messages'));
  }

  return

$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.

<?php

  $commands

= array();
 
$commands[] = ajax_command_html('#element1', drupal_render($select1));
 
$commands[] = ajax_command_replace("#element2", drupal_render($select2));
  return array(
'#type' => 'ajax', '#commands' => $commands);
?>

The exhaustive list is here: https://api.drupal.org/api/drupal/includes%21ajax.inc/group/ajax_commands/7

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.

How to filter as well as paginate through AJAX?

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.

can i use ajax_command_xxx to get the dynamic input content ?
or what should do to get each time user's input content but in a form

thanks

Can somebody help me adding a form elements via ajax. But ajax must be called from an anchor element or link outside the form.

Thanks