Search code examples
ruby-on-railsajaxrespond-to

How to respond to ajax call in Rails


I know there are many questions about that already on stackoverflow but none of them has been useful for me. Here is my ajax code:

function update_schedule($task){
  var taskId = $task.data("taskId"),
    startHour, endHour,
    userId = $('#users').val();
  if( !$task.hasClass('daily-task')){ 
    startHour = getStartHour($task),
    endHour = startHour + (+$task.data('time'));
  }
  console.log(startHour, endHour)

   $.ajax({
          url: '/heimdall/update_scheduled_task',
          method: 'POST',
          data: { "task_id": taskId, "start_hour": startHour, "end_hour": endHour, "user_id": userId },
          success: function (){
            console.log("SUCESS!!", data['head'])
          },
          error: function () {
              console.log("FAILURE");
          },
          async: true
    }); 
}

The controller code:

def update_scheduled_task
    scheduled_task = ScheduledTask.find_or_create_by(task_id: params[:task_id])
    scheduled_task.update_attributes(start_hour: params[:start_hour], end_hour: params[:end_hour], task_id: params[:task_id], user_id: params[:user_id])

  end

I want to return the id of found or created task. I don't know how to send/receive this information. I've read about respond to but still I don't know how to use it in this case.


Solution

  • You may do render json: ... to return the required info to ajax in JSON format:

    def update_scheduled_task
      scheduled_task = ScheduledTask.find_or_create_by(task_id: params[:task_id])
      scheduled_task.update_attributes(start_hour: params[:start_hour], end_hour: params[:end_hour], task_id: params[:task_id], user_id: params[:user_id])
    
      render json: {scheduled_task_id: scheduled_task.id}
    end
    

    And in the ajax function's success, use it like:

    success: function (data){
      var data = JSON.parse(data);
    
      console.log(data["scheduled_task_id"]);
    },