How can I upload files asynchronously with jQuery

javascriptjquery

To upload files asynchronously with jQuery, you can use the $.ajax() function to send an HTTP POST request to the server with the file data.

Here is an example of how you can do this:

$('#file-input').change(function() {
  // get the selected file
  const file = this.files[0];

  // create a FormData object to store the file data
  const data = new FormData();

  // add the file to the FormData object
  data.append('file', file);

  // send an AJAX request to the server with the file data
  $.ajax({
    type: 'POST',
    url: '/upload',
    data: data,
    processData: false,  // tell jQuery not to process the data
    contentType: false,  // tell jQuery not to set the content type
    success: function(response) {
      // handle the response from the server
      console.log('File uploaded successfully');
    },
    error: function(xhr, status, error) {
      // handle the error
      console.error('Error uploading file:', error);
    },
  });
});

In this example, the change event handler is used to detect when the user selects a file using the file input element.