skip to Main Content

I got totally lost.

Ive tried to make some Image Upload function in PHP and everything works fine. Because i dont want the whole Page to reload, when uploading a File i wanted to use AJAX with Jquery, to send the Form Content (Image) via POST to a file like upload.php with an hidden ajax request.

No matter what i try its impossible to send anything with formData(). I copied & pasted several Sample Codes, tried changing the Code, nothing happens when i use formData().

A normal request with Jquery / Ajax, using POST works fine.

Here ist the Sample of my last used Code..

Could my XamPP has been misconfigured, or what could cause that really not one of the Scripts from google, tutorial pages etc works?

<!DOCTYPE html>
<html>
<body>

<script type="text/javascript" src="jquery.min.js"></script>


<form id="Test" action="" method="post" enctype="multipart/form-data">
  Select image to upload:
  <input type="file" name="fileToUpload" id="fileToUpload">
 
</form>
 <button id="Knopf">Knopf</button>

<div id="Disp">fghfgh</div>

</body>


<script>

    



$(document).ready(function(){
  $("#Knopf").click(function(){
    
    var formData = new FormData(Test);

    $.ajax({
        url : "uploadtest2.php",
        type : "POST", 
        data : formData,
        cache : false,
        contentType : false,
        processType : false,
        success : function() {
            $("#Disp").html(result);
        }
    });

  });
});



</script>


</html>
<?php
$target_dir = "Media/uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
  $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
  if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
  } else {
    echo "File is not an image.";
    $uploadOk = 0;
  }
}

// Check if file already exists
if (file_exists($target_file)) {
  echo "Sorry, file already exists.";
  $uploadOk = 0;
}

// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
  echo "Sorry, your file is too large.";
  $uploadOk = 0;
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
  echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
  $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
  echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
  if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
  } else {
    echo "Sorry, there was an error uploading your file.";
  }
}
?>

2

Answers


  1. Please see: https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData

    You must use a Form Element:

    An HTML <form> element — when specified, the FormData object will be populated with the form’s current keys/values using the name property of each element for the keys and their submitted value for the values. It will also encode file input content.

    Consider the following example.

    $(function() {
      $("#Test").submit(function(e) {
        e.preventDefault();
        var formData = new FormData(this);
        $.ajax({
          url: "uploadtest2.php",
          type: "POST",
          data: formData,
          cache: false,
          contentType: false,
          processType: false,
          success: function(result) {
            $("#Disp").html(result);
          }
        });
      });
      $("#Knopf").click(function() {
        $("#Test").submit();
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form id="Test" action="" method="post" enctype="multipart/form-data">
      Select image to upload:
      <input type="file" name="fileToUpload" id="fileToUpload" />
    </form>
    <button id="Knopf" type="submit">Knopf</button>
    <div id="Disp">fghfgh</div>

    It is better to bind to the submit callback. This way, if the User submits the form or clicks Submit, the callback is triggered. We need to .preventDefault() on the Event to ensure the Form doesn’t post or submit the data. Now we can then perform the AJAX call without the page being refreshed.

    In your success callback, you must pass in a variable to be used for the returned data. Otherwise result will be undefined.

    With the proper FormData, there should be no issue uploading. this in the callback refers to the Form Element itself.

    Consider updating your PHP as well:

    if(isset($_POST["submit"])) {
    

    Change this to:

    if(isset($_POST["fileToUpload"])) {
    
    Login or Signup to reply.
  2. The problem is this:

    if(isset($_POST["submit"])) {
    

    There’s no element named submit in the form, so this check fails. Even if you had a submit button in the form, it wouldn’t be included in formData, because buttons are only automatically included in POST data when they trigger normal form submission.

    You can add that to formData.

    var formData = new FormData(Test);
    formData.set("submit", "1");
    

    Or you could change your test to

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search