Home > Software design >  Passing JS variable value to PHP variable to update database
Passing JS variable value to PHP variable to update database

Time:06-30

If you want to see the part where I tried AJAX, go look down below. It completely messed up the page and I'm stuck on how to do this. I've got some code here:

$id = $_SESSION["id"];
$sql = "SELECT riskcoin FROM klanten WHERE id='$id'";
$INFO=mysqli_query($conn, $sql);
if (mysqli_num_rows($INFO) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($INFO)) {
        echo "riskcoin: " . $row["riskcoin"].  "<br>";
        $riskcoins = $row["riskcoin"];
    }
} else {
   echo "0 results";
}
?>

var dealerHand = [];
var playerHand = [];
var currentHand;
var deck;
var deckCount;
var countCards = true;
var bets = new Bets();


// Bets Object
function Bets() {
   this.pot = <?php echo "$riskcoins"; ?>;
   this.bet = 0;
   $('#bet').text(0);
   $('#pot').text('$'   this.pot);
 }

// Bets methods
Bets.prototype.updateAmounts = function () {
   $('#bet').text('$'   this.bet);
   $('#pot').text('$'   this.pot);
};
Bets.prototype.doubleDown = function() {
   this.pot -= this.bet;
   this.bet  = this.bet;
};
Bets.prototype.potAmount = function() {
    return this.pot;
};
Bets.prototype.betAmount = function(){
    return this.bet;
};
Bets.prototype.disableDeal = function () {
    $('#button-deal').addClass('disabled');
};
Bets.prototype.addBet = function(amount) {
    if (this.pot >= amount) {
        this.pot = this.pot - amount;
        this.bet = this.bet   amount;
        this.updateAmounts();
        $('#button-deal').removeClass('disabled');
    } else {
        notEnoughChips();
    }
};

First part is php second part js. I have an int value in my database called riskcoin. this.pot contains that riskcoin value (//Bets object) and shows itin another php file in a paragraph with id="pot".

When an image is clicked another function ads an amount to the bet depending on the picture (for example 5).

Now my question: after the line this.updateAmounts(); it executes

// Bets methods
Bets.prototype.updateAmounts = function () {
   $('#bet').text('$'   this.bet);
   $('#pot').text('$'   this.pot);

Now my question would be if I could update the riskcoin value in my database with an update query after this function with the current this.pot value? It should show live updates without page refreshes. I've read about AJAX so I tried something like this:

Bets.prototype.updateAmounts = function () {
    $('#bet').text('$'   this.bet);
    $('#pot').text('$'   this.pot);
    window.history.pushState('page2', 'Title', '?coins='   this.pot);
    $(document).ready(function(){
    var url = window.location.href;
    var params = url.split('?coins=');
    var id = (params[1]);
        $("#button-deal").click(function(){ $.ajax({
        type:"POST",
        url:"blackjackgame.php",
        data:{id:id},
        success:function(result){
        $("#pot").html(result);
        }
        });
        });
    });
};

But it for some reason when I click on the deal button (#button-deal) it shows up my login page in the middle of the page under all the other stuff, console gives me: GET http://riskybusiness.nglyceum.eu/games/login.css net::ERR_ABORTED 404 (Not Found)jquery-3.1.1.js:5921

CodePudding user response:

// Bets Object
function Bets() {
   this.pot = <?php echo "$riskcoins"; ?>;
   this.bet = 0;
   $('#bet').text(0);
   $('#pot').text('$'   this.pot);
 }

You cannot put php code inside of javascript as PHP is server side so it runs before javascript.

I believe your best option would be to use php for all of it.

CodePudding user response:

PHP and Javascript execute in different contexts. PHP on the server, Javascript on the client (browser). Keep your PHP code and Javascript separate. Since PHP executes first on the server, you can embed PHP output into your HTML/Javascript/CSS—BEFORE—it is sent to the browser.

One problem you have with your code is intermingling PHP and Javascript, such as:

<?php
if (mysqli_num_rows($INFO) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($INFO)) {
        echo "riskcoin: " . $row["riskcoin"].  "<br>";
        $riskcoins = $row["riskcoin"];
    }
} else {
   echo "0 results";
}
?>

var dealerHand = [];
var playerHand = [];
var currentHand;

// Bets Object
function Bets() {
   this.pot = <?php echo "$riskcoins"; ?>;
   this.bet = 0;
   $('#bet').text(0);
   $('#pot').text('$'   this.pot);
 }

The PHP (only) gets processed on the server, and this text is sent to the client:

riskcoin: 100<br>

var dealerHand = [];
var playerHand = [];
var currentHand;

// Bets Object
function Bets() {
   this.pot = 100;
   this.bet = 0;
   $('#bet').text(0);
   $('#pot').text('$'   this.pot);
 }

Also, this $("#button-deal").click(function(){ in your code adds a click event handler to your button. The problem is, you're not adding this event handler until addBet() is executed, which then executes updateAmount(). Not only don't wait, but the handler is added each time addBet() is executed. Instead add the event handler on page load.


I've separated the various code components into server-side execution and client-side execution contexts, and properly connected them to each other:

blackjack.html

var dealerHand = [];
var playerHand = [];
var currentHand;
var deck;
var deckCount;
var countCards = true;
var bets = new Bets();

// Bets Object
function Bets() {
  this.pot = 100; // <?=$riskcoin?>;
  this.bet = 0;
  $('#bet span').text('$'   0);
  $('#pot span').text('$'   this.pot);
  $('#deal button').addClass('disabled');
}

// Bets methods
Bets.prototype.updateAmounts = function() {
  $('#bet span').text('$'   this.bet);
  $('#pot span').text('$'   this.pot);
};
Bets.prototype.potAmount = function() {
    return this.pot;
};
Bets.prototype.betAmount = function(){
    return this.bet;
};
Bets.prototype.addBet = function(amount) {
  if (this.pot >= amount) {
    this.pot = this.pot - amount;
    this.bet = this.bet   amount;
    this.updateAmounts();
    $('#deal button').removeClass('disabled');
  } else {
    notEnoughChips();
  }
};

// add the click event handler on page load
document.querySelector("#deal button").addEventListener("click", evt => {
  $.ajax({
    type: "POST",
    url: "deal.php", // <-- post data to separate PHP file, see PHP file below
    data: {bet: bets.betAmount()},
    success: function(result) {
      const win = (result > bets.pot)? " (won)": " (lost)";
      bets.pot = result;
      bets.bet = 0;
      $("#pot span").text('$'   bets.pot   win);
      $('#bet span').text('$'   bets.bet);
      $('#deal button').addClass('disabled');
    }
  });
});

document.querySelectorAll("#bet button").forEach(btn => {
  btn.addEventListener("click", evt => {
    bets.addBet(parseInt(evt.target.textContent));
  });
});

function notEnoughChips() {
  alert("Not enough chips.");
}

// mock ajax, remove in real world
$.ajax = (function () {
  return function (params) {
    if (Math.random() < 0.5) {
      params.success(bets.pot   (params.data.bet * 2));
    } else {
      params.success(bets.pot);
    }
  };
}());
.disabled {
  cursor: not-allowed;
  pointer-events: none;
  color: #c0c0c0;
  background-color: #ffffff;
}
<!-- uncomment in the real world
<?php

$id = $_SESSION["id"];
$sql = "SELECT riskcoin FROM klanten WHERE id=?"; // <-- use prepared statements
$INFO=mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
if (mysqli_num_rows($INFO) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($INFO)) {
        $riskcoin = $row["riskcoin"];
    }
} else {
   $riskcoin = 0;
}

?>
-->

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="pot">Pot: <span><?=$riskcoin?></span></div>
<div id="bet">Bet: <span>0</span> <button> 5</button><button> 10</button><button> 15</button><button> 20</button></div>
<div id="deal"><button>Deal</button></div>

deal.php

<?php

// this file called in JQuery ajax function found in "#deal button" "click" handler

$id = $_SESSION["id"];
$bet = $_POST["bet"];

$sql = "SELECT riskcoin FROM klanten WHERE id= ?";
$INFO=mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
if (mysqli_num_rows($INFO) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($INFO)) {
        $riskcoin = $row["riskcoin"];
    }
} else {
   $riskcoin = 0;
}

// random win or lose
$riskcoin  = ((bool)random_int(0, 1))? ($bet * 2): (-1 * abs($bet));

$sql = "UPDATE klanten SET riskcoin = ? WHERE id = ?";
$INFO=mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "ii", $riskcoin, $id);
mysqli_stmt_execute($stmt);

echo $riskcoin;

?>
  • Related