Sunday, January 8, 2017

Native Drupal ajax requests

If you are using jQuery.ajax() or jQuery.post() for background requests you should have a look at native Drupal ajax implementation. Drupal provides a js object Drupal.ajax that performs all needed actions for you (like processing ajax commands that came from back-end side). All that you need to do is to create instance of this object and configure it.

Send ajax request by event triggering of a DOM object:
// By clicking on this link we will
// send an ajax request.
var $link = $('#link-element', context);

new Drupal.ajax($link.attr('id'), $link, {
  url: '/ajax/callback/path',
  event: 'click',
  // Pass some data to back-end side
  // if you need.
  submit: {
    some_data: 'some_data_value'
  }
});
Send ajax request immediately:
// If we want to send request immediately
// we can omit first two parameters.
var ajax = new Drupal.ajax(false, false, {
  url: '/ajax/callback/path'
});

// To send request call this function.
// You shouldn't think how to process
// response. Be sure that all commands
// will be processed correctly.
ajax.eventResponse(ajax, {});

Key notes:

No comments:

Post a Comment