user2725109
user2725109

Reputation: 2386

auto ajax call in ruby on rails is not working

I'm trying to do this: after my homepage loads (home.html.erb), call ajax to update the value of a tag on the same page. Here is what I have in my home.html.erb

<script>
  $(document).ready(function() {
    $.ajax({
      type: 'GET',
      url: '<%= url_for(action: "home") %>'
    });
  });
</script>

and my home.js.erb

var id = 5;
$('#jquerylogo').html(id);

and my controller

def home
  respond_to do |format|
    format.html # home.html.erb
    format.js
  end
end

but ajax is not called and the code doesn't work. why? thanks.

Upvotes: 1

Views: 986

Answers (1)

trh
trh

Reputation: 7339

Sometimes ujs issues are tricksie.

I would start by adding a dataType to the ajax call to force the controller to respect it's type.

$(document).ready(function() {
  $.ajax({
    type: 'GET',
    dataType: 'script',
    url: '<%= url_for(action: "home") %>'
  });
});

Things to look for are:

  • Check the javascript console to see what (if any) errors you have
  • Check your log to see if the request is made/received/rendered as html

Upvotes: 4

Related Questions