Reputation: 39
I cannot pass parameters to controller action in ajax POST request. There is my code :
$("#sendSubCatButton").click(function(){
var catId = $("#category_name").data("id");
var subCatName = $("#sous_category_name").val();
var lvlUrgenceMax = $("#sous_category_lvl_urgence_max option:selected").val();
// alert(catId);
// alert(subCatName);
// alert(lvlUrgenceMax);
$.ajax({
url: '/sous_categories',
type: 'POST',
dataType: 'json',
data: {
name: subCatName,
category_id: catId,
lvl_urgence_max: lvlUrgenceMax
}
});
});
And my controller (only the parts concerned) :
def create
@create_new_subcategory = verifRight('create_new_subcategory')
if @create_new_subcategory
@category = Category.find(params[:category_id])
@sous_category = SousCategory.new(sous_category_params)
# Any category have a 'lvl_urgence_max', for those who create an incident.
# With that, we can determine how many an incident is important.
@sous_category.lvl_urgence_max.nil? ? @sous_category.lvl_urgence_max = 10 : false
respond_to do |format|
if @sous_category.save
format.json { render json: @sous_category.id, status: :created }
format.html { redirect_to edit_category_path(@category), notice: 'Vous venez de créer une sous catégorie.' }
else
format.json { render json: @sous_category.errors, status: :unprocessable_entity }
format.html { redirect_to :back, notice: 'Impossible de créer la sous catégorie.' }
end
end
else
renderUnauthorized
end
end
...
def sous_category_params
params.require(:sous_category).permit(:name, :category_id, :lvl_urgence_max)
end
In console there are that :
Started POST "/sous_categories" for 127.0.0.1 at 2016-08-31 16:08:56 +0200
Processing by SousCategoriesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"EDqyXaq+2PekfJrLrmn/+16AnirzvySD+hkZj5+cQee2JD2ddMudDRJWXlZkCfKJ3mzw2AWuVAeCPr/y0Y1WVw==", "sous_category"=>{"name"=>"efsefesf", "lvl_urgence_max"=>"10"}}
EDIT : I commented the "alerts" but I can see the value of the var "CatId" in the alert popup but it is not passed.
Upvotes: 1
Views: 797
Reputation: 576
var data = {"data": {
"name": subCatName,
"category_id": catId,
"lvl_urgence_max": lvlUrgenceMax
}};
$.ajax({
type: 'POST',
url: 'http://localhost:3000/sous_categories',
data: JSON.stringify(data),
contentType: 'application/json',
dataType: 'json'
});
Upvotes: 1