Noodles
Noodles

Reputation: 197

php global variable not updating

I am new to php and ajax. I have a 'test3.php' file where I made a ajax call to another php file, 'test2.php'. In test2.php there is a global variable, and a simple function which changes the value of the global variable.

Once the ajax request finishes I echo the returned data, which is the global variable to make sure that it's value indeed changed. However, when I alert this global variable with php, it's value does not update.

test3.php:

<?php 
include('test2.php');
?>
<html>


<body>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
        $.post('test2.php', { action: 'u', file:'file'},
               function(data){
            alert(data);
            alert('<?php echo $global_var; ?>');
        });
    </script>
</body></html>

test2.php:

<?php 
$global_var = "unchanged";

if(isset($_POST['action'])){
    if($_POST['action'] == 'u'){
        setValue();
        echo $global_var;
    }
}

function setValue(){
    global $global_var;
    $global_var = "changed";
}

?>

If I run test3.php, the first alert returns "changed", the second alert returns "unchanged". Why would this happen? Any help would be greatly appreciated!

Upvotes: 2

Views: 1915

Answers (1)

Matt
Matt

Reputation: 5428

You are outputting client side code from server side code.

The 2nd alert is always going to output the value that $global_var was set to when PHP executed. (Before the client side $.post is executed.)

The way you're doing it with the first alert is generally how you'd want to get the data back.

The 2nd alert would work if this wasn't an ajax request and instead you were posting to PHP directly and receiving a full page refresh from the server.

Upvotes: 1

Related Questions