简体   繁体   中英

Data not inserted to database while using custom ajax request without form in rails

I'm trying to make ajax post request without using form and here is my view,

View

<div class="col-md-12">
    <input value="<%= session[:user_id]%>" id="user_id" hidden>
    <%= link_to "Add New", new_task_list_path, :remote => true, :class =>"btn btn-xs add-list" %>
</div>

Ajax

$(document).on('click','.add', function(){
  user_id = $('#user_id').val();
  var name = $('.new-list').val();
  var current = $(this);
  if(name){
    $.ajax({
      method: 'POST',
      url: action,
      dataType: 'JSON',
      data: { 
        task_list: {
          name: name, 
          user_id: user_id 
        }
      }
    }).success(function(e){
      $(current).parent().parent().parent().before(
        '<div class="col-md-12">'+
          '<a href="#" class="btn btn-xs list ">'+name+'</a>'+
        '</div>'
        );
      $(current).parent().parent().parent().remove();
      $('.add-list').show();
    });
  }else{
    alert('please add title');
  }
});

Controller

def create
    @task_list = TaskList.new(task_list_params)
end

private

def task_list_params
    params.require(:task_list).permit(:user_id, :name)
end 

Here, ajax post request is triggered while clicking the Add New button and parameters are passed to the controller and status code returned is 204 with success but no data inserted to the database table.

I'm using postgres for database. Please help me to identify what I'm doing wrong.

PS: I'm new to rails and forgive if this is stupid question and ask freely if you need more details.

I think this problem occured for CSRF token. You can fix this using bellow steps -

Step 1. Add CSRF token to your application layout file as a meta tag.

# app/views/layouts/application.html.erb
<head>
 ....
 <%- if protect_against_forgery? %>
   <meta name="authenticity-token" id="authenticity-token" content="<%= form_authenticity_token %>" />
 <% end %>
 ....
</head>

Step 2. Create a new JS file

# app/assets/javascripts/csrf_token.js
$(function(){
 // always pass csrf tokens on ajax calls
 $.ajaxSetup({
    headers: { 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') }
  });
});

Step 3. Add above js file to application.js and your application js file look likes

# app/assets/javascripts/application.js

//= require rails-ujs
//= require jquery
//= require turbolinks
//= require csrf_token.js

Now your ajax code should work, because before ajax above code set the Rails authenticity token.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM