How to add a file upload in php using jquery and ajax?

Part 1: Setting up the file upload

We can select a file and click upload. The file will be sent to the server using AJAX without refreshing the page.

  1. index.html — Web frontend file.
  2. upload.php — Backend script that handles uploads.
  3. uploads/ — A folder to store the uploaded files.

<h2>Upload a File</h2>

<input type="file" id="fileInput">

<button id="uploadBtn">Upload</button>

<div id="status"></div>
$('#uploadBtn').on('click', function () {

var file = $('#fileInput')[0].files[0];

if (!file) {

$('#status').text('Please select a file.');

return;

}

var formData = new FormData();

formData.append('file', file);

$.ajax({

url: 'upload.php',

type: 'POST',

data: formData,

processData: false,

contentType: false,

success: function (response) {

$('#status').html(response);

},

error: function () {

$('#status').text('An error occurred while uploading.');

}

});

});