2017-01-12 10 views
-1

私は何をしていますか?
jQueryのajax関数を使用してPHPスクリプトを呼び出して、MySqlデータベースにデータを挿入しようとしています。

問題は何ですか?
データがデータベースに2回挿入されます。

HTMLコード:JQuery Ajaxでデータを2回挿入する

<button id="insert">Insert</button> 
<script> 
    $('#insert').click(function(){ 
     $.ajax({ 
      type: "GET", 
      url: 'url-of-php-script-here', 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      cache: false, 
      success: function (data) { 
       alert(data.status); 
      } 
     }); 
    }); 
</script> 

PHPスクリプト:

try { 
    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password); 
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
} 
catch(PDOException $e) 
{ 
    echo "Connection failed: " . $e->getMessage(); 
} 

$custId = $_GET["custId"]; 
$tableId = $_GET["tableId"]; 

try { 
    $statement = $conn->prepare("INSERT INTO reservation_master(cust_id,table_id) VALUES(:custId, :tableId)"); 
    $statement->execute(array(
     "custId" => $custId, 
     "tableId" => $tableId 
    )); 
    $reservId = $conn->lastInsertId(); 
    $result = array("status"=>"reserved", "cust_id"=> $custId , "table_id"=> $tableId, "reserv_id"=> $reservId); 
    echo json_encode($result); 
} 
catch(PDOException $e) 
{ 
    $result = array("status"=>"failed"); 
    echo json_encode($result); 
} 


UPDATE 1
私は、フォームを使用してスクリプトを呼び出すようにしようと、それが正常に働いていました。問題はアヤックスだと思う。私は次のコードを使用しました:

<form method="get" action="url-of-php-script-here"> 

    <input name="custId" type="text"></input> 
    <input name="tableId" type="text" ></input> 
    <input type="submit"></input> 

</form> 

答えて

0

私はcontentType: "application/json; charset=utf-8"を削除して正常に動作しました。 作業コードは次のとおりです。

$.ajax({ 
    type: "GET", 
    url: 'url-of-php-script-here', 
    data: "{}", 
    dataType: "json", 
    cache: false, 
    success: function (data) { 

    } 
}); 
関連する問題