Take the 2-minute tour ×

I have some textbook-simple jquery code that makes an ajax call and writes the result to the web page. It works on its own, but not when included in a page on a drupal 7 site.

The code is being included via a custom module that writes to the page using hook_block_view_alter(). Here it is:

        alert("starting ajax call.");
         type: "GET",
         url: 'http://my.datasource.page/',
         data: "parameter=5",
         success: function(data) {
            alert('starting ajax callback');
            result = "The oracle says: " + data;
            jQuery('#ccbuy').fadeOut( function() { jQuery('#ccbuy').html(result); jQuery('#ccbuy').fadeIn(); });
            alert('ajax callback complete');
        alert('ajax call complete');

If I put this in a regular web page, here's what happens:

  1. I click the link with ID "carrotlink".
  2. I get an alert "starting ajax call" followed immediately by "ajax call complete".
  3. A moment later, I get the alerts "starting ajax callback" and "ajax callback complete".
  4. The div with ID "ccbuy" fades out and fades in with the new content.

When I include this code in a drupal page, clicking the link brings up the "starting ajax call" and "ajax call complete" alerts, but I never get the callback alerts, and the div never changes.

I've spent hours trying to debug this, resulting in the simplified case above. Clearly my jquery is functioning, the target link is being altered as intended, and the intended function is called when I click it. The ajax call just isn't happening. Why could this be?

PS - I know drupal has its own methods for replacing text via ajax, as well as drupal_add_js(). But I've already written the functions I'm trying to use as part of a standalone website, and I'd rather include them in a drupal page than reimplement everything. And it seems like it's so close to working!

share|improve this question
add comment

1 Answer

You may just be missing the behavior wrappers. try wrapping the text in the behaviors and behaviors attach code:

(function ($) {
  Drupal.behaviors.ajax_example = {
    attach:function (context) {

      // If the site name is present set it to the username.
      if ($('#site-name', context).length) {
          url: '/ajax/username',
          success: function(data) {

            // Change site name to current user name.
            $('#site-name a span').html(data + '.com');

I wrote a full blog post for my company blog on doing ajax in Drupal 6 & 7 that may be of some help as well: http://clikfocus.com/blog/simple-ajax-example-drupal-6-and-7

share|improve this answer
add comment

Your Answer


