0

I have a global variable that I want to pass into Ajax. Ajax is very new to me and I've done some research and testing but I am stuck. I don't know if the variable is being passed into the Ajax function for my first question.

I'm not really interested in Json, however I did also make an attempt with that and it's not correct either.

I am not looking to get a response from the php back to the page, the page is updating using the existing js and html.

My second dilemma is that my php file is being activated when it should, however it's posting 0 into the database field. Another problem here too is that it's updating all users money to this same 0 entry so some how it's isset is not set correctly yet. I believe my bindValue is coded correctly, I am really unsure if I need to break down the POST to the php page and if so if I have to use the value, how would I do that? Also when I add WHERE userid = userid to UPDATE the game stalls completely.

Any help even a small fix would be greatly appreciated.

Here are the files. Thank you in advance for helping me get my head around Ajax.

game.js

money = 2000;

function updateMoney() {
   if ( pot <= 0 ){ 
   if ( money <= 0 ){ 
   document.getElementById("aaa").innerHTML = "Lost? Here's A Loan !!!";
      money = 1000 ;}
  }
   document.getElementById("money").innerHTML = money;
  }
  




function enterWager(){  // doMath function inside here
var x=parseInt(document.getElementById('textbox').value,10);  // Displays the textbox for placing a 
wager
   if (money <= 0) {
      x = 0 ; }
document.getElementById("bet").innerHTML = parseInt(x,10);
if(isNaN(x)||x < 1 || x > 250)
{
document.getElementById("aaa").innerHTML = "You're Out Of Money!!!";
}
    document.getElementById("textbox").style.display = 'none';
    document.getElementById("button").style.display = 'none';
    
    


function doMath() {  //   PVPCoinTransaction()   and   
transferCoins()  are off right now. Plus 4 tests failed 
and 
are also off at end of function.

   if (pot == 0){
       countWagers = 0;
   }
   
   if (money <= 0) {
      money = 0 ; }
   if (x > money) {
      x = money ; }
  money = money - x;
  pot = pot + x;
                 }


doMath()


function updateDatabase() {   

// POST test not working
//    $.ajax({
//     url: 'php/credits/credit.php', // 
//     type: "POST",
//     dataType:'json', // add json datatype to get json
//     data: ({money: 145}),  Do I put div here and how?
//     success: function(data){
//   I dont need to return anything, just update db field!
//     }
//}); 


// this section reaches php but posts 0 into database field
//data = money // I don't think this is working.
if (window.XMLHttpRequest) { // Mozilla, Safari, ... 
  xml = new XMLHttpRequest(); 
  } else if (window.ActiveXObject) { // IE 8 and older  
  xml = new ActiveXObject("Microsoft.XMLHTTP");  
  }
xml.open("POST", "../php/credits/credit.php", true);
xml.setRequestHeader("Content-type", "application/x- 
www-form-urlencoded");
xml.send(money);
}



updateMoney()
updateDatabase()

credit.php

<?php 
session_start();
if(empty($_SESSION['userid']))    // check user login
{
    header("Location: ../login/index.php");
}
include('../../login/database.php');

if (isset($_SESSION['userid'])) {
//  $money = null;
//  $money = $_POST['money'];

try {
$db = DB();
header("Content-Type: application/json"); 

$stmt = $db->prepare("UPDATE usersystem SET money=:money");
$stmt->bindValue(':money', $_POST['money'], PDO::PARAM_STR);
$stmt->execute(); 

}
catch(PDOException $e)
{
    $db = null;  
    echo $e->getMessage();  
}
}
?>
Ed Nolan
  • 62
  • 7

3 Answers3

0

Your server expects a key called money in your $_POST array. This means that in order to receive the data properly you need to send the data with a key as well. In PHP this data looks like an associative array and in JavaScript as an object, both having keys and values.

The easiest way to accomplish a key-value structure is to create a string with a key=value structure. This is similar to how forms send their data to servers and requires no modification on the backend for receiving the data.

var package = `money=${money}`;

There is nothing wrong with XMLHttpRequest (there is with ActiveXObject ;) ), I would recommend to learn the Fetch API. It is an updated and simplified specification of making HTTP requests to and from the server. You've indicated that you don't need to receive a response, that means that a basic POST request with sending data looks like the example below.

fetch('../php/credits/credit.php', {
  method: 'POST',
  body: package
});

The first parameter is the URL, the second an options object. The method property speaks for itself. The body property is the data you're sending (comparable to xml.send(package);).

Now if your URL is correct then an HTTP request with the correct data should be send to your server.

// $_POST should have received data, and because you've send it as a
// key-value it will be represented as an associative array with, 
// you guessed it, keys and values.
$money = $_POST[ 'money' ];

// $money will always be a string in this form, so you'll 
// need to convert it if you need it to be a number.
$money_as_number = intval( $money );

To test if this works open the network tab in the developer tools of your browser. You can check if an HTTP request occurs and checkout if the correct payload has been sent.

Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32
  • Thank you for the kind reply. I will try and implement this and look into Fetch. – Ed Nolan Nov 08 '20 at 01:23
  • Your code vs my code trips me up - string. Your code looks backwards. "to accomplish a key-value structure is to create a string with a key=value structure. var package = `money=${money}`; " I see global 'money = 2000' is being passed into your fetch code as ${money} and then you are converting it to 'money' and then passing that too 'package'. But I also see that 'money' is my database field and is being populated by ${money}. Do I have to do more now with my php file since I am now passing package to it? Or do I have to convert like, var ${money}=money? – Ed Nolan Nov 08 '20 at 16:50
  • The `money=${money}` is using string interpolation. That means that the result will be a string that could look like `"money=2000"`. It's the same as doing `"money=" + money` where you combine the string with a number. The former is a newer syntax called [Template Literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals). You could pass that string straight to the `body` property, but I figured it would give more context to store it in a variable called `package` to show you how the data is sent. – Emiel Zuurbier Nov 08 '20 at 17:34
  • The PHP side should now see that the `$_POST` variable has received data (because it won't be empty). And because your data is now structured you can select it with `$money = $_POST[ 'money' ]`. However the value will be a string, so you may need to add some conversion if you want it to be a number. – Emiel Zuurbier Nov 08 '20 at 17:36
0

Okay so this is what works in the console ...

function updateDatabase() { 

var package = money;
console.log(package);
fetch('../php/credits/credit.php', {
  method: 'POST',
     headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
  body: JSON.stringify(package)

});
}

console log = 1975 game.js:1608:9

I just need the 1975 value to post to the database via my php now. it's still posting 0 into my database.

Ed Nolan
  • 62
  • 7
0

I solved it. Thank you for setting me on the right path!

<?php 
session_start();
if (isset($_SESSION['userid'])) {
 $money = json_decode(file_get_contents('php://input'), true);
 $money_as_number = intval( $money );
 $userid = $_SESSION['userid'];
try {
$db = DB();

$stmt = $db->prepare("UPDATE usersystem SET money=:money WHERE userid=:userid");
$stmt->bindValue(':money', $money_as_number, PDO::PARAM_INT);
$stmt->bindValue(':userid', $userid, PDO::PARAM_STR);
$stmt->execute();

}
    catch(PDOException $e)
    {
        $db = null;  
        echo $e->getMessage();  
    }
    }
    ?>
Ed Nolan
  • 62
  • 7