I
I
Ivan Ivanov2018-04-02 17:55:18
PHP
Ivan Ivanov, 2018-04-02 17:55:18

Why is the script being executed several times instead of once?

Hello! I have a roulette wheel that spins, but there are two problems: firstly, when the user clicks on the button, not 1 request is executed, but several (up to 7+), I set settimeout to execute an ajax request, to execute other parts code but it doesn't help. Also, if you reload the page and click on the button, then the roulette will not spin from the 1st time ((( THANKS
IN ADVANCE Here is wheel.php:

<?php top("Игра \"Колесо фортуны\"")?>
<h1 style="font-size: 35px">Игра Колесо фортуны</h1>
<h1>Ваш баланс:
    <b><?=$_SESSION['balance']?>$</b></h1>
<div class="games">
    <img src="img/str.gif" alt="Стрелка" class="img-responsive center-block">
    <img src="img/wheel.png" alt="Колесо" class="img-responsive center-block wheel" id="wheel"><br>
    <select class="center-block" id="col">
        <option value="0" disabled>Выберите ставку</option>
        <option value="R">Красный</option>
        <option value="B">Черный</option>
        <option value="G">Зеленый</option>
    </select><br>
    <input type="number" id="bet" class="center-block" placeholder="Ваша ставка">
    <br>
    <button class="center-block" id="but" onclick="game()">Крутить</button>
    <p id="p">Выпало: </p>
    <p id="res"></p>
</div>
<?php bottom() ?>

Here is the JS code:
function game() {
        var but = document.getElementById("but");
        var wheel = document.getElementById("wheel");
        wheel.style.transitionDuration = "3s";
        wheel.style.transitionTimingFunction = "ease-in-out";
        but.addEventListener('click', function func() {
            var bet = $("#bet").val();
            var col = $("#col").val();
            but.style.pointerEvents = "none";
            setTimeout(function(){
                

            $.ajax({
                method: "POST", // метод HTTP, используемый для запроса
                url: "game_engine", // строка, содержащая URL адрес, на который отправляется запрос
                data: { // данные, которые будут отправлены на сервер
                    bet: bet,
                    col: col
                },
                success: function(data) {
                    var msg = JSON.parse(data);
                    wheel.style.transform = "rotate(" + msg.deg + "deg)";
                    if (msg.winbet == 0) {
                        setTimeout(function() {
                            $("#res").text("Вы проиграли!");
                        }, 3500);
                    } else if (msg.winbet == 1) {
                        setTimeout(function() {
                            $("#res").text("Вы выйграли!");
                        }, 3500);
                    } else {
                        alert("Ошибка");
                    }
                    setTimeout(function() {
                        $("#p").text("Выпало: " + msg.win); // добавляем текстовую информацию и данные 
                        but.style.pointerEvents = "auto";
                    }, 3500);
            }
            });
        }, 1000);
        });
    }

Here is the game_engine.php file:
<?php
    session_start();
    $login = $_SESSION['id'];
    $bal = (int)$_SESSION['balance'];
    $bet = (int)$_POST['bet'];
    $col = $_POST['col'];
    if($bal<$bet){
        exit("ОШИБКА!");
    }else{
    $vin1 = array(350,349,348,1,'R');
    $vin2 = array(323,325,327,2,'B');
    $vin3 = array(305,307,303,3,'G');
    $vin4 = array(280,282,284,4,'B');
    $vin5 = array(261,262,263,5,'R');
    $vin6 = array(240,238,236,6,'B');
    $vin7 = array(216,215,214,7,'R');
    $vin8 = array(190,192,194,8,'B');
    $vin9 = array(172,170,168,9,'R');
    $vin10 = array(148,146,149,10,'B');
    $vin11 = array(126,124,122,11,'R');
    $vin12 = array(103,101,99,12,'B');
    $vin13 = array(80,82,83,13,'R');
    $vin14 = array(58,56,55,14,'B');
    $vin15 = array(36,35,34,15,'R');
    $vin16 = array(12,13,14,16,'B');
    $roulette = array($vin1, $vin2, $vin3, $vin4, $vin5, $vin6, $vin7, $vin8, $vin9, $vin10, $vin11, $vin12, $vin13, $vin14, $vin15, $vin16);
    $deg = $roulette[rand(0,15)];
    $win = $deg[3];
    if($deg[4] == $col){
        if($deg[4] == 'G'){
            $winbet = 1;
            $newbal = $bal + ($bet*6);
            $text = "Ставка ".$bet.". Выйграна! Дата: ".date("H:i:s")." ".date("m.d.y").". Новый баланс: ".$newbal;
            mysqli_query($CONNECT, "UPDATE `users` SET `balance` = '$newbal' WHERE `id` = '$login'");
            mysqli_query($CONNECT, "INSERT INTO `history` VALUES('', '$login', '$text')");
            $_SESSION['balance'] = $newbal;
            
        }else{
        $winbet = 1;
        $newbal = $bal + $bet;
        $text = "Ставка ".$bet.".Выйграна! Дата: ".date("H:i:s")." ".date("m.d.y")." .Новый баланс: ".$newbal;
        mysqli_query($CONNECT, "UPDATE `users` SET `balance` = '$newbal' WHERE `id` = '$login'");
        mysqli_query($CONNECT, "INSERT INTO `history` VALUES('', '$login', '$text')");
        $_SESSION['balance'] = $newbal;
        }
    }else{
        $winbet = 0;
        $newbal = $bal - $bet;
        $text = "Ставка ".$bet.".Проиграна! Дата: ".date("H:i:s")." ".date("m.d.y").". Новый баланс: ".$newbal;
        mysqli_query($CONNECT,"UPDATE `users` SET `balance` = '$newbal' WHERE `id` = '$login'");
        mysqli_query($CONNECT, "INSERT INTO `history` VALUES('', '$login', '$text')");
        $_SESSION['balance'] = $newbal;
    }
    $deg = $deg[rand(0,2)];
    $deg = $deg + 360*rand(3,5);
    $array = array('deg' => $deg, 'win' => $win, 'winbet' => $winbet, 'newbal' => $newbal);
    $json = json_encode($array);
    exit($json);
    }
?>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
ThunderCat, 2018-04-02
@ThunderCat

This is

<button class="center-block" id="but" onclick="game()">Крутить</button>
and what the hell is this? Why create a click listener on the same element on click?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question