2017-05-13 2 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 두번째 파라미터

$(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

맞아요.하지만 버튼은 submit 이벤트를 생성하지 않고'type = "submit"을하지 않고 submit 이벤트를 잡으려고합니다. – RiggsFolly

답변

1

서버로 보낼 데이터를 설정 .post $, 당신은

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

그래서 당신이 전통적인 양식을 생성 할 것이다 제출 무엇 아약스 제출 일치를 위해, quantity:value:을 변경해야합니다.

+0

정말 고마워요! 너는 천재 야!!!!! –

관련 문제