2

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!

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So the value of '$global_var' did change, correct?
Only within the scope of the ajax request. The variables within Test3 are set in stone once they are processed for the first time. Any variables you reference from your javascript output will be what they were when it originally ran.

Your Answer

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.