I'm trying to append files to FormData to handle files upload through AJAX and after read and keep finding for a solution without need to use external plugins I found this and I'm trying to use it on my code so I made this:
$(function () {
$('.smart-form').on('submit', function (e)
{
var files;
e.stopPropagation(); // Stop stuff happening
e.preventDefault(); // Totally stop stuff happening
if ($(".state-error").length < 1) {
// Create a formdata object and add the files
var data = new FormData();
// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Grab the files and set them to our variable
files = e.target.files;
$.each(files, function (key, value)
{
data.append(key, value);
});
}
// Create a jQuery object from the form
$form = $(e.target);
// Serialize the form data
var formData = $form.serializeArray();
$.ajax({
async: false,
url: '{{ path('update-product', {'id': id}) }}',
type: 'POST',
data: formData,
cache: false,
success: function (data, textStatus, jqXHR)
{
if (typeof data.error === 'undefined')
{
// Success so call function to process the form
console.log("SUCCESS");
}
else
{
console.log("ERRORS");
}
},
error: function (jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log("ERRORS");
},
complete: function ()
{
// STOP LOADING SPINNER
}
});
}
});
});
But I'm getting this error at Firebug console:
TypeError: e is undefined
And I not able to find where is my mistake or what's happening. Here is a Fiddle with test code, can any help me and tell me what I'm doing wrong?
Update
The error is not the same at jsFiddle, if you take a look at Firebug console the error trown is this one instead:
TypeError: obj is undefined
length = obj.length,