提交图像的Ajax表单错误

时间:2022-11-23 16:55:06

I'm having a difficult time trying to make AJAX edit changes when the form is submitted on the same page and make the changes appear, but the image throws error: Undefined index: image in update.php on line 22 and 24. It refuses to pass the values.

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

Form (editForm.php):

形式(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(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(...)

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 (display edited changes) Problem: Need to submit those edited changes

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');
                });
            }
        });


   });


   });

4 个解决方案

#1


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

    }
});

By default the image is not being added to the form during your post, you need to get the entire form and append the image to it before sending it. I did this for asp.net, it should work for php too though.

默认情况下,在发布过程中不会将图像添加到窗体中,您需要获取整个窗体,并在发送之前将图像附加到窗体中。我这样做是为了asp.net,但它也应该适用于php。

#2


1  

Add a series of tests to your PHP and you'll figure it out quite quickly yourself.

在PHP中添加一系列测试,您自己就可以很快地解决它。

You are already alerting the response sent by the PHP ajax processor file:

您已经在通知PHP ajax处理程序文件发送的响应:

alert(smsg);

So, use that to troubleshoot/diagnose where things are going wrong.

因此,使用它来排除/诊断出哪里出了问题。

First test can be to put a "I got here" message at the top of the PHP file -- at least then you know the ajax itself is working. So, modify the top of update.php to read:

第一个测试可以是在PHP文件的顶部放置一个“I got here”消息——至少您知道ajax本身正在工作。因此,修改更新的顶部。php阅读:

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

If that alerts, then get rid of the die() and echo out a few more such tests at various places in the file. Use this method to narrow down the location (in the PHP file) of the error.

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

Echo out the data received so you know what is coming in. Modify update.php to be:

回传接收到的数据,这样您就知道要输入什么了。修改更新。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();

I'm sure you'll find the error pretty quick -- certainly quicker than composing a detailed SO question and awaiting the answer...

我相信你很快就会发现这个错误——当然比写一个详细的SO问题等待答案要快得多……

Good luck!

好运!

#3


1  

Maybe it's because the image never send to server via ajax, so $_FILES have nothing under 'image' index. Take a look at how to do file upload using jquery serialization

可能是因为这个映像从来没有通过ajax发送到服务器,所以$_FILES在“image”索引下没有任何内容。看看如何使用jquery序列化进行文件上传

or consider to use FormData object.

或者考虑使用FormData对象。

#4


0  

Change <input name="image" type="file" id="inputImage"/ to <input name="image" type="file" id="inputImage"/>

#1


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

    }
});

By default the image is not being added to the form during your post, you need to get the entire form and append the image to it before sending it. I did this for asp.net, it should work for php too though.

默认情况下,在发布过程中不会将图像添加到窗体中,您需要获取整个窗体,并在发送之前将图像附加到窗体中。我这样做是为了asp.net,但它也应该适用于php。

#2


1  

Add a series of tests to your PHP and you'll figure it out quite quickly yourself.

在PHP中添加一系列测试,您自己就可以很快地解决它。

You are already alerting the response sent by the PHP ajax processor file:

您已经在通知PHP ajax处理程序文件发送的响应:

alert(smsg);

So, use that to troubleshoot/diagnose where things are going wrong.

因此,使用它来排除/诊断出哪里出了问题。

First test can be to put a "I got here" message at the top of the PHP file -- at least then you know the ajax itself is working. So, modify the top of update.php to read:

第一个测试可以是在PHP文件的顶部放置一个“I got here”消息——至少您知道ajax本身正在工作。因此,修改更新的顶部。php阅读:

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

If that alerts, then get rid of the die() and echo out a few more such tests at various places in the file. Use this method to narrow down the location (in the PHP file) of the error.

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

Echo out the data received so you know what is coming in. Modify update.php to be:

回传接收到的数据,这样您就知道要输入什么了。修改更新。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();

I'm sure you'll find the error pretty quick -- certainly quicker than composing a detailed SO question and awaiting the answer...

我相信你很快就会发现这个错误——当然比写一个详细的SO问题等待答案要快得多……

Good luck!

好运!

#3


1  

Maybe it's because the image never send to server via ajax, so $_FILES have nothing under 'image' index. Take a look at how to do file upload using jquery serialization

可能是因为这个映像从来没有通过ajax发送到服务器,所以$_FILES在“image”索引下没有任何内容。看看如何使用jquery序列化进行文件上传

or consider to use FormData object.

或者考虑使用FormData对象。

#4


0  

Change <input name="image" type="file" id="inputImage"/ to <input name="image" type="file" id="inputImage"/>