带图像和文本的Ajax PHP表单提交

时间:2018-03-12 18:41:53

标签: javascript php ajax forms

我正在编写一个应用程序,允许我的妻子将她的食谱添加到我已设置的数据库中。我有一个表单设置文本和图像的文件输入。它工作正常,她可以将文本和图像上传到数据库。现在,我正在尝试添加一个功能,以便她可以编辑它。它是完全相同的形式,只有数据进入不同的PHP文件进行处理。当她点击“编辑”按钮时,它会使用从服务器提取的数据填充所有文本输入,并且可以进行编辑。如果她愿意,她也可以添加一张新照片。尽管它是相同的形式,但它不会上传图像。文本上传很好,但是当我查看发送到服务器的对象$_POST['recipeImage'])时,recipeImage: ""始终为空;

我很困惑,不明白为什么这不起作用。这是代码:

HTML表格(图片上传是底部):

<div id="editRecipeModal">
    <div class="col-md-8">
        <div class="card">
       <form action="../PHP/modify_recipe.php" method="POST" role="form" class="form-horizontal" enctype="multipart/form-data" id="editRecipeForm" name="editRecipeForm">
                <input class="form-control" type="hidden" value="" id="creatorIdEdit" name="creatorId">
                <input class="form-control" type="hidden" value="" id="recipeIdEdit" name="recipeId" value="">
                <div class="card-header card-header-text" data-background-color="purple">
                    <h4 class="card-title"><i class="far fa-edit"></i>&nbsp;Edit Recipe</h4>
                </div>
                <div class="card-content"
                    <div class="row">
                        <label class="col-sm-2 label-on-left">Recipe Name</label>
                        <div class="col-sm-9">
                            <div class="form-group label-floating is-empty">
                                <label class="control-label"></label>
                                <input class="form-control" type="text" name="name" maxlength="150" id="editRecipeName" required>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <label class="col-sm-2 label-on-left">Prep Time</label>
                        <div class="col-sm-9">
                            <div class="form-group label-floating is-empty">
                                <label class="control-label"></label>
                                <input class="form-control" type="number" name="prepTime" id="editPrepTime" required>
                                <span class="help-block">Numbers Only. In minutes... ie: 120 Minutes</span>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <label class="col-sm-2 label-on-left">Servings</label>
                        <div class="col-sm-9">
                            <div class="form-group label-floating is-empty">
                                <label class="control-label"></label>
                                <input class="form-control" type="number" name="servings" id="editServings" required>
                                <span class="help-block">Numbers Only...</span>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <label class="col-sm-2 label-on-left">Calories</label>
                        <div class="col-sm-9">
                            <div class="form-group label-floating is-empty">
                                <label class="control-label"></label>
                                <input class="form-control" type="number" name="calories" id="editCalories" required>
                                <span class="help-block">Numbers Only</span>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <label class="col-sm-2 label-on-left">Brief Description</label>
                        <div class="col-sm-9">
                            <div class="form-group label-floating is-empty">
                                <label class="control-label"></label>
                                <textarea class="form-control" name="description" id="editBriefDescription" rows="5" required></textarea>
                            </div>
                        </div>
                    </div>
                    <hr>
                    <div class="row">
                        <label class="col-sm-2 label-on-left">Ingredients</label>
                        <div class="col-sm-9">
                            <div class="form-group label-floating is-empty">
                                <label class="control-label"></label>
                                <textarea class="form-control" name="ingredients" id="editPasteIngredientsShow" rows="20" required></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <label class="col-sm-2 label-on-left">Recipe Steps</label>
                        <div class="col-sm-9">
                            <div class="form-group label-floating is-empty">
                                <label class="control-label"></label>
                                <textarea class="form-control" name="directions" id="editPasteStepsShow" rows="20" required></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <label class="col-sm-2 label-on-left">Search Tags</label>
                        <div class="col-sm-9">
                            <div class="form-group label-floating is-empty">
                                <label class="control-label"></label>
                                <input class="form-control" type="text" id="editTags" name="tags" required>
                            </div>
                        </div>

                    </div><br> <br> <br> <br>
                    <div class="row">
                        <div class="col-md-12">
                            <div class="row">
                                <div class="col-lg-4 col-md-6 col-sm-3">
                                    <select class="selectpicker" data-style="btn btn-primary btn-round" title="vegOrVegan" data-size="7" id="vegOrVeganEditSelect">
                                                    <option disabled selected>Dietary Restrictions</option>
                                                    <option value="" name="">None</option>
                                                    <option value="T" name="T">Vegetarian</option>
                                                    <option value="VG" name="VG">Vegan</option>
                                                </select>
                                    <input type="hidden" id="vegOrVeganEdit" name="vegOrVegan">
                                </div>
                                <div class="col-lg-4 col-md-6 col-sm-3">
                                    <select class="selectpicker" id="suggestedPairingEditSelect" data-style="btn btn-primary btn-round" title="Suggested Pairing" data-size="7">
                                                    <option disabled selected>Suggested Pairing</option>
                                                    <option value="" name="">None</option>
                                                    <option value="B" name="B">Beer</option>
                                                    <option value="WW" name="WW">White Wine</option>
                                                    <option value="RW" name="RW">Red Wine</option>
                                                </select>
                                    <input type="hidden" id="suggestedPairingEdit" name="suggestedPairing" value="">
                                </div>
                                <div class="col-lg-4 col-md-6 col-sm-3">
                                    <select class="selectpicker" id="" data-style="btn btn-primary btn-round" title="Some Other Attributes" data-size="7">
                                                    <option disabled selected>Some Other Attributes</option>
                                                    <option value="" name="">None</option>
                                                    <option value="B" name="B">Beer</option>
                                                    <option value="WW" name="WW">White Wine</option>
                                                    <option value="WW" name="WW">Red Wine</option>
                                       </select>
                                </div>
                            </div>

                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12" style="text-align: center;">
                        </div>
                    </div>
                    <div class="row" style="width: 80%; margin: 0 auto;">
                        <div class="col-sm-4"></div>
                        <div class="col-sm-4" style="text-align: center;">
                            <div class="fileinput fileinput-new text-center" data-provides="fileinput">
                                <div class="fileinput-new thumbnail">
                                    <img src="../assets/img/placeholder.jpg" alt="...">
                                </div>
                                <div class="fileinput-preview fileinput-exists thumbnail"></div>
                                <div>
                                    <span class="btn btn-rose btn-round btn-file">
                                                    <span class="fileinput-new">Select image</span>
                                    <span class="fileinput-exists">Change</span>
                                    <input type="file" name="recipeImage" id="recipeImageEdit" />
                                    </span>
                                    <a href="#pablo" class="btn btn-danger btn-round fileinput-exists" data-dismiss="fileinput"><i class="fa fa-times"></i> Remove</a>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-4"></div>
                    </div>
                    <br><br>
                    <div class="row">
                        <div class="col-sm-2"></div>
                        <div class="col-sm-4" style=" text-align: center; margin: 0; padding: 0;"><button class="btn btn-primary btn-lg modRecButton" type="submit" id="submitRecipe">Submit Changes</button></div>
                        <div class="col-sm-4 closePanel" style="text-align: center; margin: 0; padding: 0;" id="closePanel"><button type="button" class="btn btn-default btn-lg">Cancel Changes</button>
                        </div>
                        <div class="col-sm-2"></div>
                    </div>
                </div>

            </form>
        </div>
    </div>
</div>

AJAX代码

$(document).ready(function(e) {
    $("#editRecipeForm").on('submit', (function(e) {
        e.preventDefault();
        $.ajax({
            url: "../PHP/modify_recipe.php",
            type: "POST",
            data: new FormData(this),
            cache: false,
            contentType: false,
            processData: false,
            success: function(response) {
                let parsedResponse = JSON.parse(response);
                let newObject = parsedResponse[0]
                if (parsedResponse == 'notModified') {
                    showErrorModal();
                }else{
                    reBuildAfterObjectChange(newObject.recipeId, parsedResponse);
                }
            },
            error: function() {
                showErrorModal();
            }
        });
    }));
});

PHP代码

<?php
    include 'db_operations.php';
            if(isset($_POST['name'])&& isset($_POST['description']) && isset($_POST['ingredients'])&& isset($_POST['directions']) && isset($_POST['suggestedPairing'])  && isset($_POST['prepTime']) && isset($_POST['servings']) && isset($_POST['calories'])  && isset($_POST['vegOrVegan']) && isset($_POST['recipeId']) && isset($_POST['creatorId']))
            {
        $result = '';
        $name = $_POST['name'];
        $description = $_POST['description'];
        $ingredients = $_POST['ingredients'];     
        $ingredients = str_replace(';', '-', $ingredients);
        $ingredients = str_replace('\n', ';', $ingredients);
        $directions = $_POST['directions'];
        $directions = str_replace(';', '-', $directions);
        $directions = str_replace('\n', ';', $directions);          
        $suggestedPairing = $_POST['suggestedPairing'];
        $prepTime = $_POST['prepTime'];
        $servings = $_POST['servings'];
        $calories = $_POST['calories'];
        $vegOrVegan = $_POST['vegOrVegan'];
        $recipeId = $_POST['recipeId'];
        $creatorId = $_POST['creatorId'];
        $tags = $_POST['tags'];
        $time=time();
        $lastModified = (date("Y-m-d H:i:s", $time));

        modifyRecipe_recipes($name, $description, $ingredients, $directions, $suggestedPairing, $prepTime, $servings, $calories, $vegOrVegan, $lastModified, $creatorId, $recipeId, $tags);
            }

        if(isset($_POST['recipeImage'])){
            $size = $_FILES['recipeImage']['size'];

            if($size > 0){
             $tmp_dir = $_FILES["recipeImage"]["tmp_name"];
            $tmpImg = $_FILES['recipeImage']['name'];
            $ext = strtolower(pathinfo($tmpImg, PATHINFO_EXTENSION));

            $recipeImage = rand(10000, 10000000).".".$ext;
            move_uploaded_file($tmp_dir, "../userRecipeImages/".$recipeImage);
            $sql = 'UPDATE recipes SET recipeImage = :recipeImage WHERE creatorId = :creatorId AND recipeId= :recipeId';
            $stmt = $conn->prepare($sql);       
            $stmt->bindParam(':creatorId', $creatorId, PDO::PARAM_STR);                       
            $stmt->bindParam(':recipeImage', $recipeImage, PDO::PARAM_STR);            
            $stmt->bindParam(':recipeId', $recipeId, PDO::PARAM_STR);            
            $stmt->execute();               

            }

        }


        $modifiedRecipeDate = getLastModified_recipes($lastModified, $creatorId);
        if ($modifiedRecipeDate === $lastModified) {
                $newObject = getSingleRecipeById_recipes($recipeId, $creatorId);
                echo json_encode($newObject);
        }
        else {
            $result = "notModified";
            echo json_encode($result);
        }


?>

1 个答案:

答案 0 :(得分:1)

您显然忘了将$_POST['recipeImage']更改为$_FILES['recipeImage']

文件包含在$_FILES全局变量$_POST

更改此

if(isset($_POST['recipeImage'])){

if(isset($_FILES['recipeImage'])){