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.
-
stackoverflow.com/questions/8859401/…Viet Nguyen– Viet Nguyen2017年08月25日 03:58:46 +00:00Commented Aug 25, 2017 at 3:58
3 Answers 3
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.
3 Comments
function random_no(){
$.ajax({
url: "test.php",
success: function(result){
var result_val=result;
alert(result);
}
});
}
1 Comment
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>