Aurelijus Aurelijus - 4 months ago 15
Ajax Question

How to pass input value to PHP? Updated 2016-08-02

I can't find problem in my code... P.S When i change $wonorlose in won.php,lose.php to any number it works perfect but adds not that number of money i want, if i change it to $wonorlose = $_GET['wonorlose']; that should get my input value not working :/

Here all my system:



dice.php(main php):

<?php
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user']))
{
header("Location: /manopuslapis/index.php");
}
$res=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<br>
<h3 id="satoshitext" align="center">Money: <?php echo $userRow['money'];
?></h3>
<br>
</form>
<script>
function rollTail(){
var die1 = document.getElementById("die1");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random() * 2) + 1;
if(d1 == 1)
{
die1.innerHTML = "You won!";
fliped.innerHTML = "Fliped Tail!";
var ajax = new XMLHttpRequest();
ajax.open('POST','won.php',true);
ajax.send();
}
else if (d1 == 2)
{
die1.innerHTML = "You lose!";
fliped.innerHTML = "Fliped Head!";
var ajax = new XMLHttpRequest();
ajax.open('POST','lose.php',true);
ajax.send();
}
}
function rollHead(){
var die1 = document.getElementById("die1");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random() * 2) + 1;
if(d1 == 1)
{
die1.innerHTML = "You lose!";
fliped.innerHTML = "Fliped Tail!";
var ajax = new XMLHttpRequest();
ajax.open('POST','lose.php',true);
ajax.send();
}
else if (d1 == 2)
{
die1.innerHTML = "You won!";
fliped.innerHTML = "Fliped Head!";
var ajax = new XMLHttpRequest();
ajax.open('POST','won.php',true);
ajax.send();
}
}
</script>
<div id="fliped" class="fliped"> </div>
<div id="die1" class="dice"> </div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<button id="Head" onclick="rollHead()">Head</button>
<button id="Tail" onclick="rollTail()">Tail</button>
<br>
<br>
<br>
<h2 align="center"><form method="get" >
<input type="text" id="wonorlose" name="wonorlose" value=50>
</form>
</h2>
</body>
</html>


won.php:

<?php
session_start();
include_once 'dbconnect.php';

if(!isset($_SESSION['user']))
{
header("Location: /manopuslapis/index.php");
}
$res=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);

$wonorlose = $_GET['wonorlose'];
echo $wonorlose;
mysql_query("UPDATE `users` SET money=money+'$wonorlose' WHERE user_id=".$_SESSION['user']);
?>


lose.php:

<?php
session_start();
include_once 'dbconnect.php';

if(!isset($_SESSION['user']))
{
header("Location: /manopuslapis/index.php");
}
$res=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);

$wonorlose = $_GET['wonorlose'];
echo $wonorlose;
mysql_query("UPDATE `users` SET money=money-'$wonorlose' WHERE user_id=".$_SESSION['user']);
?>

Answer

I had a spare 1/2 hour so I quickly put this together in the hope it might help solve your problems. Potentially there are problems with allowing a user to specify things like the value or prize so much of that should be handled serverside. This code populates a session variable to track winnings etc and sends back json data for the ajax callback - this is simply for example ~

<?php
    session_start();

    if( $_SERVER['REQUEST_METHOD']=='POST' ){

        ob_clean();

        if( !isset( $_SESSION['coins'] ) ) $_SESSION['coins']=array('attempts'=>0,'total'=>0);

        $_SESSION['coins']['total'] += $_POST['prize'];
        $_SESSION['coins']['attempts']++;

        $_POST['total']['total']='£'.$_SESSION['coins']['total'];
        $_POST['total']['attempts']=$_SESSION['coins']['attempts'];

        /*
            -----------------------
            Example db and sql code
            -----------------------
            $host   =   'localhost';
            $uname  =   'root';
            $pwd    =   'xxx'; 
            $db     =   'xxx';

            $db=new mysqli( $host, $uname, $pwd, $db );
            $sql='update `users` set `money`=? where `user_id`=?;';

            $stmt=$db->prepare( $sql );
            $stmt->bind_param( 'is', $_POST['prize'], $_SESSION['user'] );
            $res=$stmt->execute();
            $db->close();
            $db=null;
        */

        header('Content-Type: application/json');
        exit( json_encode( $_POST ) );
    }
?>
<!doctype html>
<html>
    <head>
        <title>CoinToss Game</title>
        <script type='text/javascript' charset='utf-8'>
            function tosscoin(e){
                var i,msg,result;

                var prize=parseFloat( document.getElementById('wonorlose').value );
                var results=document.getElementById('results');

                var el=e.target;
                var type=el.dataset.type;
                var i = getrandom(0,1);

                msg=( i==1 ? 'You won' : 'You lost' );
                prize=( i==1 ? prize : prize * -1 );

                switch( type ){
                    case 'heads':
                        result=( i==1 ? 'Flipped Heads!' : 'Flipped tails!'  );
                    break;
                    case 'tails':
                        result=( i==1 ? 'Flipped Tails!' : 'Flipped heads!' );
                    break;
                }
                ajax.call( this, 'post', location.href, { i:i, prize:prize, result:result, msg:msg, type:type }, cbcointoss,{ target:results } );
            }

            function cbcointoss(r,o,h){
                var json=JSON.parse(r);
                o.target.innerHTML=[json.msg+' '+json.result,json.total.total].join(', ');
            }

            function getrandom(min,max){
                return Math.floor( Math.random()*( max-min +1 ) + min );
            }

            function ajax(m,u,p,c,o){
                /*
                    Method,Url,Params,Callback,Options
                */
                var xhr=new XMLHttpRequest();
                xhr.onreadystatechange=function(){
                    if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
                };

                var params=[];
                for( var n in p )params.push(n+'='+p[n]);

                switch( m.toLowerCase() ){
                    case 'post': p=params.join('&'); break;
                    case 'get': u+='?'+params.join('&'); p=null; break;
                }

                xhr.open( m.toUpperCase(), u, true );
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                xhr.send( p );
            }

            function bindEvents(){
                var col=document.querySelectorAll('input[type="button"]');
                if( col ){
                    for(var n in col)if(col[n].nodeType==1){
                        col[n].addEventListener('click',tosscoin,false);
                    }
                }
            }
            document.addEventListener( 'DOMContentLoaded', bindEvents, false );
        </script>
        <style type='text/css' charset='utf-8'></style>
    </head>
    <body>
        <form name='cointoss' method='post'>

            <input type='button' data-type='heads' value='Heads' />
            <input type='button' data-type='tails' value='Tails' />
            <input type="text" id="wonorlose" name="wonorlose" value=50>

            <span id='results'></span>
        </form>
    </body>
</html>