Reputation: 321
I'm using blueimp's jQuery.fileUpload component to build up part of an application using Laravel 5. The form itself is working as expected, but i'm having a hard time dealing server-side with validation:
Laravel's Request Validation deals with backend validation of the ajax request, and when validation fails, the response is sent with an HTTP 422
code.
The main problem is that blueimp's jQuery.fileUpload does not parse the file
(json) array (doc. link) containing the validation messages. Instead, it simply uses the standard description of HTTP 422
code.
Do you guys know a way to override that? How can I manually parse the json returned from the validation? Or is there a way to make Laravel return HTTP 200 even though validation fails?
Here's some code:
Laravel's Request class:
class UploadRequest extends Request {
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
Log::info("Request de upload");
return [
'file' => 'required|max:1200'
];
}
}
And here's my jQuery.fileUpload initialization script:
$(function () {
'use strict';
var jupload = $('#fileupload');
jupload.fileupload({
url: window.location
});
// from http://stackoverflow.com/a/21728472
if (typeof existingfiles !== 'undefined'){
jupload.fileupload('option', 'done').call(jupload, $.Event('done'), {result: existingfiles});
};
});
Thanks in advance, Peixoto.
Upvotes: 0
Views: 1005
Reputation: 82
I had the same problem a few days ago... If you take a look at the data
object available in each callback you will see that it has within another object, jqXHR
(after all we're dealing with just a jQuery AJAX call), which has itself another object called responseJSON
, with an array with the errors you're looking for.
From the official blueimp docs:
"The send method returns a jqXHR object, that allows to bind callbacks to the ajax file upload request(s):"
var jqXHR = $('#fileupload').fileupload('send', {files: filesList})
.success(function (result, textStatus, jqXHR) {/* ... */})
.error(function (jqXHR, textStatus, errorThrown) {/* ... */})
.complete(function (result, textStatus, jqXHR) {/* ... */});
So now, you could do something like...
$('#fileupload').fileupload({
fail: function (e, data) {
var errors = data.jqXHR.responseJSON;
$.each(errors, function (key, value) {
alert(value);
});
}
});
Or maybe more appropriate:
var jqXHR = data.submit()
.success(function (result, textStatus, jqXHR) {/* ... */})
.error(function (jqXHR, textStatus, errorThrown) {
console.log(data);
var errors = jqXHR.responseJSON;
$.each(errors, function (key, value) {
alert(value);
});
})
.complete(function (result, textStatus, jqXHR) {/* ... */});
Upvotes: 1