4

I have some links with the class use-ajax. Everything works fine with default settings.

The problem is that at some point I need to change the href attribute of a link and make the ajax call to the new url, which is not working. The call is made to the initial url of that link.

I tried to reattach behaviours but this doesn't seem to work.

Any help would be appreciated.

Any ideas? Thanks

5

Drupal link based Ajax, correspond to a Drupal.ajax['#id'] element object and drupal works with them not with DOM Objects.

So you don't have to change the href attribute you need to change the URL where it's doing POST in the Drupal.ajax element, in this case do this:

// Confirm structure first executing on console 'Drupal.ajax['#id'].options.url'
var href = 'hook_url/ajax/parameter1/parameter2';

// And change the href POST parameter
Drupal.ajax['#id'].options.url = href;

And it's done!

2
  • This worked fine for me. Note that if you're working with a url containing 'nojs' you'll need to clean that up. Also, links don't usually have ids, so I had to add some.
    – John Fiala
    Apr 12 '13 at 21:22
  • You excellent man, this just solved all of my problems May 27 '15 at 8:41
3

Since nobody knows how to do it I think this might help:

var element_settings = {};
element_settings.url = $(this).attr('href');
element_settings.event = 'click';
element_settings.progress = {
  type: 'throbber',
  message: ''
};
var base = $(this).attr('id');
Drupal.ajax[base] = new Drupal.ajax( base, this, element_settings );

$(this).unbind(Drupal.ajax[base].event);

$(this).bind(Drupal.ajax[base].event, function (event) {
  return Drupal.ajax[base].eventResponse(this, event);
});
0

in case your link has no ID attribute, here is another solution:

var href = oldhref.replace('/watch/', '/unwatch/'); //your new url
var elem = $('.watchthis a'); // the link element 
elem.attr('href', href);
var n = Drupal.ajax.instances.length;
for (var i = 0; i < n; i++) {
  if (Drupal.ajax.instances[i].element == elem[0]) {
    Drupal.ajax.instances[i].options.url = href+'?_wrapper_format=drupal_ajax';
  }
}
1
  • Your talking Drupal8 ;)
    – rémy
    Aug 8 '19 at 20:50

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.