Search code examples
ruby-on-railsajaxform

Rails + ajaxForm: Use the 'error' callback when error uploading file


Background

I first wanted to upload a file via json and get a response in that way as well.

I'm using:

I soon found out that you can't get a reponse in json. So, I follow that advice and returned as text.

I'm able to get things working after removing the pre tags. Ugly solution, but it's an ugly problem.

Problem

Now, my problem is handling errors.

Here's the JS:

$('form#new_image').submit(function() {
  $(this).ajaxSubmit({
    dataType: 'text',
    beforeSubmit: showLoading,
    success: imageUploadSuccess,
    error: imageUploadError
  });
  return false;
});

function imageUploadSuccess(data) {
  var jsonObject = $.parseJSON((/<pre>(.+)<\/pre>/.exec(data))[1]);
  //Do something
}

function imageUploadError(data) {
  alert("FAIL!");
}

Even if I respond with an error, the success callback (imageUploadSuccess) is always executed.

Here's my controller:

def create
  @image = Image.new params[:file]
  @image.imageable_type = params[:imageable_type]
  @image.imageable_id = params[:imageable_id]

  respond_to do |f|
    if @image.save
      logger.debug "PASSED"
      f.text {render :text => @image.to_json}
    else
      logger.debug "FAIL"
      f.text { render :text => "Fail!", :status => 500 }
    end
  end
end

Now, while I could return a json object with success: false in it when it fails, it just feels dirty that the success callback is always executed.

How do I make use of the error callback?


Solution

  • It seems that whether you use .ajax or .ajaxForm to submit it, as long as the server responds, the success callback will be executed.

    So, I have to reply with specially structured json that has a success: true/false depending on the situation. It's best illustrated with the controller action (I'm using inherited_resources here, but you get the idea):

    def create
      create! do |success, failure|
       success.html {redirect_to to}
       success.text do
         image = {
           :id => @image.id,
           :file_name => @image.file_name,
           :success => true
         }
         render :text => image.to_json
       end
       failure.text do
         image = {
          :success => false,
          :errors => @image.errors
         }
         render :text => image.to_json
       end
       success.js
      end
    end