-2

Sometimes this AJAX fires & sometimes it doesn't, let me explain.

habit.js

$(document).ready(function()
{
  $(".habit-check").change(function()
  {
    habit = $(this).parent().siblings(".habit-id").first().attr("id");
    level = $(this).siblings(".level-id").first().attr("id");
    if($(this).is(":checked"))
    {
       $.ajax(
       {
         url: "/habits/" + habit + "/levels/" + level + "/days_missed",
         method: "POST"
       });
    }
    else
    {
       $.ajax(
       {
         url: "/habits/" + habit + "/levels/" + level + "/days_missed/1",
         method: "DELETE"
       });
    }
  });
});

It only fires after I load the show page AND refresh it so that the terminal looks like this:

Started GET "/habits/1" for ::1 at 2015-06-20 23:55:42 -0400
Processing by HabitsController#show as HTML
  Parameters: {"id"=>"1"}
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
  Habit Load (0.1ms)  SELECT "habits".* FROM "habits" WHERE "habits"."user_id" = ?  [["user_id", 1]]
  ActsAsTaggableOn::Tag Load (0.2ms)  SELECT "tags".* FROM "tags" WHERE (LOWER(name) = LOWER('ingrain'))
  CACHE (0.0ms)  SELECT "habits".* FROM "habits" WHERE "habits"."user_id" = ?  [["user_id", 1]]
  Level Load (0.2ms)  SELECT "levels".* FROM "levels" WHERE "levels"."habit_id" = ?  [["habit_id", 1]]
  ActsAsTaggableOn::Tag Load (0.3ms)  SELECT  DISTINCT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."tagger_id" = ? AND "taggings"."tagger_type" = ?  ORDER BY taggings_count desc LIMIT 20  [["tagger_id", 1], ["tagger_type", "User"]]
   (0.1ms)  SELECT COUNT(*) FROM "habits" WHERE "habits"."user_id" = ?  [["user_id", 1]]
  Habit Load (0.1ms)  SELECT  "habits".* FROM "habits" WHERE "habits"."id" = ? LIMIT 1  [["id", 1]]
  CACHE (0.0ms)  SELECT  "habits".* FROM "habits" WHERE "habits"."id" = ? LIMIT 1  [["id", "1"]]
  Habit Load (0.1ms)  SELECT  "habits".* FROM "habits" WHERE "habits"."user_id" = ? AND "habits"."id" = ? LIMIT 1  [["user_id", 1], ["id", 1]]
  CACHE (0.0ms)  SELECT "levels".* FROM "levels" WHERE "levels"."habit_id" = ?  [["habit_id", 1]]
  ActsAsTaggableOn::Tag Load (0.2ms)  SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = ? AND "taggings"."taggable_type" = ? AND (taggings.context = 'tags') GROUP BY tags.id  [["taggable_id", 1], ["taggable_type", "Habit"]]
  Note Load (0.1ms)  SELECT "notes".* FROM "notes" WHERE "notes"."habit_id" = ?  ORDER BY notes_date  [["habit_id", 1]]
  Rendered notes/_notes.html.erb (2.0ms)
  Rendered notes/_form.html.erb (3.9ms)
  User Load (0.1ms)  SELECT "users".* FROM "users" INNER JOIN "habit_likes" ON "users"."id" = "habit_likes"."user_id" WHERE "habit_likes"."habit_id" = ?  [["habit_id", 1]]
  Comment Load (0.1ms)  SELECT "comments".* FROM "comments" WHERE "comments"."habit_id" = ?  [["habit_id", 1]]
  Rendered comments/_comments.html.erb (0.8ms)
  Rendered comments/_form.html.erb (1.0ms)
  Rendered habits/show.html.erb within layouts/application (24.0ms)
   (0.2ms)  SELECT COUNT(*) FROM "notifications" WHERE "notifications"."user_id" = ?  [["user_id", 1]]
  Rendered layouts/_header.html.erb (2.9ms)
   (0.1ms)  SELECT COUNT(*) FROM "habits" WHERE "habits"."user_id" = ? AND 1=0  [["user_id", 1]]
  Rendered habits/_today.html.erb (1.0ms)
  Goal Load (0.2ms)  SELECT  "goals".* FROM "goals" WHERE "goals"."user_id" = ? AND "goals"."accomplished" = 'f'  ORDER BY deadline LIMIT 3  [["user_id", 1]]
   (0.1ms)  SELECT COUNT(*) FROM "users" INNER JOIN "relationships" ON "users"."id" = "relationships"."followed_id" WHERE "relationships"."follower_id" = ?  [["follower_id", 1]]
   (0.1ms)  SELECT COUNT(*) FROM "goals" WHERE "goals"."user_id" = ? AND "goals"."accomplished" = 'f'  [["user_id", 1]]
   (0.1ms)  SELECT COUNT(*) FROM "quantifieds" WHERE "quantifieds"."user_id" = ?  [["user_id", 1]]
   (0.1ms)  SELECT COUNT(*) FROM "users" INNER JOIN "relationships" ON "users"."id" = "relationships"."follower_id" WHERE "relationships"."followed_id" = ?  [["followed_id", 1]]
   (0.1ms)  SELECT COUNT(*) FROM "goals" WHERE "goals"."user_id" = ? AND "goals"."accomplished" = 't'  [["user_id", 1]]
   (0.1ms)  SELECT COUNT(*) FROM "results" INNER JOIN "quantifieds" ON "results"."quantified_id" = "quantifieds"."id" WHERE "quantifieds"."user_id" = ? AND "results"."bad" = 'f'  [["user_id", 1]]
   (0.1ms)  SELECT COUNT(*) FROM "valuations" WHERE "valuations"."user_id" = ?  [["user_id", 1]]
  Rendered layouts/_count.html.erb (10.7ms)
  Rendered layouts/_tags.html.erb (0.1ms)
  Rendered layouts/_recommendations.html.erb (0.0ms)
  Quantified Load (0.1ms)  SELECT "quantifieds".* FROM "quantifieds" WHERE "quantifieds"."user_id" = ? AND "quantifieds"."categories" = ?  [["user_id", 1], ["categories", "Averaged"]]
  Quantified Load (0.1ms)  SELECT "quantifieds".* FROM "quantifieds" WHERE "quantifieds"."user_id" = ? AND "quantifieds"."categories" = ?  [["user_id", 1], ["categories", "Instance"]]
   (0.1ms)  SELECT COUNT(*) FROM "valuations" WHERE "valuations"."user_id" = ? AND (1 = 0)  [["user_id", 1]]
  Rendered layouts/_value.html.erb (0.8ms)
  Rendered layouts/_sidebar.html.erb (18.9ms)
Completed 200 OK in 324ms (Views: 307.4ms | ActiveRecord: 3.3ms)


Started GET "/assets/application-2b528cffd402884831208f505b651927.css?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/jquery-ea2706bc2d0586731b7c00ec2cd0a414.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/stylesheet-3e834b3a950daa6165191fa42b13a968.css?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/jquery_ujs-29277b946c1d3754af13672bfec0c660.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/bootstrap-d16805677947f8c7ce91cea7ae7f82b0.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/cocoon-07a2b3765fb91baf2df1cea98d97eed0.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/turbolinks-3a7cdb8630f3e86770867bd488a098e0.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/account_activations-8f6eecd1178ef85964369ec66d33c4f1.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/comments-8f6eecd1178ef85964369ec66d33c4f1.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/days_missed-8f6eecd1178ef85964369ec66d33c4f1.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/facebook-faaf7b74474e5a746a0c4a160e4705d2.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/habit-ff66f57b87d00b4469848f1af3f6910a.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/habits-8f6eecd1178ef85964369ec66d33c4f1.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/activities-8f6eecd1178ef85964369ec66d33c4f1.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/pages-8f6eecd1178ef85964369ec66d33c4f1.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/password_resets-8f6eecd1178ef85964369ec66d33c4f1.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/notes-8f6eecd1178ef85964369ec66d33c4f1.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/quantified-5cae96afee8ab50e506c00828f3042b3.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/goals-8f6eecd1178ef85964369ec66d33c4f1.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/quantifieds-8f6eecd1178ef85964369ec66d33c4f1.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/relationships-8f6eecd1178ef85964369ec66d33c4f1.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/sessions-8f6eecd1178ef85964369ec66d33c4f1.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/notifications-8f6eecd1178ef85964369ec66d33c4f1.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/tags-8f6eecd1178ef85964369ec66d33c4f1.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/users-8f6eecd1178ef85964369ec66d33c4f1.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/values-8f6eecd1178ef85964369ec66d33c4f1.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/application-6fd7d78d93af9f6901c08c3bc66303d0.js?body=1" for ::1 at 2015-06-20 23:55:42 -0400


Started GET "/assets/bootstrap/glyphicons-halflings-regular-195cb410b49d75c104a5bc6ad385ac77.woff" for ::1 at 2015-06-20 23:55:43 -0400

Just loading the show page once won't do the job because the checkmark doesn't fire the AJAX (Notice all the GET above & lack of GET below, I think it has something to do with turbolinks).

Started GET "/habits/1" for ::1 at 2015-06-21 00:09:02 -0400
Processing by HabitsController#show as HTML
  Parameters: {"id"=>"1"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
  Habit Load (0.1ms)  SELECT "habits".* FROM "habits" WHERE "habits"."user_id" = ?  [["user_id", 1]]
  ActsAsTaggableOn::Tag Load (0.2ms)  SELECT "tags".* FROM "tags" WHERE (LOWER(name) = LOWER('ingrain'))
  CACHE (0.0ms)  SELECT "habits".* FROM "habits" WHERE "habits"."user_id" = ?  [["user_id", 1]]
  Level Load (0.2ms)  SELECT "levels".* FROM "levels" WHERE "levels"."habit_id" = ?  [["habit_id", 1]]
  ActsAsTaggableOn::Tag Load (0.2ms)  SELECT  DISTINCT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."tagger_id" = ? AND "taggings"."tagger_type" = ?  ORDER BY taggings_count desc LIMIT 20  [["tagger_id", 1], ["tagger_type", "User"]]
   (0.1ms)  SELECT COUNT(*) FROM "habits" WHERE "habits"."user_id" = ?  [["user_id", 1]]
  Habit Load (0.1ms)  SELECT  "habits".* FROM "habits" WHERE "habits"."id" = ? LIMIT 1  [["id", 1]]
  CACHE (0.0ms)  SELECT  "habits".* FROM "habits" WHERE "habits"."id" = ? LIMIT 1  [["id", "1"]]
  Habit Load (0.1ms)  SELECT  "habits".* FROM "habits" WHERE "habits"."user_id" = ? AND "habits"."id" = ? LIMIT 1  [["user_id", 1], ["id", 1]]
  CACHE (0.0ms)  SELECT "levels".* FROM "levels" WHERE "levels"."habit_id" = ?  [["habit_id", 1]]
  ActsAsTaggableOn::Tag Load (0.1ms)  SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = ? AND "taggings"."taggable_type" = ? AND (taggings.context = 'tags') GROUP BY tags.id  [["taggable_id", 1], ["taggable_type", "Habit"]]
  Note Load (0.1ms)  SELECT "notes".* FROM "notes" WHERE "notes"."habit_id" = ?  ORDER BY notes_date  [["habit_id", 1]]
  Rendered notes/_notes.html.erb (1.1ms)
  Rendered notes/_form.html.erb (3.2ms)
  User Load (0.1ms)  SELECT "users".* FROM "users" INNER JOIN "habit_likes" ON "users"."id" = "habit_likes"."user_id" WHERE "habit_likes"."habit_id" = ?  [["habit_id", 1]]
  Comment Load (0.1ms)  SELECT "comments".* FROM "comments" WHERE "comments"."habit_id" = ?  [["habit_id", 1]]
  Rendered comments/_comments.html.erb (0.9ms)
  Rendered comments/_form.html.erb (1.1ms)
  Rendered habits/show.html.erb within layouts/application (21.4ms)
   (0.1ms)  SELECT COUNT(*) FROM "notifications" WHERE "notifications"."user_id" = ?  [["user_id", 1]]
  Rendered layouts/_header.html.erb (2.3ms)
   (0.1ms)  SELECT COUNT(*) FROM "habits" WHERE "habits"."user_id" = ? AND 1=0  [["user_id", 1]]
  Rendered habits/_today.html.erb (0.9ms)
  Goal Load (0.2ms)  SELECT  "goals".* FROM "goals" WHERE "goals"."user_id" = ? AND "goals"."accomplished" = 'f'  ORDER BY deadline LIMIT 3  [["user_id", 1]]
   (0.1ms)  SELECT COUNT(*) FROM "users" INNER JOIN "relationships" ON "users"."id" = "relationships"."followed_id" WHERE "relationships"."follower_id" = ?  [["follower_id", 1]]
   (0.1ms)  SELECT COUNT(*) FROM "goals" WHERE "goals"."user_id" = ? AND "goals"."accomplished" = 'f'  [["user_id", 1]]
   (0.1ms)  SELECT COUNT(*) FROM "quantifieds" WHERE "quantifieds"."user_id" = ?  [["user_id", 1]]
   (0.1ms)  SELECT COUNT(*) FROM "users" INNER JOIN "relationships" ON "users"."id" = "relationships"."follower_id" WHERE "relationships"."followed_id" = ?  [["followed_id", 1]]
   (0.1ms)  SELECT COUNT(*) FROM "goals" WHERE "goals"."user_id" = ? AND "goals"."accomplished" = 't'  [["user_id", 1]]
   (0.1ms)  SELECT COUNT(*) FROM "results" INNER JOIN "quantifieds" ON "results"."quantified_id" = "quantifieds"."id" WHERE "quantifieds"."user_id" = ? AND "results"."bad" = 'f'  [["user_id", 1]]
   (0.1ms)  SELECT COUNT(*) FROM "valuations" WHERE "valuations"."user_id" = ?  [["user_id", 1]]
  Rendered layouts/_count.html.erb (9.3ms)
  Rendered layouts/_tags.html.erb (0.0ms)
  Rendered layouts/_recommendations.html.erb (0.1ms)
  Quantified Load (0.1ms)  SELECT "quantifieds".* FROM "quantifieds" WHERE "quantifieds"."user_id" = ? AND "quantifieds"."categories" = ?  [["user_id", 1], ["categories", "Averaged"]]
  Quantified Load (0.1ms)  SELECT "quantifieds".* FROM "quantifieds" WHERE "quantifieds"."user_id" = ? AND "quantifieds"."categories" = ?  [["user_id", 1], ["categories", "Instance"]]
   (0.1ms)  SELECT COUNT(*) FROM "valuations" WHERE "valuations"."user_id" = ? AND (1 = 0)  [["user_id", 1]]
  Rendered layouts/_value.html.erb (0.8ms)
  Rendered layouts/_sidebar.html.erb (17.6ms)
Completed 200 OK in 318ms (Views: 301.9ms | ActiveRecord: 3.1ms)

This show page calls the AJAX

<div class="strikes">
  <% if @habit.current_level_strike %> 
    <div class="btn" id="red"> <label id="<%= @habit.id %>" class="habit-id">Strikes:</label>
  <% else %> 
    <div class="btn" id="gold"> <label id="<%= @habit.id %>" class="habit-id-two">Strikes:</label>
  <% end %>
    <% @habit.levels.each_with_index do |level, index| %>
      <% if @habit.current_level >= (index + 1) %>
        <p>
          <% if @habit.current_level_strike %> 
            <label id="<%= level.id %>" class="level-id">Level <%= index + 1 %>:</label> 
          <% else %> 
            <label id="<%= level.id %>" class="level-id-two">Level <%= index + 1 %>:</label> 
          <% end %>
          <%= check_box_tag nil, true, level.missed_days > 0, {class: "habit-check"} %>
          <%= check_box_tag nil, true, level.missed_days > 1, {class: "habit-check"} %>
          <%= check_box_tag nil, true, level.missed_days > 2, {class: "habit-check"} %>
       </p>
      <% end %>
    <% end %>
  </div>
</div>

This is what the AJAX fires to, days_missed_controller.rb.

class DaysMissedController < ApplicationController
  before_action :logged_in_user, only: [:create, :destroy]

  def create
    habit = Habit.find(params[:habit_id])
    habit.missed_days = habit.missed_days + 1
    @habit.save!
    level = habit.levels.find(params[:level_id])
    level.missed_days = level.missed_days + 1
    if level.missed_days == 3
      level.missed_days = 0
      level.days_lost += habit.calculate_days_lost + 1
    end
    level.save!
    head :ok # this returns an empty response with a 200 success status code
  end

  def destroy
    habit = Habit.find(params[:habit_id])
    habit.missed_days = habit.missed_days - 1
    habit.save!
    level = habit.levels.find(params[:level_id])
    level.missed_days = level.missed_days - 1
    level.save!
    head :ok # this returns an empty response with a 200 success status code
  end
end

Here's the gist of it. Sorry I'm new to AJAX and got help with this so my level of description maybe elementary. Please don't hesitate to ask for further clarification or code :-]


UPDATE

So in other words if a user loads the show page and then checks the checkboxes nothing is sent to the server; If the user loads the show page AND then refreshes it then checks the checkboxes this POST is made in the server:

Started POST "/habits/1/levels/1/days_missed" for 127.0.0.1 at 2015-06-22 02:15:21 -0400
Processing by DaysMissedController#create as */*
  Parameters: {"habit_id"=>"1", "level_id"=>"1"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
  Habit Load (0.2ms)  SELECT "habits".* FROM "habits" WHERE "habits"."user_id" = ?  [["user_id", 1]]
  ActsAsTaggableOn::Tag Load (0.3ms)  SELECT "tags".* FROM "tags" WHERE (LOWER(name) = LOWER('ingrain'))
  CACHE (0.0ms)  SELECT "habits".* FROM "habits" WHERE "habits"."user_id" = ?  [["user_id", 1]]
  Level Load (0.2ms)  SELECT "levels".* FROM "levels" WHERE "levels"."habit_id" = ?  [["habit_id", 1]]
  ActsAsTaggableOn::Tag Load (0.3ms)  SELECT  DISTINCT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."tagger_id" = ? AND "taggings"."tagger_type" = ?  ORDER BY taggings_count desc LIMIT 20  [["tagger_id", 1], ["tagger_type", "User"]]
   (0.1ms)  SELECT COUNT(*) FROM "habits" WHERE "habits"."user_id" = ?  [["user_id", 1]]
  Habit Load (0.1ms)  SELECT  "habits".* FROM "habits" WHERE "habits"."user_id" = ? AND "habits"."id" = ? LIMIT 1  [["user_id", 1], ["id", 1]]
  Habit Load (0.1ms)  SELECT  "habits".* FROM "habits" WHERE "habits"."id" = ? LIMIT 1  [["id", 1]]
   (0.1ms)  begin transaction
  CACHE (0.0ms)  SELECT "levels".* FROM "levels" WHERE "levels"."habit_id" = ?  [["habit_id", 1]]
  CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
  ActsAsTaggableOn::Tag Load (0.2ms)  SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = ? AND "taggings"."taggable_type" = ? AND (taggings.context = 'tags' AND taggings.tagger_id IS NULL)  [["taggable_id", 1], ["taggable_type", "Habit"]]
  CACHE (0.0ms)  SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = ? AND "taggings"."taggable_type" = ? AND (taggings.context = 'tags' AND taggings.tagger_id IS NULL)  [["taggable_id", 1], ["taggable_type", "Habit"]]
  ActsAsTaggableOn::Tag Load (0.1ms)  SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = ? AND "taggings"."taggable_type" = ? AND (taggings.context = 'tags' AND
                                    taggings.tagger_id = 1 AND
                                    taggings.tagger_type = 'User')  [["taggable_id", 1], ["taggable_type", "Habit"]]
   (0.1ms)  commit transaction
  Level Load (0.2ms)  SELECT  "levels".* FROM "levels" WHERE "levels"."habit_id" = ? AND "levels"."id" = ? LIMIT 1  [["habit_id", 1], ["id", 1]]
   (0.1ms)  begin transaction
  SQL (0.3ms)  UPDATE "levels" SET "missed_days" = ?, "updated_at" = ? WHERE "levels"."id" = ?  [["missed_days", 1], ["updated_at", "2015-06-22 06:15:21.959609"], ["id", 1]]
   (2.8ms)  commit transaction
Completed 200 OK in 40ms (ActiveRecord: 5.4ms)
AnthonyGalli.com
  • 2,796
  • 5
  • 31
  • 80
  • I suspect there's a good and worthwhile question in here somewhere, but it's too dense to sift through. Is it that your change event isn't being fired when you expect? If you bind to listen for change, it should not do anything until in fact there is a change. Simply having a checkbox with a value isn't enough. Also, is it possible that you're getting back a cached value? I would try setting `cache` to `false` in the `$.ajax()` call. – Greg Pettit Jun 21 '15 at 05:16
  • Thanks for the help @GregPettit! Sorry for the density. It's not the cache I don't think because when I added this it stopped all together the AJAX from firing upon a checkmark: `$.ajax( { cache: false url: "/habits/" + habit + "/levels/" + level + "/days_missed", method: "POST" }); }` – AnthonyGalli.com Jun 21 '15 at 05:23
  • 1
    Is it supposed to do something on pageload? – Greg Pettit Jun 22 '15 at 05:09
  • I made an update to the question @GregPettit. Hopefully that is a better elaboration :-] Please let me know. – AnthonyGalli.com Jun 22 '15 at 06:21
  • Still strikes me as a caching issue. After pageload, when asked to do so (ie on click) the browser goes to the cache, says "yup, did that, here are the results" and does not go to the server. But after refresh, the cache is cleared and the checkboxes work. On click, the browsers says, "I have no cache of that, let me go get what you want." Inside your Ajax methods, try adding something to the success and error handlers that print out the data returned. Won't take long to see if it's cached data being returned! – Greg Pettit Jun 22 '15 at 20:33
  • 1
    Try removing `//= require turbolinks` from `application.js` – fylooi Jun 23 '15 at 05:52
  • @fylooi I removed it and that made it work in development, but in production for some reason the checkmarks disappear upon refreshing the page. The checkmarks are suppose to remain just like it does in development. I don't get why it works for one and not the other. – AnthonyGalli.com Jun 23 '15 at 21:52

3 Answers3

2

This might be the problem with Turbolinks, could you try changing your javascript:

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

to look like:

$(document).on("ready page:load", function() {
  // ..
}

Please, let me know if it helped!

Good luck!

AnthonyGalli.com
  • 2,796
  • 5
  • 31
  • 80
Paweł Dawczak
  • 9,519
  • 2
  • 24
  • 37
  • So with "ready page:load" it seems to work perfectly in development, but when I look at it in production it has some funky behavior. For example upon checking then refreshing the page, the checkmark disappears, but the POST was made because a `missed_day` was added. Sometimes the checkmark stays. – AnthonyGalli.com Jun 23 '15 at 14:59
  • I discovered this answer: http://stackoverflow.com/questions/17881384/jquery-gets-loaded-only-on-page-refresh-in-rails-4-application. Do you think I should try this or is there another way to tinker with your answer? – AnthonyGalli.com Jun 23 '15 at 16:23
  • Unfortunately I'm away from computer at the moment so I can't do much testing, but the I've provided sample of code from book of DHH which worked in my projects, so personally I'd try around this. I'll get back to you as soon as I have opportunity to do any testing. – Paweł Dawczak Jun 23 '15 at 16:29
  • Maybe I had old version of turbolinks. Could you check what version do you have? Maybe it'll let me reproduce the problem – Paweł Dawczak Jun 23 '15 at 16:36
  • Could you give a shot `page:change` one more time? Just googled for usage, and [there](https://gist.github.com/abitdodgy/ff713f19aaed488a3628), or it might be useful to try [this](https://github.com/rails/turbolinks/issues/338#issuecomment-60689815) – Paweł Dawczak Jun 23 '15 at 16:52
  • Sure thing. I'm using 2.3 turbolinks – AnthonyGalli.com Jun 23 '15 at 16:53
  • I tried "page:change" & "ready page:change". The former stops the double rendering with POST in development, but it caused problems in production. – AnthonyGalli.com Jun 23 '15 at 17:02
  • I also tried your links. The first looks like your first suggestion and the latter stopped it from working all together. I had added `hit = -> ga('send', 'pageview') hit() $(document).on "page:load page:restore", hit` – AnthonyGalli.com Jun 23 '15 at 17:13
1

As per my comment, strikes me as a caching issue.

First thing to do is for the Ajax methods, set the cache to false. Then, to see if it works, log something in the success handlers. This will both show you that the Ajax has indeed fired, but will also report back what the results were:

// nested in your code as per your sample; just extracted out here

$.ajax({
     cache: false,
     url: "/habits/" + habit + "/levels/" + level + "/days_missed",
     method: "POST",
     success: function(data){
       console.log("result of Post is: ", data);
     }
   });

// ...

$.ajax({
     cache: false,
     url: "/habits/" + habit + "/levels/" + level + "/days_missed/1",
     method: "DELETE",
     success: function(data){
       console.log("result of Delete is: ", data);
     }
   });

The supplemental thing to do is open up your web development tools in your browser and inspect network activity. When the Ajax call is made, it should report back how long it took as well as what the source was. If it comes from the cache, it will say "cache" somewhere in there.

Greg Pettit
  • 10,749
  • 5
  • 53
  • 72
  • Thanks for the additional help! :] With your code and with my old if I click the checkbox and don't refresh then using the Chrome Javascript Console in Developer Tools it still has no affect, no mention of anything including "cache". I even used " Disable cache (while DevTools is open)". This is quite puzzling. – AnthonyGalli.com Jun 23 '15 at 00:05
  • And I didn't see any difference in how the POST looked. I looked for the phrase "result of Post is" Am I suppose to see that in the POST or with `rails c`? – AnthonyGalli.com Jun 23 '15 at 00:38
  • Anthony, that should be appearing in your browser's developer tools in the "console" pane. If you don't have that opened yet, you need to do so post (haha) haste! If it's not appearing at all, there are other issues we've missed... specifically either the event isn't bound or there's an error on the POST. – Greg Pettit Jun 23 '15 at 01:08
  • Yea Greg gave that another try, but still no show :/ I guess its got to be because the event isn't bound? I don't think its the error on the POST because as you can see with the question update there was no error message. – AnthonyGalli.com Jun 23 '15 at 05:28
1

Not so much of an answer yet, but too big for a comment. Let's find out if the ajax is actually being called. I put some alert boxes in as well as an ajax error catcher. Run it and see what behavior you get, please. It should help all of us understand what is really going on.

$(document).ready(function()
{
  $(document).on("click", ".habit-check", function()
  {
    alert(".habit-check change called");
    habit = $(this).parent().siblings(".habit-id").first().attr("id");
    level = $(this).siblings(".level-id").first().attr("id");
    if($(this).is(":checked"))
    {
       alert("calling POST " + "/habits/" + habit + "/levels/" + level + "/days_missed");
       $.ajax(
       {
         url: "/habits/" + habit + "/levels/" + level + "/days_missed",
         method: "POST"
       });
    }
    else
    {
       alert("calling DELETE " + "/habits/" + habit + "/levels/" + level + "/days_missed/1");
       $.ajax(
       {
         url: "/habits/" + habit + "/levels/" + level + "/days_missed/1",
         method: "DELETE"
       });
    }
  });
  $( document ).ajaxError(function( event, request, settings )
  {
    alert("ajax error received");
  });
});
Guy Schalnat
  • 1,697
  • 15
  • 26
  • Thanks Guy! When I click a checkbox with your code I get the alert message: ."habit-check change called". Then another alert: "calling POST /habits/6/levels/26/days_missed", but if it's a refreshed page and I click the checkbox nothing happens. – AnthonyGalli.com Jun 23 '15 at 14:34
  • Does all your HTML content get loaded at once (as a static or rendered page from a back-end technology like PHP or JSP)? If the DOM itself is being manipulated, perhaps you are losing elements after the bind, or trying to bind to elements that aren't on the page yet? – Greg Pettit Jun 23 '15 at 14:47
  • 1
    Yea @GregPettit I think it has something to do with turbolinks. They affect binding from my understanding. Trying to fix `$(document).on("page:change", function()` – AnthonyGalli.com Jun 23 '15 at 17:03
  • Or $(document).on("click", ".habit-check", function() instead of $(".habit-check").change(function() - see http://stackoverflow.com/questions/4471401/getting-value-of-html-checkbox-from-onclick-onchange-events – Guy Schalnat Jun 23 '15 at 17:20
  • @GuySchalnat your answer seems to work now too in development, but it's also not working right in production heroku. When I click the checkbox your alert messages come up and then the checkmark POSTS like it should, but then the checkmark disappears upon refreshing the page whereas it should stay visible. – AnthonyGalli.com Jun 23 '15 at 21:58
  • 1
    Interesting. I've been reading up on turbolinks, and most answers suggest page:change. My fix is something I learned while using .NET (which had a similar problem). Basically, instead of capturing the events on the element, I let them bubble up to the document, and use the selector at that time to determine if it is an event we are interested in or not. It is probably a tiny bit slower, but even on mobile, unnoticeable to the user. At this point, I'd suggest trying each answer separately and in combination, and seeing if any work. You may have two problems happening at once. – Guy Schalnat Jun 24 '15 at 02:05
  • Thanks @AnthonyGalli.com I'm glad you got it working. – Guy Schalnat Jun 26 '15 at 03:40
  • Thanks @GuySchalnat! I just deleted the link I provided there sorry. Here is the new one if you could take a look http://stackoverflow.com/questions/31064486/the-mystery-of-the-disappearing-checkmarks – AnthonyGalli.com Jun 26 '15 at 03:42