How can JavaScript be used to facilitate file selection in PHP applications?
To facilitate file selection in PHP applications, JavaScript can be used to create a user-friendly interface for uploading files. This can be achieved by using JavaScript to trigger the file input field and display the selected file name to the user. Once the file is selected, it can be uploaded to the server using PHP.
<!DOCTYPE html>
<html>
<head>
<title>File Upload Example</title>
</head>
<body>
<input type="file" id="fileInput">
<button onclick="uploadFile()">Upload File</button>
<script>
function uploadFile() {
var fileInput = document.getElementById('fileInput');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php', true);
xhr.onload = function() {
if (xhr.status === 200) {
alert('File uploaded successfully');
} else {
alert('Error uploading file');
}
};
xhr.send(formData);
}
</script>
</body>
</html>