Here’s something that came in helpful the other day at work – “Simple file upload using jQuery and AJAX“. We were on the right track, but this blog post helped iron out the last few details. In particular, this bit:
$.ajax({ url: 'submit.php?files', type: 'POST', data: data, cache: false, dataType: 'json', processData: false, // Don't process the files contentType: false, // Set content type to false as jQuery will tell the server its a query string request success: function(data, textStatus, jqXHR) { if(typeof data.error === 'undefined') { // Success so call function to process the form submitForm(event, data); } else { // Handle errors here console.log('ERRORS: ' + data.error); } }, error: function(jqXHR, textStatus, errorThrown) { // Handle errors here console.log('ERRORS: ' + textStatus); // STOP LOADING SPINNER } });
And a clarification of the parameters:
2 attributes need to be set to false:
- processData – Because jQuery will convert the files arrays into strings and the server can’t pick it up.
- contentType – Set this to false because jQuery defaults to
application/x-www-form-urlencoded
and doesn’t send the files. Also setting it tomultipart/form-data
doesn’t seem to work either.
There’s a GitHub repository with all the necessary example code.
RT @mamchenkov: Simple file upload using jQuery and AJAX #WebDev #JavaScript #jQuery #AJAX https://t.co/qjJ2AZR8Ma
RT @mamchenkov: Simple file upload using jQuery and AJAX #WebDev #JavaScript #jQuery #AJAX https://t.co/qjJ2AZR8Ma