I'm creating an application in PHP for Wordpress and at this point, I'm trying to fetch a value from a database through AJAX every 2 seconds, and I've created a new file with the function that should be fired.
<?php
global $wpdb;
function conta(){
global $wpdb, $table_name;
$count = $wpdb->get_var("SELECT contatore FROM $table_name WHERE email = '$mail'");
echo "$count";
}
conta()
?>
An this function is called here with an XMLHttpRequest Object every 2 seconds
setInterval(function () {
var url = <?php echo json_encode($con); ?>;
var valuereq = new XMLHttpRequest();
valuereq.open("GET", url, true);
valuereq.send();
valuereq.status;
valuereq.onreadystatechange = function () {
if (valuereq.readyState == 4 && valuereq.status == 200) {
var return_data = valuereq.responseText;
document.getElementById("conta").innerHTML = "Executed: " + return_data;
}
else document.getElementById("conta").innerHTML = "Error";
}
}, 2000);
The Http request is executed correctly, but I receive this error:
Fatal error: Uncaught Error: Call to a member function get_var() on null in
C:\xampp\apps\wordpress\htdocs\wp-content\plugins\bittrex-
trader\admin\partials\conta.php:7 Stack trace: #0
C:\xampp\apps\wordpress\htdocs\wp-content\plugins\bittrex-
trader\admin\partials\conta.php(11): conta() #1 {main} thrown in
C:\xampp\apps\wordpress\htdocs\wp-content\plugins\bittrex-
trader\admin\partials\conta.php on line 7
The program is not able to find the global variable $wpdb, even though is declared. This happens only with the AJAX request because if i include directly the file $wpdb is found and working. Is there a reason? Thank you in advance.