javascriptajaxglobal-variablesbind-variablesbindvalue

pass global variable into ajax function, post to php, save to database


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();  
}
}
?>

Solution

  • 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.