O
O
olinapopa2016-08-08 15:44:41
PHP
olinapopa, 2016-08-08 15:44:41

ajax(jquery) - php. passing data (variables) back and forth?

There are two files, index.php and random.php.
From index.php we send ajax data from the form to random,php. back we get html.
How can I make sure that after sending to random, some variables are sent back to the index from there?

INDEX.PHP

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1251" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script type="text/javascript">


        function AjaxFormRequest(result_id,form_id,url) {
            jQuery.ajax({
                url:     "random.php", //Адрес подгружаемой страницы
                type:     "POST", //Тип запроса
                dataType: "html", //Тип данных
                data: jQuery("#"+form_id).serialize(),
                success: function(response) { //Если все нормально
                    document.getElementById(result_id).innerHTML = response;
                    var serverAnwer =  '<?php echo $number;?>';
                },
                error: function(response) { //Если ошибка
                    document.getElementById(result_id).innerHTML = "Ошибка при отправке формы";
                }
            });
        }

    </script>
</head>
<body>
<div id="result_div_id">
    Поиграем?<br/>
    <br/>
    Введите число от 1 д 10.
</div>
<br/><br/>
<form method="post" action="" id="form_id">
    <input type="text" name="number"  /><br/>

    <input type="button" value="Играем!" onclick="AjaxFormRequest('result_div_id', 'form_id', 'random.php')" />
</form>

</body>
</html>
<?php

ЗДЕСЬ ПЕРЕМЕННЫЕ ИЗ RANDOM.PHP

?>


RANDOM.PHP
<?php

if(!empty($_POST['number'])) {
    $number = $_POST['number'];
    $random = rand(1, 10);
    if($number == $random) {
        echo "Выпало число: $random";
        echo "<br>Вы выиграли!";
        global $number;
        return true;
    } else {
        echo "Выпало число: $random";
        echo "<br>Проиграли";
        global $number;
        return false;
    }
}
else {echo "Не заполнили форму";}


?>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey ZSA, 2016-08-08
@serjikz

You can just deduce variables. Or do you need to be able to access these variables from js after they are returned from php?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question