Background
I first wanted to upload a file via json and get a response in that way as well.
I'm using:
- Rails 3
- ajaxForm
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?