简体   繁体   中英

cannot get php global variables using ajax

if(!isset($_GET['t'])){$table = 'notes';}
else{$table = $_GET['t'];}

$cats = $table . '_cats';

include 'test.php';

test.php

test(); // works fine

if(isset($_POST['fn'])){
    $_POST['fn']();
}

function test(){
    global $cats, $table;
    echo $cats;
    echo $table;
}

js

$(document).on('click', '.atitle', function(){
    $.post('test.php', {fn: 'test'}, function(data){
        console.log(data); // empty
    });
});

I'm expecting $cats and $table written in console

Any help?

As your first file name is a_notes.php then call a_notes.php from ajax. You are defining $cats, $table in a_notes.php not in test.php .

$(document).on('click', '.atitle', function(){
    $.post('a_notes.php', {fn: 'test'}, function(data){
        console.log(data);
    },'json');// set dataType as json
});

Also in test.php , As you are calling a function test() then echo returned value of function.

echo test();

if(isset($_POST['fn'])){
    $_POST['fn']();
}

function test(){
    global $cats, $table;
    return json_encode(["cats"=>$cats,"table"=>$table]);
}

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