如何通过ajax上传图像时发送文件信息

I am attempting to split up image file uploading to an ajax method. All of the html and JS is in one file and then I made up a PHP file that contains all of the PHP.

What I am struggling with is I am not sure how to send the image file info over to the php file and then for the rest of the php to work as it used to.

As of now, this line of code $p_img = $_POST['file']; is getting an undefined index error. However, even if that is populating, I am not sure if this will work correctly with the files being seperated.

Is there anyway that I can leave my first PHP function, UploadFile in the file with the HTML and JS and then send the function over to the PHP file?

IF not, what can I do?

HTML

<form action="" method="POST" id="projectForm" enctype="multipart/form-data">
    <label>Project Name</label>
    <input type="text" class="input block" name="p_name">
    <label>Project Img</label>
    <input type="file" id="file" name="file" class="file-input block">
    <button id="submit">Submit Project</button>
</form>

JS

$('#projectForm').validate({
        ignore: [],
        rules: {
            p_name: {
                required: true,
                minlength: 5
            },
            p_alt: {
                required: true,
                minlength: 2
            }
        },
        messages: {
            p_name: {
                required: "Please enter the project name",
                minlength: "The project name is too short"
            },
            p_alt: {
                required: "Please enter the alt text",
                minlength: "Your alt text is too short"
            }
        },
        submitHandler: function (form, e) {
            e.preventDefault();
            var formData = new FormData(form);
            category = $(this).data('category');

            console.log(category);

            $.ajax({
                url: '/php/projectSend.php',
                type: 'POST',
                data: formData,
                success: function (data) {
                  console.log(data);
                },
                contentType: false,
                processData: false,
                error: function (xhr, textStatus, errorThrown) {
                    alert(textStatus + " | " + errorThrown);
                    alert('There are currently no project images for this selection');
                }
            });
        }
    });

PHP

ini_set('display_errors', 1);
error_reporting(E_ALL);
include($_SERVER['DOCUMENT_ROOT'].'/config.php');

$p_name = trim(htmlspecialchars($_POST['p_name'], ENT_QUOTES));
$p_img = $_POST['file'];
$p_alt = trim(htmlspecialchars($_POST['p_alt']));
$category = trim(htmlspecialchars($_POST['categoryName']));
$creator = trim(htmlspecialchars($_POST['creatorName']));
$status = $_POST['status'];

    function UploadFile($fileArray = array(), $destinationFolder = '../project_images/') {
        $filename       =   $fileArray['file']['name'];
        $tmp_name       =   $fileArray['file']['tmp_name'];
        $filesize       =   $fileArray['file']['size'];
        $file_error     =   $fileArray['file']['error'];
        $file           =   $fileArray['file'];
        // Save all the default data.
        $return['error']        =   true;
        $return['success']      =   false;
        $return['file']['dest'] =   $destinationFolder.$filename;
        $return['file']['size'] =   $filesize;

        if($file_error == 0)
            $return['error']    =   false;
        if(!is_dir($destinationFolder))
            mkdir($destinationFolder,0755,true);
        // If your filename is not empty, return success or fail of upload
        if (!empty($filename))
            $return['success']  = (move_uploaded_file($tmp_name, $destinationFolder.$filename));

        return $return;
    }

try {
    $con = getConfig('pdo');
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    function SaveToDb($con,$filename = false) {
        // Return fail immediately if the connection is false or image is invalid
        if(empty($filename) || !$con)
            return false;
        $project_sql = "
            INSERT INTO quotes
            (p_name, p_img, p_alt, category, creator, status, date_added)
            VALUES(?, ?, ?, ?, ?, ?, NOW())
        ";
        if ($project_stmt = $con->prepare($project_sql)) {
            $project_stmt->execute(array($p_name, $p_img, $p_alt, $category, $creator, $status));
            return true;
            $proj_succ = "Success";
            echo json_encode($proj_succ);
        }
        return false;
    }
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

    if(isset($_POST['create'])) {
        // Try uploading
        $upload =   UploadFile($_FILES);
        // If upload fails
        if(!$upload['success']) {
            echo '<h3>Sorry, an error occurred</h3>';
        }
        else {

            // Try to save it
            $saveToDb   =   SaveToDb($con,$upload['file']['dest']);
            // Get the profile from image name
            $profPic    =   ($saveToDb)? getPhoto($con,$upload['file']['dest']) : false;   
        }
    }

I think your form object you are sending to FormData is not what FormData expects.

var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function() {

  var oOutput = document.querySelector("div"),
      oData = new FormData(form);
}

you can read more

That's because you're trying to access the uploaded file via the $_POST array, which doesn't include files. What you're looking for is $_FILES.

Reference