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

Ruby

AJAX not loading without page refresh in Rails app

I added an AJAX script to my Rails app so that my form would automatically add a car object to the car feed. Behind the scenes the car is posting to the feed like it should. However, nothing happens on the webpage until I refresh and then the new car pops up. How can I make this happen without a page refresh?

The AJAX script: create.js.rb

$('#car_feed').replace("<%= escape_javascript(render 'shared/feed') %>");
$('#new_car').replace("<%= escape_javascript(render 'shared/car_form') %>");
$('#car_errors').html("<%= escape_javascript(render 'shared/error_messages', object: @car) %>");

I added remote:true to form_for

<%= form_for(@car, html: {multipart: true, remote: true}) do |f| %>

Everything looks good in the rails logs:

Started POST "/login" for 128.252.110.217 at 2015-02-27 01:16:38 +0000
Processing by SessionsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"gFDS0iSBZl38m/LMPXulLCxvNgsjMQWMA3P/K+VEVzzTvQfTShKud3UaCRRlz6jL4JFtnwFiA6jukBfxZ7WpIw==", "session"=>{"email"=>"andrew@example.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log in"}
  User Load (1.0ms)  SELECT  "users".* FROM "users" WHERE "users"."email" = ? LIMIT 1  [["email", "andrew@example.com"]]
   (0.2ms)  begin transaction
   (0.1ms)  commit transaction
Redirected to http://rails-tutorial-ajhausdorf.c9.io/
Completed 302 Found in 129ms (ActiveRecord: 1.2ms)

2 Answers

Javier Perez
Javier Perez
3,337 Points

Hi Andrew,

Try to use .html() instead of replace, see if that works. Your create.js.erb should look like this:

$('#car_feed').html("<%= escape_javascript(render 'shared/feed') %>");

$('#new_car').html("<%= escape_javascript(render 'shared/car_form') %>");

$('#car_errors').html("<%= escape_javascript(render 'shared/error_messages', object: @car) %>");

I hope that works, let me know.

I believe you can also use .replaceWith()

Brandon Barrette
Brandon Barrette
20,485 Points

I second Javier Perez. I would first put something simple like

$('#car_feed').html("IS THIS WORKING?????");

To trouble shoot. If that works, then we know it's not the javascript. Also, what does your controller look like? You need to respond_to js in the controller for remote: true to work properly.