Drupal 7: Updating content using attach behaviours

In Drupal Javascript attach behaviours are help us to perform HTML DOM related operations. With help of Drupal attach behaviours we can able to add the Dynamic HTML content to the HTML. The below example will show the adding AJAX response to the HTML elements.

Syntax:​

callbackUrl = "CALLBACK_URL";
var selectorElement = $(ELEMENT_SPECIFIER);
$.ajax({
  url: callbackUrl,
  type: "GET",
  success: function(data) {
    var response = $(data).find('SELECTOR_ELEMENT');
    selectorElement.html(response);
    Drupal.attachBehaviors(ELEMENT_SPECIFIER);
  }
});

Example:

var callbackUrl = '/admin/content';
var selectorElement  = $("div#block_list");
$.ajax({
  url: callbackUrl,
  type: "GET",
  success: function(data) {
    var result = $(data).find('#block_list');
    $("div#block_list").html(result);
    Drupal.attachBehaviors("div#block_list");
  }
});

 

Category: