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

C++ JAVA
Post Reply
User avatar
Ticketa
Турист
Турист
Posts: 393
Joined: Mon Feb 27, 2012 1:54 pm
Answers: 23
Location: in /root
Contact:

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

Post by Ticketa » Thu Mar 14, 2019 8:14 pm

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

insert.php

Code: Select all

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

Това ми връща данните в масива:
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

Code: Select all

<!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&#58;//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <link rel="stylesheet" href="https&#58;//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script>
$&#40;document&#41;.ready&#40;function&#40;&#41;&#123;
 
 $&#40;document&#41;.on&#40;'click', '.add', function&#40;&#41;&#123;
  var html = '';
  html += '<tr>';
  html += '<td><input type="text" name="item_name&#91;&#93;" class="form-control item_name" /></td>';
  html += '<td><input type="file" name="item_photo&#91;&#93;" class="form-control item_photo" /></td>';
  html += '<td><input type="text" name="item_price&#91;&#93;" class="form-control item_price" /></td>';
  html += '<td><input type="text" name="item_quantity&#91;&#93;" class="form-control item_quantity" /></td>';
  html += '<td><input type="text" name="item_min_quantity&#91;&#93;" class="form-control item_min_quantity" /></td>';
  html += '<td><textarea placeholder="Description" class="form-control item_description" name="item_description&#91;&#93;" ></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>';
  $&#40;'#item_table'&#41;.append&#40;html&#41;;
 &#125;&#41;;
 
 $&#40;document&#41;.on&#40;'click', '.remove', function&#40;&#41;&#123;
  $&#40;this&#41;.closest&#40;'tr'&#41;.remove&#40;&#41;;
 &#125;&#41;;
 
 $&#40;'#insert_form'&#41;.on&#40;'submit', function&#40;event&#41;&#123;
  event.preventDefault&#40;&#41;;
  var error = '';
  $&#40;'.item_name'&#41;.each&#40;function&#40;&#41;&#123;
   var count = 1;
   if&#40;$&#40;this&#41;.val&#40;&#41; == ''&#41;
   &#123;
    error += "<p>Enter Item Name at "+count+" Row</p>";
    return false;
   &#125;
   count = count + 1;
  &#125;&#41;;
  $&#40;'.item_photo'&#41;.each&#40;function&#40;&#41;&#123;
   var count = 1;
   if&#40;$&#40;this&#41;.val&#40;&#41; == ''&#41;
   &#123;
    error += "<p>Enter Photo at "+count+" Row</p>";
    return false;
   &#125;
   count = count + 1;
  &#125;&#41;;
  $&#40;'.item_price'&#41;.each&#40;function&#40;&#41;&#123;
   var count = 1;
   if&#40;$&#40;this&#41;.val&#40;&#41; == ''&#41;
   &#123;
    error += "<p>Enter Item Price at "+count+" Row</p>";
    return false;
   &#125;
   count = count + 1;
  &#125;&#41;;
  
  $&#40;'.item_quantity'&#41;.each&#40;function&#40;&#41;&#123;
   var count = 1;
   if&#40;$&#40;this&#41;.val&#40;&#41; == ''&#41;
   &#123;
    error += "<p>Enter Item Quantity at "+count+" Row</p>";
    return false;
   &#125;
   count = count + 1;
  &#125;&#41;;
  $&#40;'.item_min_quantity'&#41;.each&#40;function&#40;&#41;&#123;
   var count = 1;
   if&#40;$&#40;this&#41;.val&#40;&#41; == ''&#41;
   &#123;
    error += "<p>Enter Item Min. Quantity at "+count+" Row</p>";
    return false;
   &#125;
   count = count + 1;
  &#125;&#41;;
  $&#40;'.item_description'&#41;.each&#40;function&#40;&#41;&#123;
   var count = 1;
   if&#40;$&#40;this&#41;.val&#40;&#41; == ''&#41;
   &#123;
    error += "<p>Enter Item Description at "+count+" Row</p>";
    return false;
   &#125;
   count = count + 1;
  &#125;&#41;;
  
  var form_data = $&#40;this&#41;.serialize&#40;&#41;;
  if&#40;error == ''&#41;
  &#123;
   $.ajax&#40;&#123;
    url&#58;"insert.php",
    method&#58;"POST",
    data&#58;form_data,
    success&#58;function&#40;data&#41;
    &#123;
     if&#40;data == 'ok'&#41;
     &#123;
      $&#40;'#item_table'&#41;.find&#40;"tr&#58;gt&#40;0&#41;"&#41;.remove&#40;&#41;;
      $&#40;'#error'&#41;.html&#40;'<div class="alert alert-success">Item Details Saved</div>'&#41;;
     &#125;
    &#125;
   &#125;&#41;;
  &#125;
  else
  &#123;
   $&#40;'#error'&#41;.html&#40;'<div class="alert alert-danger">'+error+'</div>'&#41;;
  &#125;
 &#125;&#41;;
 
&#125;&#41;;
</script>
</head>
<body>
<div class="container-fluid">
    <div class="row">
     <div class="col-md-12"> <!-- col-md-offset-0 -->
   <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>

  <!-- Table data display -->
  <div class="table-responsive">
      <table class="table table-bordered table-hover" style="margin-top&#58;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&#40;"SELECT * FROM `items`"&#41;;
        	while&#40;$row = $sqlquery->fetch_array&#40;&#41;&#41;&#123;
                echo '  
               <tr>  
                 <td>#0000'.$row&#91;"id"&#93;.'</td> 
                 <td>'.$row&#91;"photo"&#93;.'</td> 
                 <td>'.$row&#91;"name"&#93;.'</td>  
                 <td>$ '.$row&#91;"price"&#93;.'</td>  
                 <td>'.$row&#91;"qty"&#93;.'</td>  
                 <td>'.$row&#91;"min_qty"&#93;.'</td>
                 <td>? '.$row&#91;"euro"&#93;.'</td>
                 <td>'.$row&#91;"bgn"&#93;.' лв</td>
                 <td>'.$row&#91;"total"&#93;.' лв</td>
                 <td>'.$row&#91;"description"&#93;.'</td>
                 <td>'.$row&#91;"datetime"&#93;.'</td>
            <td><button style="float&#58;left" class="btn btn-warning btn-sm"><span class="glyphicon glyphicon-edit"></span></button></td>
            <td><button style="float&#58;left" class="btn btn-danger btn-sm"><span class="glyphicon glyphicon-remove"></span></button></td>
               </tr>  
                ';  
             &#125;
             ?>
        </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>

Post Reply