Search code examples
javascriptphpfetch-apijsonresponsejsonencoder

Json Response needs to update Javascript value and replace global initial global value - work around solution needed


I'm trying to wrap my head around the fetch api and get. From what i've been studying it looks like its suppose to be easy but my mind isn't getting it fully. In my game Javascript, it starts with a money=2000 global variable.

The game plays fine, but when someone leaves and goes to their profile page and comes back to the game, the game resets and starts the play from the beginning and resets the money back to 2000.

What is really crazy is if I refresh the page I finally see the correct value of 2200 on the web page, which is what is in the database.

startgame.html

<!DOCTYPE html>
<html>
    <head> 
<TITLE>Interactive Game</TITLE>
        <meta charset="UTF-8">
    </head>

    <body background="images/pvpcoinnew.png" style="width=120%" onLoad="updateMoney(); popup('popUpDiv'); click(); updown()" oncontextmenu="return false;">
<img background="images/pvpcoinnew.png">

<select id="textbox">
  <option value="1">1</option>
  <option value="5">5</option>
  <option value="10">10</option>
  <option value="25" selected>25</option>
  <option value="50">50</option>
  <option value="75">75</option>
  <option value="100">100</option>
  <option value="200">200</option>
  <option value="250">250</option>
  <option value="500">500</option>
  <option value="1000">1000</option>
</select> 
    <button type="click" id="button" onclick="enterWager(); return false;">Wager!</button>

    <p>Money: $<span id="money"></span><br></p>


        <script type="text/javascript" src="game.js"></script>

    </body>
</html>

The game.js file below has money preset at the very beginning to 2000. game.js

//money = 2000;
window.money = 2000;
          
fetch('../php/moneyupdate/moneyupdate.php?money=value')
  .then((response) => {
    return response.json()
  })
  .then((money) => {
    // Work with JSON data here
    window.money = money
    console.log(money)
  })
  .catch((err) => {
    // Do something for an error here
  })
  
  
document.getElementById("money").innerHTML = window.money;

When the php file is triggered from the fetch the status is 200. XHR Response Payload comes back with "2200" which is what is in the database, but the web page is still showing 2000.

Here is the moneyupdate.php file

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


if(isset($_GET["money"])) {
  $money = htmlspecialchars($_GET["money"]);
  $userid = $_SESSION['userid'];

try {
$db = DB();
$stmt = $db->prepare("SELECT money FROM usersystem WHERE userid=?");
$stmt->execute([$userid]);
$money = $stmt->fetchColumn();


// send a JSON encded money array to client
header('Content-type: application/json;charset=utf-8');
echo json_encode($money);
//}


}
catch(PDOException $e)
{
    $db = null;  
    echo $e->getMessage();  
}
}
// Notes: The json_encode function returns the JSON representation of the given value. 
//        The json_decode takes a JSON encoded string and converts it into a PHP variable.
?>

Thanks for the help and responding!


Solution

  • When using GET['money'] add this to your url "http:site.com/page.php?money=value". window.money = 2000;

    fetch('../php/moneyupdate/moneyupdate.php?money=2000')
      .then((response) => {
        return response.json()
      })
      .then((money) => {
        // Work with JSON data here
         //working with json data depends on structure 
          // you can access data as money.money
        window.money = money
        console.log(money)
      })
      .catch((err) => {
        // Do something for an error here
      })