Explain Codes LogoExplain Codes Logo

How can I upload files asynchronously with jQuery?

javascript
async-upload
xhr
progress-updates
Nikita BarsukovbyNikita Barsukov·Feb 11, 2025
TLDR

Asynchronously upload files with jQuery using FormData and $.ajax:

var formData = new FormData(); // Starting your FormData instance. formData.append('file', $('#fileInput').prop('files')[0]); // Attaching your file to the fortunes of FormData. $.ajax({ url: 'upload.php', // Here's where your file embarks on its journey to the server. type: 'POST', data: formData, contentType: false, processData: false, success: () => console.log('Upload successful! The file is chilling on the server now.'), error: e => console.error('Error:', e) });
  • Initial setup involves attaching the chosen file with append() to your FormData instance.
  • contentType and processData should be set to false.
  • Depending on your file's journey, success and error handlers deal with results.

Keeping track with progress updates

Monitoring the file's journey can often be reassuring. Use the xhr object from $.ajaxSettings.xhr() to keep a watchful eye on your file's progress. Comment below is optional, but encouraged for full comedic effect. 👀

function ajaxUpload(formData) { return $.ajax({ xhr: function() { var xhr = new window.XMLHttpRequest(); // Spawn the XMLHttpRequest transportation device. xhr.upload.addEventListener('progress', function(evt) { if (evt.lengthComputable) { var percentComplete = evt.loaded / evt.total; console.log(`This file has travelled ${percentComplete * 100}% of its journey`); } }, false); return xhr; }, // Type your AJAX settings here. The destiny of your file relies on it. }); }

This code provides real-time progress updates during the upload by setting up an event listener on progress.

Pre-upload checkup

It's always smart to prescreen your file by checking its size, name, and type before sending it off.

$('#fileInput').on('change', function() { var file = this.files[0]; if (file.size > 1048576) { // 1MB load limit alert('This file seems to be mooching off too much space!'); this.value = ''; // Resetting for another file pick. } else { // File checks out, onto uploading... } });

This file prescreening takes place in the comfort of your browser. No burden is placed on the server. The last thing we want is a grumpy server.

Aesthetically pleasing user interaction and feedback

Your dear user has just entrusted their precious files in your care. It's only fitting to give them a pleasant user experience. Incorporate 'onComplete' callback methods to graciously inform your users about their file's fate on the server.

Compatibility fallbacks

What if the user is stuck in the past due to old browsers? Give them a timeless fallback using a hidden iframe. Sequential management of the multiple file uploads ensures your server doesn't crumble under file size stress.