2017-05-13 7 views
0

$ .post jQueryコードを含めると、製品情報がデータベースに挿入されません。しかし、$ .post jQueryコードを削除すると、製品はデータベースに正常に挿入されます。助けてください。jQueryコードにより、製品がデータベースに挿入されなくなる

index.htmlを

<html> 

    <body> 
     <h1>Enter Product Details</h1> 
     <form id = "product_form" method = "post" action = "insert.php"> 
      <input type = "text" id = "n" name = "productname" placeholder = "Product name"></br> 
      <input type = "text" id = "b" name = "brandname" placeholder = "Brand name"></br> 
      <input type = "number" id = "q" name = "quantity" placeholder = "Quantity"></br> 
      <button id = "save_button">Save information</button> 
     </form> 

     <p id = "result"></p> 

     <button id = "btn">Test Button</button> 


     <script type = "text/javascript" src = "js/jquery.js"></script> 
     <script type = "text/javascript" src = "js/script.js"></script> 
    </body> 

</html> 

insert.php

<?php 

    $name = $_POST['productname']; //'productname' is from html input 
    $brand = $_POST['brandname']; //'brandname' is from html input 
    $quantity = $_POST['quantity']; //'quantity' is from html input 

    $con = new mysqli ('localhost', 'root', '', 'tutorial'); 

    if ($con -> connect_error) { 
     echo 'database connect error'; 
    } 

    //Prepare statement to insert into database 
    $stmt = $con -> prepare ("INSERT into products(name, brand, quantity) VALUES (?, ?, ?)"); 
    // Bind the variables to the values 
    $stmt -> bind_param ("ssi", $name, $brand, $quantity); 
    //Execute 
    if($stmt -> execute()){ 
     echo "success"; 
    } 
    else { 
     echo "failure"; 
    } 

?> 

script.js 2番目のパラメータで

$(document).ready(function(){ 

    $('#btn').click(function(){ 
     alert(); 
    }); 

    //The problem code!!!! 
    $('#product_form').submit(function(event){ 
     event.preventDefault();  
     $.post(
      'insert.php', 
      { 
       productname:$("#n").val(), 
       brandname:$("#b").val(), 
       value:$("#q").val(), 
      }, 
      function(result){ 
       if(result == "success"){ 
        $("#result").html("Values inserted successfully!"); 
       } 
       else{ 
        $("#result").html("Error!"); 
       } 
      } 
     ); 
    }); 
}); 
+0

あなたのボタンに 'type =" submit "'コードが動作するようにする必要があると思う ''そうでなければ、ボタンは送信イベントを生成しない – RiggsFolly

+0

@ RiggsFolly私はid = "save_button"を入れます。しかし、まだ挿入されていません。 –

+0

右ですが、ボタンはサブミットイベントを生成せず、タイプ= "サブミット"なしでサブミットイベントをキャッチしようとしています – RiggsFolly

答えて

1

あなたは、サーバーに送信するデータを設定.post $に、あなたは

{ 
    productname:$("#n").val(), 
    brandname:$("#b").val(), 
    value:$("#q").val() 
} 

を持っているので、あなたは伝統的な形式を提出するものと一致が生じるであろうAjaxの提出を持つために、quantity:value:を変更する必要があります。

+0

ありがとうございました!あなたは天才です!!!!! –

関連する問題