简体   繁体   中英

Unable to obtain php variable using ajax request

I have a php file with a variable $consult_id obtained from DB as follows:

$consult_id = $row['consult_id'];   

The same php file includes at the bottom another file 2 which includes both php and JavaScript. The relevant code is:

$http({
method: 'get',
url: 'inc/token.inc.php'
}).then(function(response) {
//alert(response);
data = JSON.parse(response);

The token.inc.php file referenced in the above code in file 2 is as follows:

$apiObj = new MYAPI(API_KEY, API_SECRET);
$sessId = $consult_id;
$connectionData = $name; 
$token = $apiObj->generateToken($sessionId , array(
    'data'       => $connectionData
));
$dresponseData = array(
        'sessionId' => trim($sessId),
        'token'=>trim($token)
    );

echo json_encode($dresponseData);

If i hardcode the string in the following it works perfectly:

$sessId = XXXXXXXXXX; //insead of $consult_id

I tried the following and lot other things without success:

$sessId = json_encode($consult_id,JSON_HEX_TAG);

The $sessId always gives null

I know it has something to do with "ajax and php" but being a newbie could not identify the issue.

Hardcoding the string works fine.

The token.inc.php file is a separated file. The variable $consult_id is being defined in another file so even if you have an ajax request - it's doesn't relate to the php's variable's scope .

If you'd include the token.inc file with PHP command (like: include/require ) - then, it would be possible to access that variable.

What you need to do is to use the data parameter in your ajax request (as I've suggested in the comment) and pass that variable to the other file.

JS:

$http({
method: 'post', //changed to post
data: {consultId: '<?php echo $consult_id; ?>'}, //added the 'data' parameter
url: 'inc/token.inc.php'
}).then(function(response) {

In the token.inc.php file:

$sessID = $_POST['consultId'];

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