Hello, I made sure that my PHP file is working, but unfortunately my ajax code is not. I placed the ajax inside a javascript function to call the file when needed, but when the function is executed nothing happens.
Here is my JS Code:
function countdownEnded() {
//make serverscreen dissapear
document.getElementById('serverScreenWrapper').style.display = 'none';
document.getElementById('serverScreenWrapper').style.opacity = '0';
document.getElementById("cashOutNumTwo").style.right = '150%';
document.getElementById("cashOutNumOne").style.right = '150%';
//start Timer
setInterval(gameTimer.update, 1000);
//make player move again
socket.emit('4');
socket.emit('6');
//make game appear
document.getElementById('gameAreaWrapper').style.opacity = 1;
//play sound
document.getElementById('spawn_cell').play();
//cut 5 cents from account - php function
$.ajax({
type: "POST",
url: 'http://cashballz.net/game/5game/subtract5.php',
data: { },
success: function (data) {
alert(data);
}
});
}
My HTML:
<script src="//code.jquery.com/jquery-2.2.0.min.js"></script>
And even my PHP:
<?php
session_start();
$servername = "localhost";
$username = "myName";
$password = "myPass*";
$dbname = "myDBname";
$cash_amount = $_SESSION['cash_amount'];
// Create connection
$userid = $_SESSION['id'];
// You must enter the user's id here. /\
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch the existing value of the cash_amount against that particular user here. You can use the SELECT cash_amount from users where userid = $userid
$_SESSION['cash_amount'] -= 0.05;
$sql = "UPDATE users SET cash_amount = cash_amount - 0.05 WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $userid);
$result = $stmt->execute();
if($result)
{
echo "5 cents have been subtracted!";
}
else
{
echo mysqli_error($conn);
session_start();
session_unset();
session_destroy();
}
$conn->close();
?>
I don't understand why my file isn't being called.
I have JQuery and i researched quite a bit on AJAX and looked at other similiar questions on this site.
I went to the file link and it works perfectly so i am pretty sure this is a javascript error.
I am great at JS, but a beginner to PHP and JQuery.
Thanks for all your help.
Try modifying your ajax call to include an error handlers. As an example:
$.ajax({
type: "POST",
url: 'http://cashballz.net/game/5game/subtract5.php',
data: { },
success: function (data) {
alert(data);
},
error: function(data) {
alert(data);
}
PHP: header('Access-Control-Allow-Origin: *');
to allow cross domain access.