简体   繁体   中英

Calling ajax:beforeSend and ajax:complete on any link_to where remote is true ruby on rails

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") %>

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");
    });
});

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM