2

I'm trying to relocate table row into another <div> through checkbox and I hope to accomplish this using Ajax call. But things won't work for me. Nothing happens after I click, there is no simply response. What am I missing?

My Javascript code in application.js

$(document).on('ready page:load', function () {
    $('.check').on('change', function(){
    if ($(this).is(':checked')) {
    id = $(this).attr('data-id');
    user_id = $(this).attr('data-user-id');
    complete = true;
    path = '/users/' + user_id + '/tasks/' + id;
    var jqXHR = $.ajax({
                 method: 'put',
                 dataType: "application/json",
                 url: path,
                 data: { task: {complete: complete, id: id}  }
    });

    jqXHR.done(function(data){
         task = $(this).closest("tr");
         $('.complete-tasks').last().after(task);
    })
  };
})
})

view file _index.html

<h3>Tasks database</h3>

<table>

  <% @tasks.each do |task| %>
    <tr class='tasks' id="task_<%= task.id %>">

    #Some stuff

  <td>
    <input type="checkbox" class='check' data-id="<%= task.id %>" data-user-id="<%= current_user.id %>" data-complete="<%= task.complete %>" >
  </td>

    </tr>

  <% end %>

</table>

<h3>Completed</h3>

<div class="complete-tasks">
</div>

I'm referring to an update action in my tasks_controller.rb

 def update
    @task = Task.find(params[:id])

      respond_to do |format|
     if @task.update(task_params)
      format.json { head :no_content }
     else
      format.html { render action: 'edit' }
      format.json { head :no_content }
     end
   end
  end


 private

    def task_params
     params.require(:task).permit(:title, :due_date, :priority, :complete)
    end

end

rake routes enter image description here

Alex Nikolsky
  • 2,087
  • 6
  • 21
  • 36

1 Answers1

1

Do not use $(this) inside an ajax callback like done. In your case it will not refer to the checkbox anymore but rather the jqXhr object.

See this question for details: $(this) inside of AJAX success not working

Community
  • 1
  • 1
mccannf
  • 16,619
  • 3
  • 51
  • 63