Reputation: 5
I am writing a website that needs to update a users credits so that it adds a javascript value to the existing credits in the database on a button click and I can't seem to find out how to do it (I'm very new to ajax so go easy...)
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);
Upvotes: 0
Views: 355
Reputation: 8134
It seems like there is no much wrong with your coding, specially regarding the JavaScript which you have put!
But I suggest you the following:
(Assuming: that your alert box shows what is the response from the server in the success block.)
$( "#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);
}
});
});
What my change to your code is:
1st Change:
$( "#depositBtn" ).submit( function(e) { // you catch the submit button click event.
e.preventDefault(); // you prevent the default event of the submit button
2nd Change:
console.log('total : '+tot); // which will print your 'tot' variable to web browser
// console before it is sent to your PHP Script.
3rd Change:
type : 'POST', // You have put 'post' for the type.
For further reading on preventing the default events read the following question thread!
Note:
Don't forget to check your JS Variables before you send them to the any server side scripts written in any lang. (PHP, Java, Rubi, ...)
Hope this helps!
Cheers!
Upvotes: 1