How can i add some data to drupal setting object using drupal_add_js withing some ajax callback?

For example I have ajaxified flag link on my page, and have implemented hook_flag in my module, how can I add JS within this hook?

function hook_flag($action, $flag, $content_id, $account) {
      'my_module' => array('color' => 'green')

3 Answers 3


drupal_add_js is designed to work when you are rendering a page, it doesn't really work for AJAX callbacks and it doesn't need to. If you want to modify the Drupal.settings data, you should do so within the JavaScript invoking the ajax call. It could look like this:

  url: "mydomain.com/url",
  type: "POST",
  dataType: "json",
  data: $.param( $("Element or Expression") ),

  success: function(json) {
    Drupal.settings.data = json.data;

  • Thanks, and what if I want to push some data available only in this particular hook to Drupal.settings?
    – nextanz
    Commented Mar 3, 2012 at 18:31
  • @nextanz I don't understand - an ajax callback is not a hook. What are you talking about?
    – googletorp
    Commented Mar 6, 2012 at 13:22
  • if you will select "JavaScript toggle" in flag's settings, then flag handler and hook_flag will be handled via ajax. I have some data in my implementation of hook_flag which I want to pass into Drupal.settings.
    – nextanz
    Commented Mar 6, 2012 at 20:45
  • This solution works if you are making the ajax callback yourself - but if you are using Drupal's in-build ajax callbacks (eg. using #ajax in the Form API), then look at djayp34's answer instead. Commented Jul 25, 2013 at 9:58

drupal_add_js doesn't work properly in an AJAX callback. If you need to execute a JavaScript function within an AJAX callback, here's a way :

First, in your form, you have to create (you can just import it) the JavaScript function :

function my_module_form($form, &$form_state) {
// [...]
    'Drupal.ajax.prototype.commands.myFunction = function(ajax, response, status) {
      // Whatever you want to do.
// [...]
  return $form;

Then, in your AJAX callback, you need to call this function you created :

function my_module_my_ajax_callback($form, &$form_state) {
// [...]
  $commands[] = array("command" => 'myFunction',);
// [...]
  return array('#type' => 'ajax', '#commands' => $commands);

Hope it helps !

  • Even though this is not marked as the "correct" answer is more complete since leverage the full power of AJAX API allowing youu to send more than just settings and avoids messing around with Drupal.ajax object.
    – d70rr3s
    Commented Jan 16, 2020 at 12:46

If you want the updated values of your variables Drupal.settings.my_module, you can use response data at ajaxComplete

  $( document ).ajaxComplete(function( event,response, settings ) {

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.