0

I'm having trouble with a index.js.erb which I've create but isn't execuing. I have the following in my controller:

def index
    @images = Image.order('id desc')

    respond_to do |format|
      format.js
      format.html
    end
end

And the following in my index.js.erb:

alert("it works")

If this helps as well I have the following in my coffee script file for this project:

ImagePoller =
poll: ->
    setTimeout @request, 5000

request: ->
    $.get($('#images').data('url'))

jQuery ->
if $('#images').length > 0
    ImagePoller.poll()

I can tell the js.erb file isn't load because I'm not seeing the alert? Any ideas?

6
  • Are you requesting with proper format at the end like /images.js? If you want Rails to render your 'index.js.erb', your url have to request with .js format. Commented Mar 15, 2013 at 18:10
  • Also check your server logs and make sure the poll isn't making an HTML request as opposed to a JS request. Commented Mar 15, 2013 at 18:28
  • @HungryCoder how do I make sure my url makes the .js request form? Commented Mar 15, 2013 at 19:57
  • @varatis thanks for the reponse, where do I find the server logs? Commented Mar 15, 2013 at 19:58
  • Don't you have rails server running on your console? It's the stuff that's getting printing out constantly onto your console Commented Mar 15, 2013 at 20:28

1 Answer 1

2

For making the ajax request, you're retrieving the url from '#images' element. All you need to make sure your URL contains proper format.

You can simply append the .js with the URL in your code:

request: ->
    $.get($('#images').data('url')) + '.js'

However, better way of doing is using rails helper methods. For example:

haml:

#images{:'data-url' => url_for(:action => 'index', :format => 'js')}

ERB:

<div id="images" data-url="<%=url_for(:action => 'index', :format => 'js')%>"></div>

The later case will already include the '.js' in the URL. so you won't need to append '.js' at the end that I've shown at beginning.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.