SyntaxStudy
Sign Up
jQuery File Upload with AJAX
jQuery Intermediate 4 min read

File Upload with AJAX

AJAX File Upload

Use FormData with jQuery's $.ajax() to upload files asynchronously without a page reload.

Example
$("#uploadForm").on("submit", function(e) {
  e.preventDefault();
  const fd = new FormData(this);

  $.ajax({
    url: "/api/upload",
    type: "POST",
    data: fd,
    processData: false,  // required for FormData
    contentType: false,  // required for FormData
    success: function(res) {
      $("#preview").attr("src", res.url);
    },
    error: function() {
      alert("Upload failed");
    }
  });
});
Pro Tip

Set processData: false and contentType: false when sending FormData — both are required.