Ask Your Question
4

What is the procedure for invoking an AJAX callback to upload a file?

asked 2023-07-05 10:34:22 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-07-05 10:50:01 +0000

djk gravatar image

Here is a possible procedure for invoking an AJAX callback to upload a file:

  1. 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>
  1. 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);
});
  1. 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);
  1. 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.
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-05 10:34:22 +0000

Seen: 7 times

Last updated: Jul 05 '23