2016-11-24 217 views
0

我有這樣的形式和Ajax調用我index.php-提交Ajax表單,而不刷新頁面PHP

<form method='post' id='saleForm' > 
    <input type='text' name='addCustomer' class='addInput' id='adlastname' placeholder='customer last name'> 
    <input type='text' name='addYear' class='addInput' id='adYear' placeholder='year'> 
    <input type='text' name='addMake' class='addInput' id='adMake' placeholder='make'> 
    <input type='text' name='addModel' class='addInput' id='adModel' placeholder='model'> 
    <input type='text' name='addGross' class='addInput' id='adGross' placeholder='front gross'> 
    <input type='hidden' name='Id' value='<?php echo $id;?>'> 
    <input type='submit' name='subSale' id='subSale' value='Save' > 
</form> 

<script> 
    $("form").submit(function(e) { 
    var url = "add.php"; // the script where you handle the form input. 

$.ajax({ 
     type: "POST", 
     url: url, 
     data: $("form").serialize(), // serializes the form's elements. 
     success: function(data) 
     { 
      alert(data); // show response from the php script. 
     } 
    }); 

e.preventDefault(); // avoid to execute the actual submit of the form. 
}); 
</script> 

我試圖用add.php將其提交到數據庫 -

$cust = $_POST['addCustomer']; 
$addMake = $_POST['addMake']; 
$addModel = $_POST['addModel']; 
$addYear = $_POST['addYear']; 
$addGross = $_POST['addGross']; 
$subSale = $_POST['subSale']; 
$soldDate = date('m/d/yy'); 

if(isset($subSale)){ 
    $sql = "INSERT INTO `$sold_table` (`Id`,`Customer`, `Year`, `Make`, `Model`, `FrontGross`, `SoldDate`) VALUES (NULL,'$cust', '$addYear', '$addMake', '$addModel', '$addGross', '$soldDate')"; 
    if (mysqli_query($conn, $sql)) { 
     echo 'success!'; 
    } else { 
     echo "Error: " . $sql . "<br>" . mysqli_error($conn); 
    } 
} 

當我點擊保存按鈕時,它顯示空的警報,並且數據不會因爲某種原因而被推送。任何想法我在哪裏出錯?我知道插入是正確的,因爲它工作時,我不使用ajax調用,只使用表單動作..

+0

那麼,你期望輸出是什麼? 你對成功沒有任何迴應。那麼,數據是否到達數據庫? – Digitalis

+0

是的只是試圖獲取數據到數據庫 –

+0

這至少解釋了空警報 – Digitalis

回答

1

當使用jQuery提交表單時,不使用提交按鈕。因此,一旦PHP收到發佈的數據,它就會變成空的。 您的腳本正在檢查$ subSale以執行查詢,該查詢現在失敗。

嘗試提供一個名爲SubSale的隱藏輸入,它將再次工作。另一個解決方案是根據您自己的建議刪除整個if語句。

if(isset($subSale)){ 
+0

完美是啊我剛剛刪除它謝謝你! –

+0

不客氣。快樂的編碼! – Digitalis