简体   繁体   中英

How to put the ajax response/result into variable php

Can I put the ajax response into variable? So that I can echo the variable into php?

ajax.php

<script>
function random_no(){
    $.ajax({
        url: "test.php",
        success: function(result){
            $("#random_no_container").html(result);//the result was displayed on this div
        }
    });
}
</script>

On my sample code above, i call the query result from test.php and the result was displayed on the div but i want to put that on the variable and echo the variable. something like the code below

<?php echo $variable;?>

Can this possible? please help me. Thank you so much.

You can't PHP is executed on server and Ajax from the client so you cannot assign PHP variable an ajax response. Once a PHP is rendered on the client side it is just HTML no PHP code.

    function random_no(){
        $.ajax({
            url: "test.php",
            success: function(result){
               var result_val=result;
               alert(result);            
            }
        });
    }

As @dev answered , you need to execute server and client code differently ! I answered here for your need variable only .But in developing website, should not use javascript in php tag <?php ?>

ajax.php

<div id="random_no_container">
    <?php
     if(isset($_GET['variable'])) {
        $variable = $_GET['variable'];
        echo $variable;
     } else {
        echo "<script>sessionStorage.setItem('stopped',0);</script>";
     }
     ?>
</div>
<script>
var stopped = sessionStorage.getItem("stopped");
if(stopped == 0) {
    random_no();
}
function random_no(){
    $.ajax({
        url: "test.php",
        success: function(result){
            sessionStorage.setItem("stopped",1);
            //$("#random_no_container").html(result);//the result was displayed on this div
            location.href = "ajax.php?variable="+result;
        }
    });
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM