1

Why this doesn't work

$(document).on('click', '.title', function(){
    let fn = 'abc';
    $.post('common.php', {fn}, function(data) {
        console.log(data);
    });
});

common.php

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

$cols = '323';

function abc() {
    global $db;  // this works (db connection);
    global $cols;
    echo $cols;  //  doesn't work result is empty
    echo '323';  // this works
}

There is no logic - some global variables work (for example $db connection) and some don't work.

Any help?

5
  • It work in 3v4l.org/p630p But you should use ; after $db Commented Sep 27, 2018 at 6:29
  • @Mohammad, that's not my question. Pls read the title - if function is called using variable. Call abc() using if (isset($_POST['fn'])) {$_POST['fn']();} Typo corrected. Commented Sep 27, 2018 at 6:32
  • 1
    Because when you calling function in first line, $cols doesn't defined. But if you define variable before function call, it work correctly. 3v4l.org/8cUNj Commented Sep 27, 2018 at 6:35
  • it's working here link . are you sure that your function is executed? make sure that your isset($_POST['fn']) is true. Commented Sep 27, 2018 at 6:36
  • @Mohammad, excellent, thanks a lot. Pls place as answer. Commented Sep 27, 2018 at 6:39

1 Answer 1

1

Because when you calling function in first line

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

$cols variable doesn't defined. But if you define variable before function call, it work correctly.

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

function abc() {...

Check result in demo

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.