I recently asked this question: Javascript Form Submition?
Now I'm trying to work out why, after form submission, the create.js.erb doesn't load the latest data (the data which was submitted).
If I submit the data again, the table will update with the second last data but not the absolute latest.
...why?
EDIT:
Latest code -
Categories controller: class Admin::CategoriesController < Admin::AdminController ...
def create
@category = Admin::Category.new(params[:admin_category])
# You can't retrieve the @categories before attempting to add new one. Keep at end of create method.
@categories = Admin::Category.all
respond_to do |format|
if @category.save
save_to_history("The category \"#{@category.name}\" has been created", current_user.id)
format.json { render json: { html: render_to_string(partial: 'categories') } }
# I've tried both the above and bellow
#format.json { render json: { html: render_to_string('categories') } }
format.html { redirect_to(admin_categories_url, :notice => 'Category was successfully created.') }
format.xml { render :xml => @category, :status => :created, :location => @category }
else
format.html { render :action => "new" }
format.xml { render :xml => @category.errors, :status => :unprocessable_entity }
end
end
end
...
end
Javascript:
<script type='text/javascript'>
$(function(){
$('#new_admin_category').on('ajax:success', function(event, data, status, xhr){
$("#dashboard_categories").html(data.html);
});
});
</script>
SOLVED
I used @PinnyM's method and added a create.json.erb file with the following code:
<% self.formats = ["html"] %>
{
"html":"<%= raw escape_javascript( render :partial => 'categories', :content_type => 'text/html') %>"
}
and changed my create method to:
def create
@category = Admin::Category.new(params[:admin_category])
respond_to do |format|
if @category.save
# You can't retrieve the @categories before attempting to add new one. Keep after save.
@categories = Admin::Category.all
save_to_history("The category \"#{@category.name}\" has been created", current_user.id)
format.json
format.html { redirect_to(admin_categories_url, :notice => 'Category was successfully created.') }
format.xml { render :xml => @category, :status => :created, :location => @category }
else
format.html { render :action => "new" }
format.xml { render :xml => @category.errors, :status => :unprocessable_entity }
end
end
end
Please do offer suggestions if this is messy.