Sometimes this AJAX fires & sometimes it doesn\'t, let me explain.
habit.js
$(document).ready(function()
{
$(\".habit-check\")
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.
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!
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");
});
});