0

I'm trying to pass data from ajax into the controller to update user location but the getData variable return nil. I'm not sure if that is the best way but I found many solutions that recommend using ajax.

Thanks in advance

//order_controller
def new
@order = Order.new
@cart = @current_cart
end

def create
#  raise 'ss'
getData = params[:data_value]
@location = Geocoder.search(getData)[0]
# console
current_user.latitude = @location.latitude
current_user.longitude = @location.longitude
current_user.address = @location.address
current_user.save

order = current_user.orders.new(status: "pending")
order.item_ids = @current_cart.item_ids
order.save
@current_cart.destroy

redirect_to root_path
end


//new.html.erb
$("#buy").on('click', function(){
//  debugger;
$.ajax({
url : "/orders/",
type : "post",
data : { data_value: 'Paris' },
success: function(post){ alert('WORK') },
error: function(post){ alert('ERROR') }
});
})
<%= button_to "buy" ,  orders_path(@order) , { action: "post", id: 
"buy" }  %>


//routes.rb
post "/orders/:id", to: "orders#create"
resources :orders 
root "sellers#index" 
Thekra
  • 1
  • 3
  • Welcome to stackoverflow. You are much more likely to get meaningful answers in response if you properly indent your example code. – anothermh Jan 06 '19 at 02:48
  • show us the `post` request logs – Moustafa Sallam Jan 06 '19 at 05:19
  • @MoustafaSallam Thanks for writing. I noticed the problem. When I use Geocoder.search() it's return nil.But It works if I directly save the getData variable into current_user.address without use Geocoder.search(). Did you know why Geocoder.search() keeps return nil – Thekra Jan 06 '19 at 17:24
  • @MoustafaSallam It works, I just add if condition @location.present?. – Thekra Jan 06 '19 at 18:14

1 Answers1

0

You miss submitting the authenticity_token when you send the post ajax request

All post requests requires passing the authenticity_token as one of the post request parameters.


Read more about authenticity_token here

Understanding the Rails Authenticity Token

Moustafa Sallam
  • 1,050
  • 1
  • 9
  • 17