2
 function submitID(){

 // some codes working in here....

var text="A_1";                 
var name="test";

$.ajax({
    url: 'callmethod.php',
    type: 'post',
    data: {'action':'methodname', 'text': text, 'name':name},
            success: function(data, status) {
            var results = JSON.parse(data);

            for(var i = 0; i < results.length; i++){
                var id= results[i]['ID'];
                alert(id);  --- I got the value of ID in here -- example output value : Hello                                                                       
            }
        },
        error: function(xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
        }
    });
}

What I would like to do in here, I got the value of var id but I want to set as the PHP variable $valuephp= >>> id <<< how can I do for that? please help me to advice.

hungrykoala
  • 1,083
  • 1
  • 13
  • 28
Siamon
  • 83
  • 1
  • 13
  • Possible duplicate of [how to assign javascript variable value to php variable](https://stackoverflow.com/questions/21620133/how-to-assign-javascript-variable-value-to-php-variable) – Amit Kumar Oct 13 '17 at 05:50
  • 1
    you cannot assign a JS variable to a PHP variable since that would be a security risk. You could, however, set the PHP variable in your `callmethod.php` you might set a session variable if you want it to be accessible globaly. – hungrykoala Oct 13 '17 at 05:54

3 Answers3

1

In short, its not possible, like that to set ajax response to php variable because

PHP runs - Server Side before page load and builds the page
JS (and thus AJAX) runs - Client Side AFTER the server gave your browser the page

So what you can do ?

  • You post data to your server with your ajax call, so in server side, you can set php variable.You can store this in a session variable if you need it later, or in the database.
Martijn
  • 15,791
  • 4
  • 36
  • 68
Akshay Hegde
  • 16,536
  • 2
  • 22
  • 36
0

You can store ajax result in php variable by embedding ajax result div into php tag.

Assign ajax response variable to js variable and then just assign it to your html div containing php variable as:

$('#result').text('test');


<?php
 $result='<div id="result"></div>';
// Here you embed div in php tag and store in php varible
?>
-1

In your ajax call, after success or error

<?php   $variablephp = "<script>document.write(111)</script>"   ?> 

Now you can access that variable, make sure that variable actually used after ajax call

<?php echo $variablephp; ?>
shashi
  • 281
  • 1
  • 13