Reputation: 671
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?
Upvotes: 2
Views: 2803
Reputation: 943152
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.
Upvotes: 3
Reputation: 11707
$.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;
?>
Upvotes: 4