Reputation: 5343
I am trying to make a POST request to my rails using jquery.
my values for ajax call
$('input[type=submit]').unbind().bind('click', function() {
// extract category id from hidden field
var category = $("#category_id").val();
var category_id = category.split("=>").pop(-1);
category_id = category_id.replace("}","");
// extract question id from hidden field
var question = $("#question_id").val();
var question_id = question.split("=>").pop(-1);
question_id = question_id.replace("}","");
// init new array to pass choices
var checked = [];
$("input:checked").each(function() {
var whole_id = $(this).attr("id");
var id = whole_id.split("_").pop(-1);
checked.push(id);
});
var answers = JSON.stringify(checked);
console.log(checked);
retrieve(answers,category_id,question_id);
});
ajax call
function retrieve(answers,category,question) {
$.ajax({
cache: false,
type: "POST",
url: "/categories/" + category + "/questions/" + question + "/retrieve",
data: answers,
success: function(data) {
},
error: function(xhr) {
alert("The error code is: " + xhr.statusText);
}
});
};
routing
resources :categories do
get '/random_question', action: 'random_question', controller: 'categories', as: 'random_question'
resources :questions do
post '/retrieve', to: 'questions#retrieve'
resources :choices, only: [:index]
end
end
controller
def retrieve
@category = Category.find_by(params[:category_id])
respond_to do |format|
format.html { redirect_to category_questions_url, notice: 'success' }
format.json {
render json: {
message: "success"
}
}
end
end
i get a 404 error(not found) and the url is like this
http://localhost:3000/categories/%222%22/questions 404 (Not Found)
which is wrong.
also in network tab of chrome dev tools i get this
ActiveRecord::RecordNotFound in QuestionsController#index
Couldn't find Category with 'id'="2"
Upvotes: 0
Views: 88
Reputation: 5343
As user TomD originally suggested is that i get strings and i need to convert them to integers.
But the real problem was that the hidden input value attribute had :value=>1
instead of just 1
after doing the following on my hidden input fields everything worked like TomD said to do.
<%= hidden_field_tag :category_id,params[:category_id], value: params[:category_id] %>
<%= hidden_field_tag :question_id,params[:id], value: params[:id] %>
Upvotes: 1
Reputation: 791
Just noticed that your sending category_id and question_id as a string, not a number. Instead of the tricky hacks do:
// extract category id from hidden field
var category = $("#category_id").val();
var category_id = parseInt(category);
// extract question id from hidden field
var question = $("#question_id").val();
var question_id = parseInt(question);
And it should be golden. Tried your way in the console and it still returning a string, there's your problem
Upvotes: 1