Fatal error: Call to a member function get_results() on a non-object (jQuery From Plugin & WordPress)

Laxmidi picture Laxmidi · Sep 22, 2011 · Viewed 34.1k times · Source

I'm trying to use jQuery's Form plugin with in a Wordpress plugin. I'm following this example. I've enqueued my scripts and built my form. In csf_form_handler.php, the equivalent of the example's json-echo.php, I can access the items selected in my form (I have a radiobutton group).

My goal is to use the values selected in the form in a SELECT statement to return data from a custom wordpress database table.

$csf_selected_sport = $_POST['csf_radiobutton_group_sport'];

global $wpdb;

$csf_db_table = $wpdb->prefix . "activity";


$csf_data = $wpdb->get_results($wpdb->prepare("
            SELECT *
            FROM " .$csf_db_table. "
            WHERE  " . $csf_selected_sport ." ")); 

Unfortunately, I'm getting:

Notice: Trying to get property of non-object (on the $wpdb->prefix line)

Fatal error: Call to a member function get_results() on a non-object (on the $csf_data line)

The code above in csf_form_handler.php isn't in a function. I don't know if that makes a difference.

How can I change the code so that I can use $wpdb?

Thank you.

Answer

Umar Niazi picture Umar Niazi · Nov 21, 2012

I came across the same issue but I got it resolved by including the wp-config.php file from the root of the WordPress folder like this:

require_once('../../../wp-config.php');
global $wpdb;

I hope this helps.