2014-12-19 58 views
0

好的,所以我想說如果以前有人問過我先對不起。儘管我似乎無法在問題部分找到它,而且我花了數小時尋找我需要的東西。使用Ajax將數據項更新到數據庫

所以開始。我從我的數據庫 - >產品的表中抽取一行數據。然後將它們添加到購物車。我知道如何在PHP中做到這一點,但我是JavaScript和Ajax的新手。我有我的代碼工作,我可以提交一個表單添加到數據庫,但它沒有爲第一個之後的任何工作。

我也會包括我的所有代碼,但我只需要幫助瞭解如何將各個項目添加到購物車。這對我來說似乎很簡單,但我無法弄清楚這樣做的正確方法,並感謝任何幫助!

這是我顯示數據庫產品的頁面的代碼。

//*script*// 
    <script type="text/javascript"> 
      $(document).ready(function() { 


       $("#FormSubmitAddToCart").click(function (e) { 
         e.preventDefault(); 
         if($("#qtyArea").val()==='0') 
         { 
          alert("Please enter a quantity!"); 
          return false; 
         } 

         $("#FormSubmitAddToCart").hide(); //hide submit button 
         $("#LoadingImage").show(); //show loading image 

         var id = 'id='+ $("#idArea").val(); 
         var qty = 'qty='+ $("#qtyArea").val(); 
         var myData = id+'&'+qty; 
         //alert(myData); 
         jQuery.ajax({ 
         type: "POST", // HTTP method POST or GET 
         url: "response.php", //Where to make Ajax calls 
         dataType:"text", // Data type, HTML, json etc. 
         data:myData, //Form variables 
         success:function(response){ 
          $("#responds").append(response); 
          $("#idArea").val(''); //empty text field on successful 
          $("#qtyArea").val(''); //empty text field on successful 
          $("#FormSubmitAddToCart").show(); //show submit button 
          $("#LoadingImage").hide(); //hide loading image 

         }, 
         error:function (xhr, ajaxOptions, thrownError){ 
          $("#FormSubmitAddToCart").show(); //show submit button 
          $("#LoadingImage").hide(); //hide loading image 
          alert(thrownError); 
         } 
         }); 
       }); 
    </script> 

//*selects products from database*// 
<?php 
include_once("config.php"); 

$results = $mysqli->query("SELECT * FROM products"); 
while($row = $results->fetch_assoc()) { 
    echo '<li id="item_'.$row["id"].'"> 
      <div class="del_wrapper"> 
       '.$row["name"].' - $'.$row["price"].' 
       <input type="hidden" id="idArea" value="'.$row["id"].'"> 
       <input type="number" id="qtyArea" value="0"> 
       <button id="FormSubmitAddToCart">Add to Cart</button> 
      </div> 
     </li><br />'; 
} 

?> 

而我的響應頁面正在工作並將第一個表單數據發佈到購物車表格。

我知道我需要某種循環或方式來確定使用按鈕提交什麼樣的表單,但不知道如何執行此操作。有什麼建議麼?只是爲了讓你知道,我確保我的東西,我得到它的工作後。謝謝! :d


************************固定碼,工程低於這些LINES ********** ****************


這是完整的更新,現在對我很有用。

腳本代碼

<script type="text/javascript"> 
     $(document).ready(function(){ 
      $('[id^=FormSubmitAddToCart]').click(function(){ 
      // now this is your product id, and now you should 
       var p_id= $(this).attr('id').replace('FormSubmitAddToCart-', ''); 

      // this is your quantity 
       var p_qty = $('#qtyArea-'+p_id).val(); 

      // + now you know the product id and quantity, so you should handle the rest 

       var myData = 'id='+p_id+'&qty='+p_qty; 

       alert(myData); 
      // throw new Error("Something went badly wrong!"); 

       jQuery.ajax({ 
       type: "POST", // HTTP method POST or GET 
       url: "response.php", //Where to make Ajax calls 
       dataType:"text", // Data type, HTML, json etc. 
       data:myData, //Form variables 
       success:function(response){ 
        $("#responds").append(response); 
        $("#idArea").val(''); //empty text field on successful 
        $("#qtyArea").val(''); //empty text field on successful 
        $("#FormSubmitAddToCart").show(); //show submit button 
        $("#LoadingImage").hide(); //hide loading image 

       }, 
       error:function (xhr, ajaxOptions, thrownError){ 
        $("#FormSubmitAddToCart").show(); //show submit button 
        $("#LoadingImage").hide(); //hide loading image 
        alert(thrownError); 
       } 
       }); 

      }) 
     }); 
    </script> 

表單代碼提交:

<?php 
    include_once("config.php"); 

    $results = $mysqli->query("SELECT * FROM products"); 
    while($row = $results->fetch_assoc()) { 
     echo '<li id="item_'.$row["id"].'"> 
       <div class="del_wrapper"> 
        '.$row["name"].' - $'.$row["price"].' 

        <input type="hidden" id="idArea-'.$row["id"].'" value="'.$row["id"].'"/> 
        <input type="number" id="qtyArea-'.$row["id"].'" value="0"> 
        <button id="FormSubmitAddToCart-'.$row["id"].'">Add to Cart</button> 
       </div> 
      </li><br />'; 
    } 

?> 

response.php頁

<?php 
//include db configuration file 
include_once("config.php"); 

if(isset($_POST["qty"]) && ($_POST["qty"] != 0)) { 
    //check $_POST["content_txt"] is not empty 

    //sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH Strip tags, encode special characters. 
    $MID = "43"; 
    $ID = $_POST["id"]; 
    $QTY = $_POST["qty"]; 

    echo $ID.$QTY; 

    // Insert sanitize string in record 
    //$insert_row = $mysqli->query("INSERT INTO add_delete_record(content,qty) VALUES('".$contentToSave.",".$QTY."')"); 

    $insert_row = $mysqli->prepare('INSERT INTO orders(members_id, product_id, quantity) VALUES (?,?,?)'); 
    $insert_row->bind_param('iii', $MID, $ID, $QTY); 
    $insert_row->execute(); 
    $insert_row->close(); 

    if($insert_row) 
    { 
     //Record was successfully inserted, respond result back to index page 
      $my_id = $mysqli->insert_id; //Get ID of last inserted row from MySQL 
      echo '<li id="item_'.$my_id.'">'; 
      echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$my_id.'">'; 
      echo '<img src="images/icon_del.gif" border="0" />'; 
      echo '</a></div>'; 
      echo $ID.'-'.$QTY.'</li>'; 
      $mysqli->close(); //close db connection 

    }else{ 

     //header('HTTP/1.1 500 '.mysql_error()); //display sql errors.. must not output sql errors in live mode. 
     header('HTTP/1.1 500 Looks like mysql error, could not insert record!'); 
     exit(); 
    } 

} 
?> 
+0

首先,如果所有有用戶設定的ID的問題,因爲你使用qtyArea和idArea一個循環中,所以兩個元素的ID將是相同的。 – 2014-12-19 05:26:07

+0

這就是我遇到的問題。我嘗試使用產品ID添加到該按鈕ID,這樣它將是一個唯一的ID,如,但我不是確定後要做什麼。 – logicK 2014-12-19 05:28:33

+0

@你可以檢查答案 – 2014-12-19 06:35:11

回答

0

你的HTML看起來應該像這樣。

  <input type="hidden" id="idArea-'.$row["id"].'" value="'.$row["id"].'"> 
          <input type="number" id="qtyArea-'.$row["id"].'" value="0"> 

          // + javascript 

          $(document).ready(function(){ 
           $('[id^=FormSubmitAddToCart]').click(function(){ 
           // now this is your product id, and now you should 
            var p_id= $(this).attr('id').replace('FormSubmitAddToCart-', ''); 

           // this is your quantity 
            var p_qty = $('#qtyArea-'+p_id).val(); 

            // + now you know the product id and quantity, so you should handle the rest 

           }) 
          }); 
+0

好的先生,你的代碼工作。我只需要在我的最後調整一些東西,這是光榮的!非常感謝!對於任何需要查看完整代碼的人,我將編輯我的問題並將其發佈到我原來的所有內容之下。希望它能幫助你一次看到它。 – logicK 2014-12-19 17:16:01