Rails ajax with POST function: why is the template missing?

I am completing loading and cropping an avatar using ajax submit.

I send a base64 image via ajax and then convert my image to a carrier.

Everything works fine, except for ajax answer: Missing template.

This is my ajax call:

$.ajax({ type: "post", dataType: "json", url: "/profile/update_avatar", data: { image: canvas.toDataURL() } }) .done(function(data) { // You can pull the image URL using data.url, eg: $('.user-image').html('<img src="'+data.url+'" />'); }); 

And this is my controller:

 def update_avatar respond_to do |format| if current_user.update_cropped_avatar(params[:image]) format.js format.html { render :nothing => true, :notice => 'Update SUCCESSFUL!' } else format.html { render :action => "edit" } format.json { render :json => current_user.errors, :status => :unprocessable_entity } end end 

end

I do not need to display the template ... but the error is:

 Missing template profiles/update_avatar, application/update_avatar with {:locale=>[:it], :formats=>[:js, :html], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :haml]}. 

Why?

+7
jquery ajax ruby-on-rails
source share
2 answers

The problem will be as follows:

 respond_to do |format| format.js 

I know that you sent JSON to Rails, but it looks like you are processing a standard script dataType when your avatar is sent correctly. Your use of format.js basically makes rails look for action_name.js.erb in your views folder - hence your template error

There are many ways to fix this, including:

 respond_to do |format| format.js { render nothing: true } 

Fix

After chatting with Roberto, this is what worked with him:

 def update_avatar respond_to do |format| if current_user.update_cropped_avatar(params[:image]) format.json { render :json => current_user.profile.avatar_url, :status => 200 } format.html { render :nothing => true, :notice => 'Update SUCCESSFUL!' } else format.html { render :action => "edit" } format.json { render :json => current_user.errors, :status => :unprocessable_entity } end end end 
+10
source share

In your controller action method, you wrote format.js What is the cause of this error.

Change it to format.json { render :json => true } or in your views you can create a file with the name: profiles/update_avatar.js .

So your controller action should look like this:

 def update_avatar respond_to do |format| if current_user.update_cropped_avatar(params[:image]) format.json { render :json => true } #<-------Change here format.html { render :nothing => true, :notice => 'Update SUCCESSFUL!' } else format.html { render :action => "edit" } format.json { render :json => current_user.errors, :status => :unprocessable_entity } end end 
+2
source share

All Articles