0

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.

asked Aug 25, 2017 at 3:56
1

3 Answers 3

2

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.

answered Aug 25, 2017 at 3:58
Sign up to request clarification or add additional context in comments.

3 Comments

Hello my friend. Thank you for your response. So what should I do? what is the option of this?
This is what i want to happen. I want to display or put the ajax response inside the javascript ----> data: [<?php echo $variable; ?>]
It's not possible as on client you cannot execute PHP codes. Why you want that? If you want any server side processing you can send to another PHP page and get that result again from Ajax.
0
 function random_no(){
 $.ajax({
 url: "test.php",
 success: function(result){
 var result_val=result;
 alert(result); 
 }
 });
 }
Nigel Ren
57.3k11 gold badges49 silver badges59 bronze badges
answered Aug 25, 2017 at 6:29

1 Comment

Hello Friend. I got this. but i dont want to use alert. i want like this ------------> series: [{ name: 'Present', data: [<?php echo $variable?> ] },
0

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>
answered Aug 25, 2017 at 6:53

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.