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:
- 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 = para开发者_如何学JAVAms[: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?
Here is some generic jQuery code to make your ajax submission:
$('#btn-submit').click(function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: $('form').attr('action'),
data: $('form').serialize(),
success: function(data) {},
error: function(data) {}
});
});
EDIT:
I just saw you're willing to upload file with ajax. Ajax doesn't allow this kind of processing, but there are great alternatives.
I give two examples here (two branches): https://github.com/apneadiving/Pic-upload---Crop-in-Ajax
- with uploadify using flash
- with jQuery Uploader, 100% js (using frames)
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
精彩评论