我正在编写一个网站,需要更新用户信用,以便在点击按钮时将javascript值添加到数据库中的现有信用,我似乎无法找到如何做到(我是非常新的ajax所以很容易......)
HTML:
<form method="post">
<input id="depositBtn" type="submit" value="Deposit">
</form>
的jQuery
$( "#depositBtn" ).submit( function() {
$.ajax({
url: 'deposit.php',
dataType: 'json',
type: 'post',
data: {total: tot},
success: function(data) {
alert(data);
}
});
});
PHP
$db = new PDO('mysql:host='.$servername.';dbname='.$dbname.';charset=utf8', $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$getCredits = $db->prepare("SELECT credits FROM userinfo WHERE steamid = ? ");
$getCredits->bindParam(1, $steamid, PDO::PARAM_INT);
$credits = $getCredits->fetch(PDO::FETCH_ASSOC);
$allcredits = $credits['credits'];
$bank = $_POST['total'];
$result = array(
'success' => true,
'credits' => $bank+$allcredits
);
echo json_encode($result);
答案 0 :(得分:1)
您的编码似乎没有太大问题,特别是关于您放置的JavaScript!
但我建议你:
(假设:您的提示框显示成功阻止服务器的响应。)
$( "#depositBtn" ).submit( function(e) {
e.preventDefault();
console.log('total : '+tot);
$.ajax({
url : 'deposit.php',
type : 'POST',
dataType : 'json',
data : {total: tot},
success : function(data) {
alert(data);
}
});
});
我对您的代码的更改是:
第一次更改:
$( "#depositBtn" ).submit( function(e) { // you catch the submit button click event.
e.preventDefault(); // you prevent the default event of the submit button
第二次更改:
console.log('total : '+tot); // which will print your 'tot' variable to web browser
// console before it is sent to your PHP Script.
第3次变更:
type : 'POST', // You have put 'post' for the type.
有关防止默认事件的进一步阅读read the following question thread!
注意:
在将JS变量发送到以任何语言编写的任何服务器端脚本之前,不要忘记检查它们。 (PHP,Java,Rubi,...)
希望这有帮助!
干杯!