0

Hi so i want to create a specific error response through AJAX that will show if an image is too big, or an image is the wrong format? I just do not know how to do this with my separate php file or my AJAX call in my main index file.

Here is the AJAX call

$.ajax({
      url: 'upload.php',
      type: 'POST',
      data: fd,
      contentType: false,
      processData: false,
      success: function(result) {
        console.log('Success!');
        console.log(result);
        location.reload(); 
       },
       error: function(xhr, status, error) {
       if (xhr.status = "Error - 200") {
       $("#error").append(`<p> The following file was to big to upload</p>`
        }
       var errorMessage = xhr.status + ': ' + xhr.statusText
       console.log(errorMessage);
    }
});

Here is my PHP file

$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];

$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png', 'pdf');


if (in_array($fileActualExt, $allowed)) {
    if ($fileError === 0) {
        if ($fileSize < 1000000) {

            $fileNameNew = uniqid('', true) . "." . $fileActualExt;
            $fileDestination = "../test/assets/images/" . $fileNameNew;

            move_uploaded_file($fileTmpName, $fileDestination);

        }
    } else {
        return false;
    }
};

I just do not know where i can set a specific variable that I can use to insert like a specific alert in my html? Thank you.

  • Welcome to Stack Overflow. It would be best to validate the image in the client *before* sending it to PHP. Yet it is good practice to validate the incoming image in PHP too. Displaying the Error you want will fall to the client either way. If the type or the size are not within parameters, PHP can respond with JSON as such. – Twisty Oct 01 '21 at 23:46
  • You can't have `return false` outside of a function. – Barmar Oct 01 '21 at 23:47
  • The `error` function is only executed if there's an HTTP or network error. Normally application-level errors are reported by echoing a status value, and this is handled in the `success` function. – Barmar Oct 01 '21 at 23:48
  • Additionally, you can respond with your own HTTP Response code if you like, so you can pass back your own HTTP Error to your AJAX: https://stackoverflow.com/questions/3258634/php-how-to-send-http-response-code – Twisty Oct 01 '21 at 23:51

0 Answers0