How do I upload files with AJAX and PHP?

AJAX, PHP, file upload, asynchronous file upload
This guide explains how to upload files using AJAX and PHP, providing a seamless user experience without page reloads.

To upload files using AJAX and PHP, you need to create an HTML form, use JavaScript to handle the file upload asynchronously, and then process the uploaded file on the server using PHP. Below is an example to demonstrate this process.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>File Upload with AJAX</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <form id="uploadForm" enctype="multipart/form-data"> <input type="file" name="file" id="file" required> <button type="submit">Upload</button> </form> <div id="response"></div> <script> $(document).ready(function(e) { $('#uploadForm').on('submit', function(e) { e.preventDefault(); // Prevent default form submission var formData = new FormData(this); $.ajax({ url: 'upload.php', type: 'POST', data: formData, contentType: false, processData: false, success: function(response) { $('#response').html(response); }, error: function() { $('#response').html('File upload failed!'); } }); }); }); </script> </body> </html>

On the server side, create a file named upload.php to handle the uploaded file:

<?php if (isset($_FILES['file'])) { $file = $_FILES['file']; $uploadDirectory = 'uploads/'; // Ensure the upload directory exists if (!is_dir($uploadDirectory)) { mkdir($uploadDirectory, 0755, true); } $uploadPath = $uploadDirectory . basename($file['name']); if (move_uploaded_file($file['tmp_name'], $uploadPath)) { echo "File uploaded successfully: " . htmlspecialchars($file['name']); } else { echo "Error uploading file."; } } else { echo "No file uploaded."; } ?>

AJAX PHP file upload asynchronous file upload