Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

AJAX request not working until after hard refresh (Treebook)

I've just finished the using AJAX badge for adding a friend on Treebook. All the Ruby stuff is working fine, as is the AJAX, but only after a hard page refresh.

When I press the 'add friend' button, it doesn't acknowledge the javascript at all and the click takes me to a new page. After refreshing the profile page, the javascript/AJAX kicks in and the button works as expected.

The Javascript is below (it's the same as Jason uses in the video).

Is there a setting in rails / something I can do in javascript to ensure the script loads with the page?

$(document).ready(function() {
  $('#add-friendship').click(function(event) {
    event.preventDefault();
    var addFriendshipBtn = $(this);
    $.ajax({
      url: Routes.user_friendships_path({user_friendship: { friend_id: addFriendshipBtn.data('friendId') }}),
      dataType: 'json',
      type: 'POST',
      success: function(e) {
        addFriendshipBtn.hide();
        $('#friend-status').html("<a href='#' class='btn btn-success'>Friendship Requested</a>");
      }
    });
  });
});

2 Answers

You can wrap the whole thing in a

$(document).ready(function() {
});

but I'm guessing that won't fix it quite so easily.

ah, sorry - doc ready is already there, I've forgotten to put it into the code snippet. Thanks!

Chris Malcolm
Chris Malcolm
2,909 Points

did you do //= require js-routes as well at top of your application.js?