Here is a possible procedure for invoking an AJAX callback to upload a file:
- Create a form element with an input of type "file" that allows the user to select a file to upload. For example:
<form enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
- Attach an event listener to the form's submit button that prevents the default form submission behavior, creates a FormData object, and sends an AJAX request with the FormData object as the data payload. For example:
var form = document.querySelector('form');
var btn = document.querySelector('button[type="submit"]');
btn.addEventListener('click', function(e) {
e.preventDefault();
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php');
xhr.onload = function() {
if (xhr.status === 200) {
console.log('File uploaded successfully');
}
else {
console.log('Error uploading file');
}
}
xhr.send(formData);
});
- In the AJAX request, set the method to "POST" or "PUT" (depending on the server's requirements), set the URL to the server-side script that will handle the file upload, and set the data payload to the FormData object you created. For example:
xhr.open('POST', 'upload.php');
xhr.send(formData);
- On the server-side, the script should receive the file contents from the "file" parameter of the POST request, save the file to a designated location on the server, and return a response indicating success or failure. The exact code for this will depend on the server-side language and framework you are using.