Asked 2 years ago
17 Jun 2021
Views 277
Hailee

Hailee posted

jQuery AJAX file upload PHP

jQuery AJAX file upload PHP
web-api

web-api
answered Apr 28 '23 00:00

To upload a file using jQuery AJAX and PHP, you can use the FormData object to send the file data to the server.

First, create a form in HTML with a file input field and a submit button:


 
<form id="uploadForm" enctype="multipart/form-data">
  <input type="file" name="fileToUpload" id="fileToUpload">
  <button type="submit" id="submitBtn">Upload</button>
</form>

Then, add an event listener to the submit button to handle the form submission:



$(document).ready(function() {
  $('#submitBtn').click(function(e) {
    e.preventDefault();
    var formData = new FormData($('#uploadForm')[0]);
    $.ajax({
      url: 'upload.php',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function(data) {
        // Handle success response
      },
      error: function(jqXHR, textStatus, errorThrown) {
        // Handle error response
      }
    });
  });
});

In the above code, we prevent the default form submission behavior using e.preventDefault() and then create a new instance of FormData with the form data. We then make an AJAX request to a PHP file called "upload.php" using $.ajax(). We set the type to "POST", and the data to the formData object. We also set processData and contentType to false to prevent jQuery from automatically processing the data or setting the content type.

In the PHP file, you can retrieve the uploaded file using the $_FILES superglobal array :



$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
  // File uploaded successfully
} else {
  // Error uploading file
}

In the above code, we specify a target directory for the uploaded file and use the move_uploaded_file() function to move the temporary uploaded file to the target directory.

Post Answer