PHP / jQuery试图发回从另一个文件生成的数据

I am currently working with some files where "fileA.php" has an option (among other things) to upload an image to my server. The "Upload Image" button calls on "upload.php" to make sure it fits my required parameters, uploads the image, generates a random name, and then renames the image to the random name.

I want to be able to get the image's new name from upload.php back to fileA.php so I can have some sort of pop up or message for the user:

"Your image was successfully uploaded and renamed to xyz.jpg"

I am currently using a combination of jQuery and PHP POSTs to send data between file. I have seen many posts where the answer seems to be "echo the data you want from upload.php and then require the upload file in fileA.php", but I can't get that to work, and I would ideally like the returned random file name generated in upload.php to be saved in a variable in fileA.php

Am I out of luck folks? Thanks for reading.

In the following code that would be found at the end of my "upload.php" file, I would like to return the value of $mediaPath back to fileA.php

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)) {


    $randName = substr(md5(rand()), 0, 15) . '.' . $imageFileType; //generates a pseudorandom string 2^31(? I think so, also saw 2^32 somewhere, but how?) possibilities, as the md5 hash of a random int truncated to 15 characters


    rename($target_file, "/var/www/html/uploads/" . $randName);

    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded and renamed to <new name here>";
} else {
    echo "Sorry, there was an error uploading your file.";
}
}

$mediaPath = "/var/www/html/uploads/" . $randName;

return $mediaPath;

and then I think I need to implement some sort of jQuery function in "fileA.php" like the following:

 $.ajax({
 type: "POST",
 url: "upload.php",
 datatype: "html",
 data: dataString,
 success: function(data) {
   alert(data);
   }
});

And this could fetch the value of "$mediaPath" and alert it out for me -- so far this does not give me any values of "data" that would be inserted in to the file, it just outputs the generic statements hardcoded in to upload.php?

Going to keep giving it a shot, would love to finally crack this case! Open to all reasonable suggestions on how to do this/best practices, cheers.

Edit - tried updating to include Jamie M's answer:

my jQuery:

    $(document).ready(function() { 
        $('#imageForm').ajaxForm(function() { 
              $.ajax({
                   type: "POST",
                   url: "upload.php",
                   dataType: "json", // We want a JSON response
                   data: dataString, // I have to assume this is already set by the upload utility
                   success: function(data) {
                     alert(data.image); // Specify the index
                   }
            });
        }); 
    });

</script>

my HTML/PHP: Select image to upload:

my upload.php

header('Content-type: application/json'); // Tell the browser what to expect so it can handle it properly



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

// Grabs the file extension of the submitted file, to be used on/around line 28
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;
    }
}

// Checks uploads/ to see if file already exists, throws uploadOk to 0 therefore sending an error if it does. This is probably going to be made useless by randomizing the upload names. Also what if two people want to use the same picture?
 if (file_exists($target_file)) {
    echo "Sorry, file already exists. 
";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 2000000) {
    echo "Sorry, your file is too large. 
";
    $uploadOk = 0;
}
// Allow certain file formats, checks to make sure it is a valid image 
format using $imageFileType
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)) {


    $randName = substr(md5(rand()), 0, 15) . '.' . $imageFileType; 
//generates a pseudorandom string 2^31(? I think so, also saw 2^32 somewhere, but how?) possibilities, as the md5 hash of a random int truncated to 15 characters


        rename($target_file, "/var/www/html/uploads/" . $randName);
        $data = ['image' => $randName]; // You can add as many items as you like here
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded and renamed to <new name here>";
    } else {
         echo json_encode($data);
    }
}

    echo json_encode($data); // Encode it properly to ensure the response is valid for browser parsing


?>

So far I am unsuccessful and the above code (seemingly) does not return any values from upload.php, and there are no visible errors in the console.

I hope I've understood your question correctly..

There are a couple more steps you need here. First you need to specifically return JSON data in a predictable way. To do this, I suggest the following in upload.php:

$data = ['image' => $mediaPath]; // You can add as many items as you like here
header('Content-type: application/json'); // Tell the browser what to expect so it can handle it properly
echo json_encode($data); // Encode it properly to ensure the response is valid for browser parsing
exit(); // Optional, but nothing beyond this point can be properly returned.

JSON expects data to be echoed, not returned, and by indexing in an array it makes it easy to access in the next step (in fileA.php):

<script type="text/javascript">
  $.ajax({
   type: "POST",
   url: "upload.php",
   dataType: "json", // We want a JSON response
   data: dataString, // I have to assume this is already set by the upload utility
   success: function(data) {
     alert(data.image); // Specify the index
   }
  });
</script>

This should work, then you just need to do as you like with data.image.

EDIT

There are a number of flaws in your edited processing code and I've (quickly, not perfectly) tried to iron some out below. One thing not clear is what your upload tool is expecting to see in the case of a successful processing - it could be that the response you're generating is breaking it.

In any case, try the following:

<?php

    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = true;
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

    $errorMsgs = array();

    // Grabs the file extension of the submitted file, to be used later
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check === false) {
            $errMsgs[] = "File is not an image.";
            $uploadOk = false;
        }
    } else {
        // What are we doing here?
    }

    // Checks uploads/ to see if file already exists, throws uploadOk to 0 therefore sending an error if it does. This is probably going to be made useless by randomizing the upload names. Also what if two people want to use the same picture?
    if (file_exists($target_file)) {
        // NOTE: we don't echo yet as this would break any subsequent output
        $errMsgs[] = "Sorry, file already exists. 
";
        $uploadOk = false;
    }

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

    // Allow certain file formats, checks to make sure it is a valid image format using $imageFileType
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
      && $imageFileType != "gif" ) {
        $$errMsgs[] = "Sorry, only JPG, JPEG, PNG & GIF files are allowed. 
";
        $uploadOk = false;
     }

    // Check if $uploadOk has been negated
    if (!$uploadOk) {
        // Set header for browser to understand
        header('Content-type: application/json');
        echo implode(', ', $errMsgs);
        exit();

    } else {
         if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            $randName = substr(md5(rand()), 0, 15) . '.' . $imageFileType; 
            //generates a pseudorandom string 2^31(? I think so, also saw 2^32 somewhere, but how?) possibilities, as the md5 hash of a random int truncated to 15 characters

            rename($target_file, "/var/www/html/uploads/" . $randName); // What if this fails?

            $data = array(
                'success' => 1,
                'image' => $randName,
                'message' => "The file " . basename( $_FILES["fileToUpload"]["name"]) . " has been uploaded and renamed to {$randName}"
            ); 
            // You can add as many items as you like above. NOTE you can now use data.image for the image name or data.message for the full string.

            // NOTE: What is the uploader expecting to receive in case of success?

            header('Content-type: application/json');
            echo json_encode($data); // This was probably your main issue

        } else {
            header('Content-type: application/json');
            echo "Unable to store file in system";
        }
    }   

    ?>