【问题标题】:Ajax Form Error submitting an imageAjax 表单提交图像时出错
【发布时间】:2014-10-04 19:32:31
【问题描述】:

当表单在同一页面上提交并显示更改时,我很难尝试进行 AJAX 编辑更改,但图像抛出错误:Undefined index: image in update.php on line 22 and 24。它拒绝传递值。

表单(editForm.php):

<div class="modal-content editDisplay">
 <div class="modal-header">
  <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
  <h4 class="modal-title" id="editModalLabel">Edit Item</h4>
</div>
<form class="editForm" method="post" enctype="multipart/form-data">
  <div class="modal-body">
        <div class="form-group">
            <label for="inputName">Name</label>
            <input type="text" class="form-control" id="inputName" name="Product_Name" placeholder="Name" value="<?php echo $product ?>">
            <input type="hidden" name="oldProduct" value="<?php echo $oldProduct ?>">
        </div>
        <div class="form-group">
            <label for="inputDescription">Description</label>
            <textarea class="form-control" id="inputDescription" name="Description" placeholder="Description"><?php echo $description ?></textarea>
        </div>
        <div class="form-group">
            <label for="inputPrice">Price</label>
            <input type="text" class="form-control" id="inputPrice" name="Price" placeholder="Price" value="<?php echo $price ?>">
        </div>
        <div class="form-group">
            <label for="inputQuantity">Quantity</label>
            <input type="number" class="form-control" id="inputQuantity" name="Quantity" placeholder="Quantity" value="<?php echo $quantity ?>">
        </div>
        <div class="form-group">
            <label for="inputSalePrice">Sale Price</label>
            <input type="text" class="form-control" id="inputSalePrice" name="Sale_Price" placeholder="Sale Price" value="<?php echo $salePrice ?>">
        </div>
        <div class="form-group">
            <label for="inputImage">Image Upload</label><br>
            <fieldset class="file-fieldset">
                <span class="btn btn-default btn-file">
                    <span class="glyphicon glyphicon-upload"></span>&nbsp;&nbsp;Browse Browse <input name="image" type="file" id="inputImage"/><br>
                </span>
                <input type="hidden" name="prevPicture" value="<?php $image ?>"/>
                <span style="margin-left:8px;" value=""><?php echo $image ?></span>

            </fieldset>
        </div>
  </div>
  <div class="modal-footer">
    <button type="reset" class="btn btn-default">Reset</button>
    <button type="submit" class="btn btn-primary" id="saveButton" name="update">Save Changes</button>
  </div>
 </form>
</div>

PHP (update.php):

<?php

include('connection.php');
include('LIB_project1.php');

$productName = $_POST['Product_Name'];
$productDescription = $_POST['Description'];
$price = $_POST['Price'];
$quantity = $_POST['Quantity'];
$salePrice = $_POST['Sale_Price'];
$oldImage = $_POST['prevPicture'];
$oldProduct = $_POST['oldProduct'];


//$productName = 'Jaime';
//$productDescription = 'This is crazy';
//$price = '0';
//$quantity = '12234';
//$salePrice = '0';
//$oldImage = $_POST['prevPicture'];
//$oldProduct = $_POST['oldProduct'];
$imageName= $_FILES['image']['name']; //TODO line 22
echo ' The image is '.$imageName;
$image_temp = $_FILES['image']['tmp_name']; // line 24
echo 'Product name is: '.$productName;

//$productName = 'Dodo Square';
//$productDescription = 'Flower on a Bee. Such Beauty!';
//$price = 9;
//$quantity = 8;
//$salePrice = 230;
//$newImage = '038.jpg';
//$oldProduct = 'Times Square';

//working under the assumption that the image already exist in the database
$targetDirectory = 'productImages'; 
$files = scandir($targetDirectory,1);
//code passed
for($i=0; $i<sizeof($files); $i++)
{
    if($oldImage==$files[$i])
    {
        unlink('productImages/'.$oldImage);
    }
}

$target = "productImages";

//add the image to the directory
$target = $target.'/'.$imageName;
move_uploaded_file($image_temp,$target);  

updateProduct($conn,'product',':productName', ':productDescription', ':price', ':quantity', ':imageName', ':salePrice',                          'Product_Name', 'Description', 'Price', 'Quantity', 'Image_Name', 'Sale_Price', $productName, $productDescription, $price, $quantity,$imageName, $salePrice, $oldProduct, ':oldProduct');
//header('location:admin.php');

?>

updateProduct(...)

/*
 * This is a function to update Product
 * 
 */
 function updateProduct(PDO $connection,$table,$bindProductName, $bindProductDescription, $bindPrice, $bindQuantity, $bindImageName, $bindSalePrice,$productNameColumn, $productDescriptionColumn, $priceColumn, $quantityColumn, $imageNameColumn, $salePriceColumn,                                    $productName, $productDescription, $price, $quantity, $imageName, $salePrice, $oldProduct, $bindOldProduct)
 {
     $result = false;

     $sql = 'UPDATE ' . $table . ' SET ' . $productNameColumn . ' = ' . $bindProductName . ',' . $productDescriptionColumn . ' = ' .                            $bindProductDescription . ',' . $priceColumn . ' = ' . $bindPrice . ',' . $quantityColumn . ' = ' . 
       $bindQuantity . ',' . $salePriceColumn . ' = ' . $bindSalePrice . ',' . $imageNameColumn . ' = ' . $bindImageName . ' WHERE ' .                      $productNameColumn . ' = ' . $bindOldProduct;

    $smtp = $connection->prepare($sql);
    $smtp -> bindParam($bindProductName, $productName);
    $smtp -> bindParam($bindProductDescription, $productDescription);
    $smtp -> bindParam($bindPrice, $price);
    $smtp -> bindParam($bindQuantity, $quantity);
    $smtp -> bindParam($bindImageName, $imageName);
    $smtp -> bindParam($bindSalePrice, $salePrice);
    $smtp -> bindParam($bindOldProduct, $oldProduct);

    if($smtp->execute() )
    {
        $result = true;
    }

    return $result;
}

AJAX(显示已编辑的更改)问题:需要提交那些已编辑的更改

 $(document).ready(function() 
 {
           //the user click save edit
   $(".edit").on("submit",function(e)
   { 
       e.preventDefault();
       $.ajax({
            type:"POST",
            url:'update.php', //I will put project id here as well
            data:$(".editForm").serialize(),
            success:function(smsg)
            {
                alert(smsg);
               //update the number of items the user has in their shopping cart
                $.get('admin.php',function(data){
                $('#refresh').load("admin.php #refresh");
                    //alert('success');
                });
            }
        });


   });


   });

【问题讨论】:

  • 您的输入标签已损坏 &lt;input name="image" type="file" id="inputImage"/ 将其更改为 &lt;input name="image" type="file" id="inputImage"/&gt; 这是最可能的原因。
  • 另外,这是什么updateProduct($conn,'product',':productName', ':productDescription', ':price', ':quantity', ':imageName', ':salePrice', 'Product_Name', 'Description', 'Price', 'Quantity', 'Image_Name', 'Sale_Price', $productName, $productDescription, $price, $quantity,$imageName, $salePrice, $oldProduct, ':oldProduct');?您的绑定周围也有引号。如果您使用的是 PDO,请删除绑定的引号。然而,很难说您的查询是什么或应该是什么。
  • 感谢您的修复,但我仍然收到错误消息。 updateProduct() 是更新产品时可重复使用的函数。
  • 不客气。你有var url='editForm.php?'; 不应该是var url='update.php?'; 吗?

标签: php ajax ajaxform forms http-post


【解决方案1】:
var inputImage = $("#inputImage");
var fd = new FormData(document.getElementById("editform")); 

fd.append("image", inputImage);

$.ajax({
    url: "",
    type: "POST",
    data: fd,
    processData: false, 
    contentType: false, 
    success: function(response) {

    }
});

默认情况下,图片不会在您发布期间添加到表单中,您需要获取整个表单并将图片附加到表单中,然后再发送。我是为 asp.net 做的,不过它也应该适用于 php。

【讨论】:

    【解决方案2】:

    在您的 PHP 中添加一系列测试,您很快就会自己解决。

    您已经在提醒 PHP ajax 处理器文件发送的响应:

    alert(smsg);
    

    所以,用它来排除故障/诊断哪里出了问题。

    第一个测试可以是在 PHP 文件的顶部放置一条“我到了”消息——至少那时您知道 ajax 本身正在工作。所以,修改update.php的顶部为:

    <?php
    echo "Got to here";
    die();
    

    如果发出警报,则删除die() 并在文件的不同位置回显一些此类测试。使用此方法缩小错误的位置(在 PHP 文件中)。

    回显接收到的数据,以便您了解传入的内容。将 update.php 修改为:

    $productName = $_POST['Product_Name'];
    $productDescription = $_POST['Description'];
    $price = $_POST['Price'];
    $quantity = $_POST['Quantity'];
    $salePrice = $_POST['Sale_Price'];
    $oldImage = $_POST['prevPicture'];
    $oldProduct = $_POST['oldProduct'];
    
    echo "$productName: " .$productName. " -- $productDescription: " .$productDescription. " - etc etc etc";
    die();
    

    我相信您会很快发现错误 - 肯定比编写详细的 SO 问题并等待答案要快...

    祝你好运!

    【讨论】:

      【解决方案3】:

      可能是因为图像从不通过 ajax 发送到服务器,所以$_FILES'image' 索引下没有任何内容。 看看how to do file upload using jquery serialization

      或者考虑使用FormData对象。

      【讨论】:

        【解决方案4】:

        更改&lt;input name="image" type="file" id="inputImage"/ to &lt;input name="image" type="file" id="inputImage"/&gt;

        【讨论】:

        • 已修复,但问题依旧。更新帖子。
        • 是的,我可以帮助你:)
        • Harutyun Abgaryan,更新功能运行良好。我通过给每个变量值独立测试它,它们被正确地发布到数据库中。
        猜你喜欢
        • 2014-08-26
        • 1970-01-01
        • 1970-01-01
        • 2016-01-16
        • 1970-01-01
        • 2021-09-30
        • 2014-02-09
        • 2018-01-27
        相关资源
        最近更新 更多