6

I have a jquery script, that running ajax script every 2 second

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 trying to move this script in assets, and call him via javascript_include_tag - then it starts to work throughout the application, not only in the view where I call him.

how fix?

upd

I put this script in to app/assets/javascripts/foobar.js, and call him in view this

  = javascript_include_tag 'foobar'
wweare
  • 241
  • 1
  • 2
  • 9
  • Could you please let me know in which file you are putting this js code, if it is in application.js then remove from this and add to your model js.coffee file. – Gaurav Gupta Apr 28 '15 at 07:01
  • I think this question has exactly what you are looking for http://stackoverflow.com/questions/602147/javascript-file-per-view-in-rails – potatopeelings Apr 28 '15 at 07:44

1 Answers1

0

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

//= require_tree .

Which tells rails to include every file in this directory into application.js, which is by default called in the head of your page. This line in your foobar.js file:

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

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

To prevent this you have multiple options (see this post for some ideas) but what might be easiest is to look for an element in the DOM which is only on the pages where you want this to run, something like this:

  $(document).ready(function(){
    if( $("#element-id-only-on-foobar-pages").is(":visable") ) {
        getvalue();
        setInterval('getvalue()', 2000);
    }
  });
l85m
  • 808
  • 1
  • 10
  • 19