John Davidson

javascript - Changing modal content breaks AJAX events

0 comments
Message:


I use jquery-ujs for ajax requests (data-remote="true"). My problem is, that the first request is okay, and while the second is running, it breaks. Whenever I call in the events $('#modal').empty() or $('#modal').text('') or $('#modal').html(''), no more events are going to be called.


To be clear, here's the code:


$(document).on('ajax:beforeSend', function () {
console.log('beforeSend');
$('#modal').empty().modal('show');
});

$(document).on('ajax:send', function () {
console.log('send');
});

$(document).on('ajax:success', function (e, xhr) {
console.log('success');
$('#modal').html(xhr).drags({ handle: '.modal-header' }).modal('show');

if (typeof doWork === 'function') {
doWork();
}
});

$(document).on('ajax:complete', function () {
console.log('complete');
});

And the console output:



  • beforeSend

  • send

  • success

  • complete

  • beforeSend


If I move $('#modal').empty().modal('show'); to the send event, then it is going to be called, but the success method is never called anymore (neither error neither complete, nothing more).


This problem annoys me for more hours now... Thank you for your help.



My Answer:
One possible solution to this issue is to use a flag to determine whether the modal content has already been cleared. You can set a flag before clearing the modal content and then check this flag before clearing it again. Here's an example:

javascript
var modalCleared = false;

$(document).on('ajax:beforeSend', function () {
console.log('beforeSend');
if (!modalCleared) {
$('#modal').empty().modal('show');
modalCleared = true;
}
});

$(document).on('ajax:send', function () {
console.log('send');
});

$(document).on('ajax:success', function (e, xhr) {
console.log('success');
$('#modal').html(xhr).drags({ handle: '.modal-header' }).modal('show');

if (typeof doWork === 'function') {
doWork();
}
});

$(document).on('ajax:complete', function () {
console.log('complete');
modalCleared = false; // Reset the flag for the next request
});


By using the `modalCleared` flag, you can ensure that the modal content is only cleared once per request, preventing any issues with subsequent AJAX events.

Rate this post

3 of 5 based on 6714 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us