last day (15 days later) » 

7:42 PM
0
A: How to use AJAX with checkboxes to CREATE & DESTROY?

Ryan KNot too difficult. In your habits form: <label id="<%= @habit.id %>" class="habit-id"> Missed: </label> <% @habit.levels.each_with_index do |level, index| %> <p> <label id="<%= level.id %>" class="level-id"> Level <%= index + 1 %>: </label> <%= check_box_tag nil, true, level.mi...

 
Thank you so much Ryan for this awesome answer! I added your code. And got a long error. I wasn't sure what Javascript file I should add it to: application.js? days_missed.coffee? habits.coffee? I generated a new one days_missed.js? I tried all but I got the same error:
 
Sorry. It has nothing to do with the javascript. Updated the form code. Basically the checked attribute needed to be inside the brackets. Also updated the javascript code (added document ready)
 
I can't get this to work Ryan :/ I put it in habit.js too. When I check the box and then go back to the page the checkbox is gone. This also happens when I click submit. The checkbox disappears, in other words it's not saving. I had this problem before and I thought AJAX could fix the issue.
 
What are :missed_one, :missed_two, and :missed_three? Because you aren't saving/updating them. You are only relying on level.missed_days to determine if they are checked or not. So maybe switch them to check_box_tags instead. Are they needed in the model?
Changed the check_boxs to check_box_tags. This should decouple the check boxes from the model, until you click on it and the ajax fires.
 
Thanks so much Ryan. I haven't responded because I was trying to figure out why the checkmarks aren't saving. With your code updated they still aren't saving, after-all they weren't saving before we introduced your awesome code. I think they are needed in the model. Each check should add 1 more day to a level before that level can be considered completed.
 
7:42 PM
Yeah, it seems like the big thing is the relationship between :days_missed and the :missed_x fields. By the way, in the line level.missed_days = level.missed_days + 1, you are sure that level.missed_days is initialized to 0 (or at least some number)? Because if not, then the ajax request would return with an error.
 
Yea t.integer "missed_days", default: 0 is in the schema for habits.rb. Do you have any ideas on how we can create that relationship between :days_missed and :missed_x fields? Someone directed me to attr_accessor and I thought that would have been enough. The purpose is so that when a user checks :missed_three on each level the level would restart. I haven't figured out how to add that yet. Maybe that's the problem :/
 
That's probably not the best idea. Because if someone selected :missed_three without selecting the other two, then the level would reset when it shouldn't. It should reset when level.missed_days >= 3. Btw, does a person WANT to miss days or is that bad? Haven't really figured that out yet.
 
haha missing a day is a bad thing. Okay I removed the :missed_x field lines. Now if we are just focusing on saving/updating (I'll leave figuring out level.missed_days >= 3 for another question) what do you think I should do? Should I also make this a new question or is this something that AJAX is suppose to resolve? Can I provide you with more code Ryan? Thanks again!
 
So you have a submit button? Where does that form go to? And when the check-boxes "disappear", are they not on the page at all or are they just hidden? Can you see them when you inspect the page?
 
Hey you there?
 
 
3 hours later…
10:16 PM
Hola?
The form goes to @habit
And the checkboxes are not there
i thought it might be easier to converse here
 
yeah definatly
so none of the checkboxes are there? at all?
 
not when I reload the page
Isnt that the point of the AJAX right? When you click the box it should stay unless you manually unclick it?
 
the point of ajax is to not need a page refresh to update data to/from the server
so in your case yeah
btw, are the checkboxes the only inputs in your form?
 
yea that's what i thought thanks :)
<%= javascript_include_tag "habit.js" %>

<%= simple_form_for(@habit) do |f| %>
<%= f.error_notification %>

<form>
<div class="committed">
<span class="label label-primary">Committed to:</span>
<%= f.collection_check_boxes :committed, Date::DAYNAMES, :downcase, :to_s %>
</div>

<div class="committed">
<span class="label label-primary">Started:</span>
<%= f.date_select :date_started, :order => [:month, :day, :year], class: 'date-select' %>
</div>

</br>

<p>
<label>AFTER I</label>
<%= f.text_field :trigger, class: 'form-control', placeholder: 'Enter Trigger' %></p>
long answer
short answer: no
 
so the rest of the form works correctly, just the checkboxes dont
 
10:28 PM
yea exactly
ive been trying to figure this out forever!
 
do the labels between the checkboxes work?
 
Just a visual
 
nice
 
so after the ajax or refresh, everything below missed is gone?
or JUST the checkboxes
 
10:31 PM
Just the checks within the checkboxes
 
oh
ah
 
sorry if i wasnt clear
 
i thought the checkboxes dissapeared
 
ohhhh lol no they stay :)
 
so its, like you said, missed_days isn't updating
 
10:35 PM
Yea how do we fix that? I removed the :missed_x field lines
 
try this, in your create/destroy methods, replace

level.missed_days = level.missed_days - 1
level.save

with

level.update!(missed_days: (level.missed_days + 1))
with the correct +/- that is
 
Damn that didn't work
 
did it return an error?
 
checkbox check just disappeared again
 
can you check your rails console for the POST request and see if you see an error there?
*rails logs
 
10:41 PM
i dont see an error
Anthony-Gallis-MacBook-Pro:~ galli01anthony$ rails logs
Usage:
rails new APP_PATH [options]

Options:
-r, [--ruby=PATH] # Path to the Ruby binary of your choice
# Default: /Users/galli01anthony/.rvm/rubies/ruby-2.1.3/bin/ruby
-m, [--template=TEMPLATE] # Path to some application template (can be a filesystem path or URL)
[--skip-gemfile], [--no-skip-gemfile] # Don't create a Gemfile
-B, [--skip-bundle], [--no-skip-bundle] # Don't run bundle install
 
hmmmm
no im sorry
dont you have a terminal where you have your rails server running?
 
yea
ohh sorry
 
check the output there....you might have to scroll up a bit to find the POST request if you refreshed the page
 
np
 
10:43 PM
i get this now
Anthony-Gallis-MacBook-Pro:pecoce galli01anthony$ rails logs
Error: Command 'logs' not recognized
 
rails logs is not a command...i mistyped and was correct what i was saying
 
rails c
 
when you type "rails s" or "rails server" into a terminal, there is a bunch of output when you go to a new webpage
 
yes yes
no error
there
 
can you copy paste the last POST request you see there?
 
10:47 PM
This came up when I hit refresh and then resubmitted:
Started GET "/assets/activities-2758d8b2279c1b016f19e512fd879882.css?body=1" for 127.0.0.1 at 2015-04-18 18:47:12 -0400


Started GET "/assets/account_activations-069e88c06b889877799890854d7f4c40.css?body=1" for 127.0.0.1 at 2015-04-18 18:47:12 -0400


Started GET "/assets/bootstrap_and_customization-c6ee8535e154be8ed443d4152d6b7f9b.css?body=1" for 127.0.0.1 at 2015-04-18 18:47:12 -0400


Started GET "/assets/comments-069e88c06b889877799890854d7f4c40.css?body=1" for 127.0.0.1 at 2015-04-18 18:47:12 -0400
 
so you dont see anything before that that says "Started POST" or anything like that? Because then that means the ajax isn't working
where do you have the javascript code?
 
Started GET "/habits/1" for 127.0.0.1 at 2015-04-18 18:49:08 -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]]
ActsAsTaggableOn::Tag Load (0.2ms) SELECT "tags".* FROM "tags" WHERE (LOWER(name) = LOWER('ingrain'))
Habit Load (0.1ms) SELECT "habits".* FROM "habits" WHERE "habits"."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 "tagg
in habit.js
 
ok
 
create_table "habits", force: true do |t|
t.text "committed"
t.integer "missed_days", default: 0
t.datetime "date_started"
t.string "trigger"
t.string "target"
t.string "reward"
t.boolean "private_submit"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "order"
end
create_table "levels", force: true do |t|
t.integer "habit_id"
t.integer "missed_days", default: 0
t.integer "current_level"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
 
when you click on a checkbox, do you see any network activity in your browser debugger/inspector?
have you used that before?
 
10:53 PM
just chrome inspect element
 
ok
 
javascript console?
 
go to "network" and check or uncheck a checkbox and see if anything pops up
a checkbox in your webpage that is
 
where's network?
 
when you click "inspect element", it should be at the top bar of what pops up at the bottom of chrome
 
10:57 PM
got it
nothing pops up
 
ok so then that means the ajax isn't firing
 
but if i go back to page
nvm lol
yea if i click on form again
i get
.habit-08a619454e7755fcb1794a64fa3a1f60.
habit-08a619454e7755fcb1794a64fa3a1f60.
habit-08a619454e7755fcb1794a64fa3a1f60.js?body=1
and it shows the code in the preview
 
hmmm
 
$(document).ready(function()
{
$(".habit-check").change(function()
{
habit = $(this).closest(".habit-id").attr("id");
level = $(this).closest(".level-id").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"
});
}
}
}
;
in new
New Habit

Create an actionable, specific, tiny, good habit
you pledge to master. The Structure: After X (Trigger),
I will Y (Habit), then I will Reward myself with Z.

Committed to: SundayMondayTuesdayWednesdayThursdayFridaySaturday
Started:

AFTER I

I WILL

UNTIL

SO I MAY

Placement:

Public
Private
Delete



Missed:
 
ok, try and comment out the if/else statement and second ajax request...maybe something wrong with that
 
11:05 PM
in new it isnt listing out checkboxes for missed but it is showing them for committed
idk if thats any thing
 
dont think so
 
yea ur right
did as u said
made no difference unfortuantely
$(document).ready(function()
{
$(".habit-check").change(function()
{
habit = $(this).closest(".habit-id").attr("id");
level = $(this).closest(".level-id").attr("id");
}
}
that what u wanted right?
 
no
keep the first ajax
just without the if/else
 
$(document).ready(function()
{
$(".habit-check").change(function()
{
habit = $(this).closest(".habit-id").attr("id");
level = $(this).closest(".level-id").attr("id");
$.ajax(
{
url: "/habits/" + habit + "/levels/" + level + "/days_missed",
method: "POST"
});
}
}
}
 
yes
btw, the checkboxes do have the "habit-check" class, right?
 
11:08 PM
didnt work :/
and yes sir
<label id="<%= @habit.id %>" class="habit-id"> Missed: </label>
<% @habit.levels.each_with_index do |level, index| %>
<p>
<label id="<%= level.id %>" class="level-id"> Level <%= index + 1 %>: </label>
<%= 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 %>
 
i mean in the html that is displayed
just want to make sure that it isn't being passed up
 
yea it does
<input type="checkbox" id="" value="true" class="habit-check">
 
cool
in your javascript, put

alert("working");

after the

$(".habit-check").change(function()
{
and then click on a checkbox
 
i did but nothing
 
try it before the change function but after the document ready line
btw, you are refreshing after you update your code, right?
 
11:16 PM
yea but sometimes going to root route and then coming back
idk if that makes a difference
 
not really just as long as you save your code and then refresh
 
$(document).ready(function()
{
alert("working");
$(".habit-check").change(function()
{
habit = $(this).closest(".habit-id").attr("id");
level = $(this).closest(".level-id").attr("id");
$.ajax(
{
url: "/habits/" + habit + "/levels/" + level + "/days_missed",
method: "POST"
});
}
}
}
 
yep
 
yea not seeing anything
 
$(document).ready(function()
{
alert("working");
}
try that
$(document).ready(function()
{
alert("working");
});
sorry
 
11:21 PM
Okay
when i check it
reload
i am prompted by
a working message
 
ok
 
but the checkmark disappears
 
i know
 
i assume u knew that :)
i was writing that
as u said it lol
 
i realize what my bug was
go back to the original code, and put ); and the very end after the last }
AND the second to last }
 
11:23 PM
$(document).ready(function()
{
$(".habit-check").change(function()
{
habit = $(this).closest(".habit-id").attr("id");
level = $(this).closest(".level-id").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"
});
}
});
});
 
i'm used to coffeescript so i forgot to put the closing parenthesis
yes
 
haha awesome. I saw some movement in the network but the checkmarks still disappear
 
does i have a post request?
*it
 
Started POST "/habits/undefined/levels/undefined/days_missed" for 127.0.0.1 at 2015-04-18 19:25:12 -0400
Processing by DaysMissedController#create as */*
Parameters: {"habit_id"=>"undefined", "level_id"=>"undefined"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
ActsAsTaggableOn::Tag Load (0.2ms) SELECT "tags".* FROM "tags" WHERE (LOWER(name) = LOWER('ingrain'))
Habit Load (0.2ms) SELECT "habits".* FROM "habits" WHERE "habits"."id" = ? LIMIT 1 [["id", 0]]
 
ah ok
so the habits and levels variables in javascript arent working
 
11:26 PM
yea u think maybe going back to original code in days_missed_controller?
 
no thats not it
its in the javascript code
 
ohhh okay
 
can you copy/past the <label>s that have "habit-id" and "level-id" classes
from the rendered html
 
<label id="1" class="level-id"> Level 1: </label>
<label id="2" class="level-id"> Level 2: </label>
<label id="3" class="level-id"> Level 3: </label>
<label id="4" class="level-id"> Level 4: </label>
<label id="5" class="level-id"> Level 5: </label>
Within each of those there are three lines of <input type="checkbox" id="" value="true" class="habit-check">
 
cool
now what about the label that has "habit-id" class?
 
11:32 PM
<label id="1" class="habit-id"> Missed: </label>
 
ok, so that works, but i found a bug in my code:
change
level = $(this).closest(".level-id").attr("id");
to
level = $(this).siblings(".level-id").first().attr("id");
 
okay n leave habit = $(this).closest(".habit-id").attr("id");?
 
yeah
 
how u doing?
 
watching some baseball
after watching some hockey so pretty good
did that work, btw?
 
11:41 PM
thats good. Tampa Bay is my favorite football team. N no lol
 
same here
 
yea i saw u lived there
i always thought about living there
this is what i got
$(document).ready(function()
{
$(".habit-check").change(function()
{
habit = $(this).closest(".habit-id").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"
});
}
});
});
 
yeah that looks good
 
still get
ActiveRecord::RecordNotFound (Couldn't find Habit with 'id'=undefined):
app/controllers/days_missed_controller.rb:5:in `create'


Rendered /Users/galli01anthony/.rvm/gems/ruby-2.1.3/gems/actionpack-4.2.0.rc3/lib/action_dispatch/middleware/templates/rescues/_source.erb (5.2ms)
Rendered /Users/galli01anthony/.rvm/gems/ruby-2.1.3/gems/actionpack-4.2.0.rc3/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (1.0ms)
Rendered /Users/galli01anthony/.rvm/gems/ruby-2.1.3/gems/actionpack-4.2.0.rc3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb (1.2ms)
 
ok for now, hardcode
habit = 1;
 
11:45 PM
how do i do that?
 
just remove $(this).closest(".habit-id").attr("id");
and put 1;
 
okay
one sec
 
ooooooh...i see
that label isn't a parent............
hold on
ok so change $(this).closest(".habit-id").attr("id");
to
$(this).parent().siblings(".habit-id").first().attr("id");
 
YES progress
but
dun dun dun
when i click once
nothing
when i click twice
refresh
then two checkmarks are shown
 
so when you click a checkbox, it doesn't actually stay checked?
 
11:56 PM
in other words
i check first box
Started POST "/habits/3/levels/11/days_missed" for 127.0.0.1 at 2015-04-18 19:56:23 -0400
Processing by DaysMissedController#create as */*
Parameters: {"habit_id"=>"3", "level_id"=>"11"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
ActsAsTaggableOn::Tag Load (0.3ms) SELECT "tags".* FROM "tags" WHERE (LOWER(name) = LOWER('ingrain'))
Habit Load (0.2ms) SELECT "habits".* FROM "habits" WHERE "habits"."id" = ? LIMIT 1 [["id", 3]]
Level Load (0.2ms) SELECT "levels".* FROM "levels" WHERE "levels"."habit_id" = ? AND "levels"."id" = ? LIMIT 1 [
refresh
checkmark disappears
Started GET "/assets/activities-2758d8b2279c1b016f19e512fd879882.css?body=1" for 127.0.0.1 at 2015-04-18 19:57:02 -0400


Started GET "/assets/attributes-40861c913294a704e4e836d49344c034.css?body=1" for 127.0.0.1 at 2015-04-18 19:57:02 -0400


Started GET "/assets/bootstrap_and_customization-c6ee8535e154be8ed443d4152d6b7f9b.css?body=1" for 127.0.0.1 at 2015-04-18 19:57:02 -0400


Started GET "/assets/pages-069e88c06b889877799890854d7f4c40.css?body=1" for 127.0.0.1 at 2015-04-18 19:57:02 -0400

check first box again
Started POST "/habits/3/levels/11/days_missed" for 127.0.0.1 at 2015-04-18 19:57:46 -0400
Processing by DaysMissedController#create as */*
Parameters: {"habit_id"=>"3", "level_id"=>"11"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
ActsAsTaggableOn::Tag Load (0.2ms) SELECT "tags".* FROM "tags" WHERE (LOWER(name) = LOWER('ingrain'))
Habit Load (0.1ms) SELECT "habits".* FROM "habits" WHERE "habits"."id" = ? LIMIT 1 [["id", 3]]
Level Load (0.1ms) SELECT "levels".* FROM "levels" WHERE "levels"."habit_id" = ? AND "levels"."id" = ? LIMIT 1 [
two checkmarks appear now
Started GET "/habits/3" for 127.0.0.1 at 2015-04-18 19:57:59 -0400
Processing by HabitsController#show as HTML
Parameters: {"id"=>"3"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
ActsAsTaggableOn::Tag Load (0.2ms) SELECT "tags".* FROM "tags" WHERE (LOWER(name) = LOWER('ingrain'))
Habit Load (0.1ms) SELECT "habits".* FROM "habits" WHERE "habits"."id" = ? LIMIT 1 [["id", 3]]
ActsAsTaggableOn::Tag Load (0.2ms) SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = ? AND "tagg
upon refreshing that is
 
hmmm i see
 
maybe its bc i switched back out ur controller code?
let me put that back in
 
sure lets see
 

  last day (15 days later) »