I have written a Wordpress plugin which generates content for a page, then tries to call Update.php via jQuery.load to refresh the results. For example:
Plugin generates this content:
global $wpdb;
$sql = "SELECT * FROM table ORDER BY id;";
$results = $wpdb->get_results($sql);
<div id="content">Database Results Here Via Loop</div>
jQuery calls Update.php:
<script type="text/javascript">
$(function() {
var refresh = setInterval(function() {
$("#content").load("Update.php");
}, 5000);
});
Update.php contains:
<?php
function update_page() {
global $wpdb;
$sql = "SELECT * FROM table ORDER BY id;";
$results = $wpdb->get_results($sql);
echo "Parsed results go here";
}
update_page();
?>
After 5 seconds, this results in a 'Fatal error: Call to a member function get_results() on a non-object' on the main page.
If I simply make Update.php return something like rand(), then it works fine and updates the div with a random number. However, if I attempt to include the header that defines all the Wordpress classes (i.e. $wpdb) in the Update.php file (e.g. require_once("wp-blog-header.php");) then the AJAX simply stops working altogether, and won't even return a rand(), yet it will prevent the fatal error mentioned above from occurring.
I am completely lost. Any help or just pointing me in the right direction would be greatly appreciated. Thank you in advance, kind sirs.
you are calling update.php file using ajax so wordpress is unable to load other its files so it is not finding $wpdb objects definition so you need to do is require_once the wp-config.php and wp-includes/wp-db.php files
and create an object as
$wpdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
before the function update_page();