2012-04-25 91 views
2

我試圖用AJAX和PHP更新我的數據庫。我確定一切都是正確的,只有我的頁面刷新了,沒有插入到我的表格中。用AJAX插入記錄不插入和刷新頁面

HTML

<form id="salary-upd"> 
     <input type="text" class="defaultText" id="monthly-income" name="monthly-income" title="What is your salary?"> 
     <input type="submit" class="salary-upd-submit"> 
</form> 
<div></div> 

AJAX

// UPDATE INCOME 
    $(".salary-upd-submit").click(function() { 
      var elem = $(this); 
      $.post("update_salary.php", elem.parent("#salary-upd").serialize(), function(data) { 
       elem.next("div").html(data); 
      }); 
    }); 

PHP

$uid = $_SESSION['oauth_id']; 
    $monthly_income = $_POST['monthly-income']; 


#update Record 
     $query = mysql_query("SET `income` (user_id, monthly_income) VALUES ($uid, '$monthly_income')") or die(mysql_error()); 

嘗試更新我的PHP,因爲我認爲這可能是...

$query = mysql_query("UPDATE `income` SET (user_id, monthly_income) VALUES ($uid, '$monthly_income')") or die(mysql_error()); 
+3

此壺乞求SQL注入。消除你的輸入! – Quassnoi 2012-04-25 20:07:28

+4

**不要將原始用戶輸入傳遞給SQL。**使用'mysqli_'或'PDO'而不是'mysql_'函數,這些函數已被棄用。 – DCoder 2012-04-25 20:07:46

+0

@DCoder我會歡迎'mysql_'被棄用,但據我所知,他們不是:-( – jeroen 2012-04-25 20:14:10

回答

1

我認爲其他人會解決您的JS方面的問題,而是要傳遞到MySQL查詢您的腳本將無法解析。

嘗試使用這樣的:

$sanitized_monthly_income = mysql_real_escape_string($_POST['monthly-income']); 
mysql_query("INSERT INTO income (user_id, monthly_income) VALUES ('$uid', '$sanitized_monthly_income') ON DUPLICATE KEY UPDATE monthly_income = VALUES(monthly_income)"); 
+0

仍然沒有運氣@Quassnoi – Liam 2012-04-25 20:13:28

+0

@李安:這是非常具有描述性的。 – Quassnoi 2012-04-25 20:14:17

+0

對不起,該頁面犯規顯示任何東西,插進我的數據庫沒有任何事情都不是,生病嘗試放錯誤 – Liam 2012-04-25 20:15:12

0

試試這個:

$(".salary-upd-submit").click(function (e) { 

    e.preventDefault(); 

    var elem = $(this); 
    $.post("update_salary.php", elem.parent("#salary-upd").serialize(), function (data) { 
     elem.next("div").html(data); 
    }); 
}); 
1

爲了避免頁面刷新,我會建議將該操作附加到表單提交處理程序並阻止默認提交事件:

$("#salary-upd").on("submit", function(event) { 
     event.preventDefault(); 
     var elem = $(this); 
     $.post("update_salary.php", $(this).serialize(), function(data) { 
      elem.next("div").html(data); 
     }); 
}); 

編輯:對於舊版本的jQuery,第一行是:

$("#salary-upd").submit(function(event) { 

關於PHP:

  • 使用準備好的語句,以避免SQL注入問題處理,以
  • 使用錯誤看看有什麼問題
+0

我收到'未知系統變量'收入'' – Liam 2012-04-25 20:06:38

0

你是否在點擊按鈕之前dom finis hes加載?我會將這些功能包裝在文檔中,以確保它只在dom完成加載後執行。

add preventDefault防止默認表單提交行爲。除此之外,您可能無法注意到它是通過ajax重新加載的,因爲整個頁面將被隱藏。

$(function(){ 
    $(".salary-upd-submit").click(function(e) { 
     e.preventDefault(); //prevent default submit behavior. 
     var elem = $(this); 
     $.post("update_salary.php", elem.parent("#salary-upd").serialize(), function(data) { 
      elem.next("div").html(data); 
     }); 
    }); 
});