Upload форма не прикачва файла , когато се използва jQuery?

Ticketa

Registered
Привет,
имам следния php Код, който добавя данни към базата данни , като с него нямам проблем. Проблема е, че при изпращане на POST заявката през jQuery не се получава към PHP-то и връща празен резултат.

insert.php
Код:
<?php
include("config.php");
if(isset($_POST["item_name"])) {
    for($count = 0; $count < count($_POST["item_name"]); $count++) {
        $name    = trim($_POST["item_name"][$count]);
        $price   = trim($_POST["item_price"][$count]);
        $qty     = trim($_POST["item_quantity"][$count]);
        $min_qty = trim($_POST["item_min_quantity"][$count]);
        $photo   = trim($_POST["item_photo"][$count]);
        $description = trim($_POST["item_description"][$count]);
        $target_dir = "files/";
        $target_file = $target_dir . basename($_FILES["item_photo"][$count]["name"]);
        $uploadOk = 1;
        $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
    
        
        /*print_r($_POST);die;
        Array
            (
                [item_name] => Array
                    (
                        [0] => 142
                    )
            
                [item_price] => Array
                    (
                        [0] => 15
                    )
            
                [item_quantity] => Array
                    (
                        [0] => 15
                    )
            
                [item_min_quantity] => Array
                    (
                        [0] => 15
                    )
            
                [item_description] => Array
                    (
                        [0] => asd
                    )
            
            )
            */
        $check = getimagesize($_FILES["item_photo"][$count]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
        // Check if file already exists
        if (file_exists($target_file)) {
            echo "Sorry, file already exists.";
            $uploadOk = 0;
        }
        // Check file size
        if ($_FILES["item_photo"][$count]["size"] > 500000) {
            echo "Sorry, your file is too large.";
            $uploadOk = 0;
        }
        // Allow certain file formats
        if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
        && $imageFileType != "gif" ) {
            echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
            $uploadOk = 0;
        }
        
        if ($uploadOk == 0) {
            echo "Sorry, your file was not uploaded.";
        } else { // if everything is ok, try to upload file
            if (move_uploaded_file($_FILES["item_photo"][$count]["tmp_name"], $target_file)) {
               $xml = new SimpleXMLElement(
                    'http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml',
                    null,
                    true
                );
                $rates = array(
                    'EUR' => null,
                    'USD' => null,
                    'BGN' => null
                );
                foreach($xml->Cube->Cube->Cube as $item){
                    if(true === array_key_exists((string)$item['currency'], $rates)){
                        $rates[(string)$item['currency']] = (float)$item['rate'];
                    }
                }
                $euro = round($price*$rates[BGN], 2);
                $bgn  = round($price*$rates[BGN], 2);
                $total = $bgn*$qty;
                $sql = "INSERT INTO items (name,price,qty,min_qty,euro,bgn,total,photo,description,datetime) 
                VALUES ('$name', '$price', '$qty', '$min_qty', '$euro', '$bgn', '$total', '". basename( $_FILES["item_photo"][$count]["name"]). "', '$description', now())";
                
                $result =  'ok';//$statement->fetchAll();
            } else {
                //echo "Sorry, there was an error uploading your file.";
                $result =  '';//$statement->fetchAll();
            }
        }
    }
    if(isset($result)) {
        echo 'ok';
    }
}


Това ми връща данните в масива:

Array
(
[item_name] => Array
(
[0] => 142
)

[item_price] => Array
(
[0] => 15
)

[item_quantity] => Array
(
[0] => 15
)

[item_min_quantity] => Array
(
[0] => 15
)

[item_description] => Array
(
[0] => asd
)

)

В случая, липсва добавената снимка item_photo.

index.php
Код:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
    <title>SYSTEM</title>
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script>
$(document).ready(function(){
 
 $(document).on('click', '.add', function(){
  var html = '';
  html += '<tr>';
  html += '<td><input type="text" name="item_name[]" class="form-control item_name" /></td>';
  html += '<td><input type="file" name="item_photo[]" class="form-control item_photo" /></td>';
  html += '<td><input type="text" name="item_price[]" class="form-control item_price" /></td>';
  html += '<td><input type="text" name="item_quantity[]" class="form-control item_quantity" /></td>';
  html += '<td><input type="text" name="item_min_quantity[]" class="form-control item_min_quantity" /></td>';
  html += '<td><textarea placeholder="Description" class="form-control item_description" name="item_description[]" ></textarea></td>';
  html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
  $('#item_table').append(html);
 });
 
 $(document).on('click', '.remove', function(){
  $(this).closest('tr').remove();
 });
 
 $('#insert_form').on('submit', function(event){
  event.preventDefault();
  var error = '';
  $('.item_name').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Enter Item Name at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  $('.item_photo').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Enter Photo at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  $('.item_price').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Enter Item Price at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  
  $('.item_quantity').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Enter Item Quantity at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  $('.item_min_quantity').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Enter Item Min. Quantity at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  $('.item_description').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Enter Item Description at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  
  var form_data = $(this).serialize();
  if(error == '')
  {
   $.ajax({
    url:"insert.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     if(data == 'ok')
     {
      $('#item_table').find("tr:gt(0)").remove();
      $('#error').html('<div class="alert alert-success">Item Details Saved</div>');
     }
    }
   });
  }
  else
  {
   $('#error').html('<div class="alert alert-danger">'+error+'</div>');
  }
 });
 
});
</script>
</head>
<body>
<div class="container-fluid">
    <div class="row">
     <div class="col-md-12"> 
   <form method="post" id="insert_form" enctype="multipart/form-data">
    <div class="table-repsonsive">
     <span id="error"></span>
     <table class="table table-bordered" id="item_table">
      <tr>
       <th>Enter Item Name</th>
       <th>Enter Item Photo</th>
       <th>Enter price</th>
       <th>Enter Quantity</th>
       <th>Enter Min. Quantity</th>
       <th>Enter Description</th>
       <th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
      </tr>
     </table>
     <div align="center">
      <input type="submit" name="submit" class="btn btn-info" value="Insert" />
     </div>
    </div>
   </form>
            <br><br>

  
  <div class="table-responsive">
      <table class="table table-bordered table-hover" style="margin-top:11px;">
        <thead>
            <tr>
                <th>арт.</th>
                <th>снимка</th>
                <th>име</th>
                <th>цена/бр</th>
                <th>кол.</th>
                <th>мин.за поръчка</th>
                <th>евро</th>
                <th>лев</th>
                <th>тотал</th>
                <th>описание</th>
                <th>Дата</th>
                <th></th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            <?php
        	$sqlquery = $mysqli->query("SELECT * FROM `items`");
        	while($row = $sqlquery->fetch_array()){
                echo '  
               <tr>  
                 <td>#0000'.$row["id"].'</td> 
                 <td>'.$row["photo"].'</td> 
                 <td>'.$row["name"].'</td>  
                 <td>$ '.$row["price"].'</td>  
                 <td>'.$row["qty"].'</td>  
                 <td>'.$row["min_qty"].'</td>
                 <td>? '.$row["euro"].'</td>
                 <td>'.$row["bgn"].' лв</td>
                 <td>'.$row["total"].' лв</td>
                 <td>'.$row["description"].'</td>
                 <td>'.$row["datetime"].'</td>
            <td><button style="float:left" class="btn btn-warning btn-sm"><span class="glyphicon glyphicon-edit"></span></button></td>
            <td><button style="float:left" class="btn btn-danger btn-sm"><span class="glyphicon glyphicon-remove"></span></button></td>
               </tr>  
                ';  
             }
             ?>
        </tbody>
      </table>
        <br />
        <form method="post" action="export.php">
         <input type="submit" name="export" class="btn btn-success" value="Export" />
        </form>
    </div>
    </div>
  </div>
</div>
</body>
</html>
 

Горе