Remis07 Remis07 - 5 months ago 18
jQuery Question

500 (Internal Server Error) in AJAX function that works correctly

I have two buttons(#shownum1, #shownum2), that run a function (increment) when clicked. I can see that the values are correctly incremented in the database which means that it works, but in the console I see this:


GET http://localhost:3000/increment?id=1 500 (Internal Server Error)


function increment(){
$.ajax({
url: '/increment',
data: {'id': <%= @voiture.id %>}
});
}


$('#shownum').on('click',function (){
increment();
});
$('#shownum2').on('click',function (){
increment();
});


The increment root:

get '/increment' => 'voitures#increment'


and finally the function increment :

def increment
Voiture.increment_counter(:compteur, 1)
end


I'm quite sure it's all about the increment function.. i don't usually use AJAX. Thanks a lot !

Answer

Instead of GET method, you should use POST method, then modify you code like following one:

function increment(){
    $.ajax({
        url: '/increment',
        data: {'id': <%= @voiture.id %>},
        method: 'POST' // Add this line!
    });  
}

# routes.rb
post '/increment' => 'voitures#increment'  # change from get to post!

#voitures_controller.rb
def increment
  Voiture.find(params[:id]).increment(:compteur, 1) # fixed line
end
Comments