Ajax Upload image

To upload an image using Ajax, you can use the following steps:

  1. Create an HTML form that allows the user to select an image file to upload
  2. Add a JavaScript file that handles the file upload using an XMLHttpRequest object
  3. On the server side, use the PHP move_uploaded_file function to save the uploaded image to a desired location

Here is some sample code to get you started:

HTML Form:

<form id="uploadForm" enctype="multipart/form-data">
  <input type="file" name="image" />
  <input type="submit" value="Upload Image" />
</form>

JavaScript file:

// Get the form element
var form = document.getElementById('uploadForm');

// Add a submit event listener to the form
form.addEventListener('submit', function(e) {
  // Prevent the default form submission behavior
  e.preventDefault();

  // Get the selected file
  var file = form.querySelector('[name="image"]').files[0];

  // Create a new FormData object
  var formData = new FormData();

  // Add the file to the FormData object
  formData.append('image', file);

  // Create an XMLHttpRequest object
  var xhr = new XMLHttpRequest();

  // Set the request URL
  xhr.open('POST', '/upload.php');

  // Set the request as asynchronous
  xhr.responseType = 'json';
  
  // Set the request onload event listener
  xhr.onload = function() {
    if (xhr.status === 200) {
      // The image was successfully uploaded
      console.log(xhr.response);
    } else {
      // There was an error uploading the image
      console.error(xhr.response);
    }
  }

  // Send the request
  xhr.send(formData);
});

upload.php:

<?php

// Check if the image was uploaded
if (isset($_FILES['image'])) {
  // Get the image file path
  $image_path = $_FILES['image']['tmp_name'];

  // Check if the file is an image
  if (exif_imagetype($image_path)) {
    // Save the image to a desired location
    move_uploaded_file($image_path, '/path/to/saved/image.jpg');
    echo json_encode(['status' => 'success']);
  } else {
    echo json_encode(['status' => 'error', 'message' => 'The uploaded file is not an image']);
  }
} else {
  echo json_encode(['status' => 'error', 'message' => 'No image was uploaded']);
}

?>