0

I'm working on a webapp using Ruby on Rails as framework. For all the partial renders, we used link_to with remote true as explained in this answer. However, I would like to bind the all those links to something equivalent to ajax:beforeSend and ajax:complete in order to implement a loader anytime a page is called in jQuery. So far I tried the following but it is not working :

$('a').on('ajax:beforeSend', function() {
  alert("BEFORE");
});

$('a').bind('ajax:complete', function() {
  alert("AFTER");
});

So if you have any other ideas it would be really appreciated if you could let me know. Thanks in advance.

EDIT: Here's an example of how I have been using link_to :

<%= link_to({action: "show_card", controller: "pages", id: activ.id, method: :get, :remote => true}, class: "nav-link p-0") %>
Giulio Colleluori
  • 1,261
  • 2
  • 10
  • 16

3 Answers3

1

What is not working ajax or loader if your ajax is working then for loader it should be like this

<div id="mySpinner" style="displany:none;">
     <img src="loader.gif">
</div>

$(function () {
    $(document).ajaxStart(function() {
        //$("#mySpinner").show();
         alert("BEFORE");
    }).ajaxStop(function() {
        //$("#mySpinner").hide();
        alert("AFTER");
    });
});
fool-dev
  • 7,671
  • 9
  • 40
  • 54
0

How about to show loader on element onclick event and hide it on ajax:success?

$('a').on('click', function() {
  alert("BEFORE");
});

$('a').ob('ajax:success', function() {
  alert("AFTER");
});

Make sure to also cover ajax:error

You might also try to subscribe to ajax:send instead of ajax:beforeSend. Because ajax:beforeSend is a local event and can be subscribed to only within the Ajax request object as docs say

Martin
  • 4,042
  • 2
  • 19
  • 29
0

I found out what it was, when I render new staff partially, I need to rebind it to the event, and apparently even using

$( window ).load(function() {
  $('a').on('ajax:beforeSend', function() {
  alert("BEFORE");
});

$('a').bind('ajax:complete', function() {
  alert("AFTER");
});
});

In the application.js file did not work, so basically to bind it initially I had to put a script tag at the bottom of my page which binds everything once it already rendered everything. Furthermore, anytime I do any remote partial rendering, I also need to rebind everything in the .js.erb file, that way it actually works. I'm there has to be a better way because this seems an awful solution; it is however, a solution for now.

Giulio Colleluori
  • 1,261
  • 2
  • 10
  • 16