Reputation: 5411
I have the following code to execute an ajax call and render a partial:
$("#save-category").click(function(){
var category_id = $('#categorization_category_id').val();
var category_name = $('#categorization_category_id option:selected').text();
var user_id = "#{current_user.id}";
$.ajax({
url: "#{dashboard_categorizations_path}",
type: 'POST',
dataType : 'json',
data: {'user_id': user_id, 'category_id': category_id},
success: function(data) {
$("#categoriamensaje").show();
$('.categories').html("#{escape_javascript(render('tutor_categories'))}");
var leadMessage = setInterval(function(){
$("#categoriamensaje").hide();
}, 3000);
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
});
everything works except the render partial.
This is the haml code:
.row
.col-md-2
.col-md-5
%h3
= _("Tus Categorias")
.categories
= render partial: 'tutor_categories'
.col-md-4
And my controller code:
def create
@categorization = Categorization.new(categorization_params)
@categorization.save
respond_to do |format|
format.json { render json: {id: @categorization.id.to_json}, success: 200 }
end
end
Thanks
Upvotes: 0
Views: 1072
Reputation: 9747
As per our discussion in chat, you need to append new categorization
records instead of replacing whole list.
Your HAML will become:
.row
.col-md-2
.col-md-5
%h3
= _("Tus Categorias")
.categories
= render partial: 'tutor_categories', collection: @user_categories, as: :category
.col-md-4
Your partial will looks like:
.badge-tutor{style:"margin: 2px;"}
= link_to "<i class='fa fa-tag'></i> #{category.name} <i class='fa fa-times-circle fa-1x' style='color:#A21F1F;'></i>".html_safe, dashboard_categorization_path(category.id), method: :delete, data: { confirm: 'Eliminar esta categoria?' }, style: "color:#fff;text-decoration: none;font-size: 15px;"
Controller:
def create
@categorization = Categorization.new(categorization_params)
@categorization.save
respond_to do |format|
format.json {render json: {category: @categorization}, success: 200}
end
end
In your AJAX call, you need to update partial rendering code to:
$('.categories').html("#{escape_javascript(render(:partial => 'tutor_categories', :locals => {:category => data.category}))}");
Upvotes: 1