Ошибка формы Ajax при отправке изображения

У меня возникают трудности при попытке внести изменения в редактирование 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');
});
}
});});});

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, хотя.

1

Другие решения

Добавьте серию тестов в ваш PHP, и вы сами это быстро поймете.

Вы уже оповещаете об ответе, отправленном файлом процессора ajax PHP:

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();

Я уверен, что вы найдете ошибку довольно быстро — конечно, быстрее, чем составление подробного ТАКОГО вопроса и ожидание ответа …

Удачи!

1

Может быть, это потому, что изображение никогда не отправляется на сервер через ajax, поэтому $_FILES не иметь ничего под 'image' индекс.
Взгляни на как сделать загрузку файла с использованием jquery сериализации

или рассмотреть возможность использования FormData объект.

1

+ Изменить <input name="image" type="file" id="inputImage"/ to <input name="image" type="file" id="inputImage"/>

0