How to make this script to view in a separate file?

I have a jquery script that runs an ajax script every 2 seconds

javascript: function getvalue(){ $.ajax({ url: "http://localhost:3000/companies/#{@company.url}", type: "GET", dataType: "json", success: function (json) { $('.blabla').html(json.clicks); $('.tratata').html(json.shows); } }); } javascript: $(document).ready(function(){ getvalue(); setInterval('getvalue()', 2000); }); 

and when I try to move this script to assets and call it via javascript_include_tag - then it starts working in the whole application, and not just in the view in which I call it.

how to fix?

update

I put this script in app / assets / javascripts / foobar.js and call it in sight of this

  = javascript_include_tag 'foobar' 
+6
source share
1 answer

When rails generates app / assets / javascripts / application.js, it automatically includes this line:

 //= require_tree . 

Indicates that the rails should include every file in this directory in application.js, which is called by default in the header of your page. This line in the foobar.js file:

  $(document).ready(function(){ getvalue(); setInterval('getvalue()', 2000); }); 

tells javascript to run this code every time the DOM loads. This is why your code works on every page.

To prevent this, you have several options (see this post for some ideas), but what could be easiest is to look for an element in the DOM that is only on the pages where you want it to be executed, approximately So:

  $(document).ready(function(){ if( $("#element-id-only-on-foobar-pages").is(":visable") ) { getvalue(); setInterval('getvalue()', 2000); } }); 
0
source

Source: https://habr.com/ru/post/986103/


All Articles