I have an number of places where I paired a static div with content with an editable field to update that content on a drupal10 site. Using $(div).load(url), I’ve got it working on a single basis like so:
(function ($) {
$(document).ready(function () {
$('.container form .form-submit').click(function () {
});
$(document).ajaxComplete(function (event, xhr, settings) {
if (typeof settings !== 'undefined' && settings.extraData && settings.extraData._drupal_ajax) {
$('.targetdiv').load(location.href + " .targetdiv > *");
}
}
);
});
})(jQuery);
However, I have pages where I have multiple instances, and I’m struggling to get a variable to trigger after the .ajaxComplete. I’ve also tried variations of $(this), but I believe the ajax process breaks the focus so it doesn’t work. I need this to work so only the refreshdiv in the set associated with the click reloads.
I’ve got this far:
(function($){
$(document).ready(function() {
var targetID = $('.container').data('id');
$(document).on('click', '.editfield' + targetID + ' form .form-submit', function(){
});
// Listening for AJAX completion after button click
$(document).ajaxComplete(function (event, xhr, settings) {
console.log('ajax complete');
// Check if the AJAX request is from Drupal
if (typeof settings !== 'undefined' && settings.extraData && settings.extraData._drupal_ajax) {
$(".container .refreshdiv").addClass(targetID);
$('.targetID').load(location.href + " .targetID > *");
}
});
});
})(jQuery);
But in this second case, the variable targetID doesn’t carry through the ajax process. I’ve also tried placing the variable after .ajaxComplete, but that comes up blank too.
I expect I need to pass the variable through the .ajaxComplete function somehow. What am I missing?
2
Answers
I see the problem you are facing is scoping issue with the targetID variable inside the ajaxComplete function.
This code temporarily add the element’s class name with the value of the
targetID
variableThis code takes the html from its own url and puts it in an element with the class name ‘targetID’, not the value of the variable
targetID
You should change the code to:
Note: this code temporarily adds the class to the element, when it loads the data from the url I’m not sure if this class is available from the data result