Uploading files to a website via AJAX in jQuery

Photo by RetroSupply on Unsplash

Uploading files to a website via AJAX in jQuery

Ajax Dec 31, 2022

Using a standard html form assumes that when a file is uploaded to the site, the page will be reloaded. But with AJAX method in jQuery, you can make a form in which the file will be submitted without reloading the page. This will add interactivity to the site.

File upload via AJAX

Here is an example code for such a download. First you need to make an HTML form with standard elements. For example, suppose there are only two fields in the form. The first is the name of the food and the second is the photo. You get this html code:

<form action="" method="post">
   <input name="food" type="text">
   <input name="photo" type="file">

To upload files via AJAX, you need to prepare a data structure. To create it, we use the FormData object:

var fdata = new FormData();
fdata.append('photo', $('input[name=photo]')[0].files[0]);
fdata.append('food', $('input[name=food]').val());
   url: '/ajax.php',
   type: 'POST',
   cache: false, 
   data: fdata,
   success: function(data){
      // receiving a response from the site
      // in case of successful submission
   processData: false,
   contentType: false

Thus, during an AJAX request, a file will be transferred to the site. If the project uses PHP, then the file can be caught in the $_FILES['photo']. This variable will contain an array exactly the same in structure as when sending a file via an HTML form. Therefore, modifications to an existing project for interactive AJAX loading will be minimal.

Improved AJAX File Submit Form

Before sending a file, it is advisable to check its size and extension so that they do not go beyond the available limits (PHP and NGINX limits on the server), otherwise the transfer will be interrupted.

File size and file type in input file in jQuery

Checking file extension and sizeWhen creating interactive sites, it is necessary to take into account that it is necessary to point out errors in detail. For example, a user might try to upload a PDF document to a form that only accepts JPG images. Or try to send a file that is too large to the site.

To prevent such misunderstandings, it is necessary to check the file extension and their size before starting the AJAX download. Let's try to write the verification code for this. Let's say we have the form from the previous example:

<input type="file" name="photo">

It is necessary to check the type and size of the file immediately after selecting it in the file window. This is done using js/jq script:

$('input[name=photo]')[0].bind('change', function() {
   var size = this.files[0].size; // size in bytes
   var name = this.files[0].name; // File name

   if(5000000 < size){
      // file larger than 5 megabytes

   var fileExtension = ['jpg', 'jpeg', 'png']; // valid file types
   if ($.inArray(name.split('.').pop().toLowerCase(), fileExtension) == -1) {
      // the file has the wrong type (extension)

   // After passing all the checks
   // you can send a file via AJAX to the site.
   // But if the checks are not passed, then it is necessary
   // show error messages to the user

This code serves to check the size and type of the file. Validation occurs immediately after selecting a file in the device explorer and before submitting the form.

Users will appreciate the interactive prompt as they fill out the form. They don't have to wait for the file to finish uploading to the site before learning that the extension doesn't fit. Of course, this validation at the client JavaScript level does not override the validation at the server script level. It is needed only for the sake of user comfort and will in no way protect the site from downloading a malicious file.


Anurag Deep

Logical by Mind, Creative by Heart