I
I
Ivan Ivanov2018-04-01 17:34:37
PHP
Ivan Ivanov, 2018-04-01 17:34:37

How to return AJAX values?

Hello! Can't return values ​​from handler in php.
Here is the php code: (its end)

$array = array('deg' => $deg, 'win' => $win, 'winbet' => $winbet);
    $json = json_encode($array);
    exit($json);

If you just take out what she returned, it will be something like this: {"deg":1452,"win":16,"winbet":0}
Here is the JS code:
function game() {
        var but = document.getElementById("but");
        var wheel = document.getElementById("wheel");
        console.log(wheel);
        wheel.style.transitionDuration = "3s";
        wheel.style.transitionTimingFunction = "ease-in-out";
        but.addEventListener('click', function func() {
            var bet = $("#bet").val();
            var col = $("#col").val();
            $.ajax({
                method: "POST", // метод HTTP, используемый для запроса
                url: "game_engine", // строка, содержащая URL адрес, на который отправляется запрос
                data: { // данные, которые будут отправлены на сервер
                    'bet': bet,
                    'col': col
                },
                success: function(data) { // функции обратного вызова, которые вызываются если AJAX запрос выполнится успешно
                    var msg = data;                 
                    wheel.style.transform = "rotate(" + msg.deg + "deg)";
                    if (msg.winbet == 0) {
                        setTimeout(function() {
                            alert("Вы проиграли!");
                        }, 3500);
                    } else if (msg.winbet == 1) {
                        setTimeout(function() {
                            alert("Вы выйграли!");
                        }, 3500);
                    } else {
                        alert("Ошибка");
                    }
                    setTimeout(function() {
                        $("p").text("Выпало: " + msg.win); // добавляем текстовую информацию и данные 
                    }, 3500);
                }
            });
        });
    }

If, for example, you export msg.deg or msg.winbet, then it returns undefined((( please help, there are no errors in the console.
If you export msg, it will write {"deg": 1452,"win":16,"winbet":0}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
McBernar, 2018-04-01
@McBernar

A string into an object and then access the properties.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question