0

In main.js, I have a script, which is sending an ajax request to script.php.

$.ajax({
    type: "POST",
    url:  "wp-content/themes/roots/script.php",
    data: registerdata,
    success: function(result)
    {
        alert(result);
    }
});
return false;

script.php validate some data and write the data into the database. For this, I use the $wpdb object by WordPress ($wpdb->insert()). Normally, WordPress provides a global variable, $wpdb, which is an instantiation of the class already set up to talk to the WordPress database. But not in my case. I get the following error

Fatal error: Call to a member function insert() on a non-object

If I do

if(class_exists('wpdb') == false){
    echo 'class wpdb doesnt exist';
}
else{
    echo 'class wpdb exists';
}

in script.php, it told me all the time 'class wpdb doesnt exist'. If I do the same in function.php, class wpdb exists. But why? Script.php and function.php are in the same directory. And $wpdb is auto loaded and set up to global by WordPress. So I have access all the time, doesn't matter in which directory I am, right?!

realpath(ABSPATH . WPINC . '/wp-db.php')

.... also doesnt work. Constants are undefined in script.php, too. Where is my fault? register_globals = on in php.ini. changed nothing. :/

1

To answer your question directly, yes, $wpdb is "auto loaded and set up to global by WordPress" but by loading wp-content/themes/roots/script.php directly you are skipping over the WordPress boot process and loading the file exactly as if WordPress did not exist. That is why the normal WordPress objects and constants aren't available. They haven't been loaded, because WordPress hasn't been loaded. You get the same problem, or similar, trying to load any other template or plugin file out of sequence.

The directory the file(s) are in is irrelevant. Files are not "autoloaded" just because they are in a particular directory, with a couple of specific exceptions-- with template hierarchy files for example-- and that only works because WordPress was written to look for and load particular files from particular places.

As stated in a comment to the question, you need to be using the AJAX API. There are plenty of questions here to help with that not to mention tutorials in other places and the Codex itself.

  • thanks to all of you! everything works great now with the AJAX API! :) – user2260090 Apr 10 '13 at 6:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.