简体   繁体   中英

How to pass global variable via ajax

I have three files:

index.php ajax.php function.php

I want to pass a global variable from index.php to function.php via ajax.php . So the alert message in index.php should be "2". But in fact, the result is "1" because function.php does not know the $global_variable .

Here is the code:

index.php

<?php
$global_variable = 1;
?>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
    $.ajax({
        type: "POST",
        url: 'ajax.php',
        success: function(data) {
            alert(data);
        }
    });
</script>

ajax.php

<?php
include 'function.php';

$result = process_my_variable(1);
echo $result;
?>

function.php

<?php
function process_my_variable($new_variable) {
    global $global_variable;
    $result = $global_variable + $new_variable;

    return $result;
}
?>

I do not want to pass the global variable to ajax call, because my real project has many variable like this, and they should not to display because of security.

How to do this?

 $.ajax({
        type: "POST",
        url: 'ajax.php',
        data:{
             global_variable:<?php echo $global_variable?>
        },
        success: function(data) {
            alert(data);
        }
    });

You can send it with data object to ajax.php page

and at ajax.php page you can fetch it by:

<?php
include 'function.php';
$global_var=$_POST['global_variable'];
$result = process_my_variable($global_var);
echo $result;
?>

index.php and ajax.php (with the included function.php ) are different programs . They do not share variables.

You either need to store the data somewhere that both programs can get at it (such as in a SESSION) or pass the data from index.php to the browser, and then send it to ajax.php in the query string or POST body of the Ajax request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM