4

In a Rails 6.1 application using @rails/ujs (no jquery), I'm trying to intercept when ajax requests are fired and when they are completed.

I have added the following to my application.js

document.addEventListener("turbolinks:load", () => {
  document.addEventListener("ajax:send", () => {
    console.log('SEND')
  })
  document.addEventListener("ajax:complete", () => {
    console.log('COMPLETE')
  })
})

I correctly get SEND when I fire them, but when they end I don't get the (expected) COMPLETE.

Am I missing something here?

Sig
  • 5,476
  • 10
  • 49
  • 89

1 Answers1

0

I have some personal ideas to investigate this kind of bug.

clue: the SEND worked properly as it was printed in the console (Make sure there is no error message in the console)
idea: open the Network tab and check if the request is pending. enter image description here

Because ajax:complete will fire no matter what result in the server responses, so we can use that to find the next step.

situationA: the request is pending.
nextStep: try to find out why the request stuck on the server-side

situationB: the request responses but the event still does not fire
nextStep: try to find if there are any scripts already listening to the rails-ujs events

  • ajax:success
  • ajax:error
  • ajax:complete

and call event.preventDefault() inside. You can also open the Source tab and check the checkboxes to add break points at some specific XHR-related events:

  • error
  • load
  • loadend

enter image description here https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#events

And try to find whether there is any errors there or call event.preventDefault()

I tested your code and it worked fine on my machine, so I just want to give you some ideas for reference.

kevinluo201
  • 1,444
  • 14
  • 18