Support » Plugins » Using AJAX, how to connect to DB in individual files

  • I want to use AJAX in my plugin. I’ve got a JavaScript function setup to call a PHP file; the PHP file queries the DB for the info and returns it to the JS file, which updates the page. I think that is the standard method for doing this sort of thing.

    The problem with trying to do it in WordPress, though, is that I either need to access $wpdb or create me own DB connection. I’d like to use $wpdb for obvious reasons, but how? The PHP file isn’t intergrated into wordpress.

    The other option is creating my own DB connection, but then I have to either manually enter the DB info in my plugin or grab it from wpconfig.php (, which is fairly unelegant.

    I’m sure lots of people have run into this before, are there any good solutions?

Viewing 4 replies - 1 through 4 (of 4 total)
  • I’ve found that you have to do global $wpdb; inside the functions you want to use $wpdb.

    This is standard practice, I just don’t think it’s mentioned in the codex :/

    But you’re right, custom calls to the database are inelegant, and they’re also officially discouraged.

    I don’t think you understand. The PHP file is not integrated into wordpress, it can’t access $wpdb because is being called by the JavaScript function directly. It just opens the file and sends it to PHP, it doesn’t go through WordPress at all.

    Moderator Samuel Wood (Otto)

    (@otto42) Admin

    Integrate your PHP solution into wordpress. All you have to do is to include the wp-blog-header.php file, and you get all of the wordpress functionality without displaying any of the actual pages and such. This will give you access to the $wpdb.

    Ah, you’re right. Thanks 🙂

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Using AJAX, how to connect to DB in individual files’ is closed to new replies.