How to call a specific PHP function with AJAX?

Asked

Viewed 395 times

0

I need to call a specific function inside a PHP file with AJAX. I tried several ways, did searches even here on Stack, but it doesn’t happen at all.

What am I doing:

PHP code:

$functionName = filter_input(INPUT_GET, 'functionName');

if (isset($_GET['functionName']) && !empty($_GET['functionName'])) {

    $functionName = $_GET['functionName'];

    switch ($functionName) {
        case 'getInscritos': 
            getInscritos(); 
        break;
    }

}

public function getInscritos() {

$datas = array();

    $vagas = get_post_meta($this->id, InscricoesPostType::ID . '_vagas');
    $ins = get_post_meta($this->id, InscricoesPostType::ID . '_inscritos');

    foreach ($data as $key => $value) {
        $datas[] = array(
            'vagas' => $vagas[$key],
            'inscritos' => $ins[$key]
        );
    }

    return json_encode(get_post_meta($this->id, InscricoesPostType::ID . '_vagas'));
}

JS Code:

$.ajax({
                type: "GET",
                url: '/../dir1/dir2/dir3/dir4/arquivo.php',
                data: "functionName=getInscritos",
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                success: function(data) {
                    console.log('Função encontrada' + data);
                },
                error: function(data){ 
                    var obj = jQuery.parseJSON(data);
                    console.log('Função não encontrada: ' + obj); 
                }
            });
  • 2
    1. Why do you use filter_input to get the value of the filtered parameter, but then get it directly? This didn’t make much sense; 2) Its function getInscritos has an encapsulation term public in its definition, which implies that it is a method of a class, then could [Edit] the question and add the complete code class? 3) When this JS code is executed, as soon as it loads the page or in some JS event? 4) Why, in function getInscritos, you use the variable $data, but this is not part of the function return?
  • I think one of the things you might be missing is this: data: "functionName=getInscritos"... You are passing wrong, and it should be like this: data: { functionName: "getInscricts" }.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.