1

I'm trying to do an ajax callback on page every load with drupal to get some info. The problem is that when the ajax callback is done and the data processed, Drupal continues calling the ajax function once and over again adding the typical "Please wait..." text repeatedly.

The javascript:

(function($){

  Drupal.behaviors.myModule = {
    attach: function () {
      var settings = {};
      settings.url = '/my_module_ajax_callback';
      settings.event = 'onload';
      settings.keypress = false;
      settings.prevent = false;

      var base = 'myModule';
      var ajax = new Drupal.ajax(null, $(document.body), settings);
      Drupal.ajax[base] = ajax;

      $(ajax.element).trigger('onload');
    }
  }

})(jQuery);

The php:

<?php

function my_module_init() {
  drupal_add_library('system', 'drupal.ajax');
}

function my_module_menu() {
  $items['my_module_ajax_callback'] = array(
    'page callback' => 'my_module_ajax_callback',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function my_module_block_info() {
  $blocks['my_module_block'] = array(
    'info' => t('My Module Block'),
  );
  return $blocks;
}

function my_module_block_view() {
  $block = array();

  $block['content'] = '<div id="my_div">This data must be replaced by ajax</div>';

  return $block;
}

function my_module_ajax_callback() {

  $commands[] = ajax_command_replace('#my_div', '<div id="my_div">This data has been replaced by ajax</div>');

  $page = array('#type' => 'ajax', '#commands' => $commands);

  ajax_deliver($page);
}

Seems the ajax callback is never complete.

In misc/ajax.js:

complete: function (response, status) {
  ajax.ajaxing = false;
  if (status == 'error' || status == 'parsererror') {
    return ajax.error(response, ajax.url);
  }
},

I don't know what I'm doing wrong. I really appreciate your help. Thanks.

0

I've found a solution myself. Seems after the ajax callback the attach function is called again, so I surrounded by a jQuery .once() method:

(function($){

  Drupal.behaviors.myModule = {
    attach: function (context, settings) {

      $('#my_div', context).once('my_div', function () {
        var elem_settings = {};
        elem_settings.url = '/my_module_ajax_callback';
        elem_settings.event = 'load';
        elem_settings.keypress = false;
        elem_settings.prevent = false;

        var base = 'myModule';
        var ajax = new Drupal.ajax(base, this, elem_settings);
        Drupal.ajax[base] = ajax;

        $(this).trigger('load');
      });
    }
  }

})(jQuery);

This prevents calling the ajax once and over again.

https://drupal.org/node/756722#jquery-once

https://drupal.org/node/2192041

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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