26
PHP form with HTML file input that submits using AJAX:
<!DOCTYPE html>
<html>
<head>
<title>File Upload Form</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<input type="submit" value="Upload File"> </form>
<script>
$(document).ready(function() {
$('#uploadForm').submit(function(e) {
e.preventDefault();
$.ajax({
url: 'upload.php',
type: 'POST',
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function(response) {
alert(response);
},
error: function(xhr, status, error) {
alert("Error occurred: " + error);
}
});
});
});
</script>
</body>
</html>
HTML part:
- We have a basic HTML form with an input field of type "file" for users to choose a file for upload.
- The form has an id attribute "uploadForm" which we use to target it in JavaScript.
- When the form is submitted, it prevents the default form submission behavior using `e.preventDefault()` to handle the submission via AJAX.
JavaScript part:
- We include jQuery library to simplify AJAX requests.
- In the script section:
- We wait for the document to be ready (`$(document).ready(...)`) to ensure the DOM elements are loaded before attaching event handlers.
- We attach a submit event handler to the form with id "uploadForm".
- Inside the submit handler, we prevent the default form submission behavior using `e.preventDefault()`.
- We then make an AJAX POST request using `$.ajax()` method.
- Parameters of the AJAX request:
- `url`: Specifies the URL where the form data will be sent. In this case, it's 'upload.php'.
- `type`: Specifies the HTTP method to be used for the request, which is POST.
- `data`: Contains the data to be sent to the server. We create a new `FormData` object from the form element (`new FormData(this)`) to include file data.
- `cache`: Set to false to force requested pages not to be cached.
- `contentType`: Set to false to prevent jQuery from automatically setting the content type. This is necessary when sending a FormData object.
- `processData`: Set to false to prevent jQuery from automatically processing the data.
- `success`: A callback function to be executed if the request succeeds. In this case, it shows an alert with the response.
- `error`: A callback function to be executed if the request fails. It shows an alert with the error message.
PHP part (in upload.php):
- We first check if the request method is POST.
- Then, we specify the directory where the uploaded files will be stored (`$targetDir`).
- We define the target file path by concatenating the target directory with the base name of the uploaded file (`$targetFile`).
- We initialize `$uploadOk` to 1, which will be used to track if the file upload is successful.
- We get the file extension (`$imageFileType`) to validate the file type later.
- We perform various checks:
- If the file already exists, we set `$uploadOk` to 0 and echo an error message.
- If the file size exceeds a certain limit, we set `$uploadOk` to 0 and echo an error message.
- If the file type is not allowed, we set `$uploadOk` to 0 and echo an error message.
- If all checks pass, we attempt to move the uploaded file from the temporary directory to the target directory using `move_uploaded_file()` function.
- If the file is moved successfully, we echo a success message. Otherwise, we echo an error message.