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);
}
});
filter_input
to get the value of the filtered parameter, but then get it directly? This didn’t make much sense; 2) Its functiongetInscritos
has an encapsulation termpublic
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 functiongetInscritos
, you use the variable$data
, but this is not part of the function return?– Woss
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" }.
– Márcio Cristian