WordPress.org

Ready to get started?Download WordPress

Forums

Using AJAX, how to connect to DB in individual files (5 posts)

  1. Ian Dunn
    Member
    Posted 8 years ago #

    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 (http://wordpress.org/support/topic/32036?replies=16), which is fairly unelegant.

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

  2. maerk
    Member
    Posted 8 years ago #

    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.

  3. Ian Dunn
    Member
    Posted 8 years ago #

    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.

  4. Samuel Wood (Otto)
    Tech Ninja
    Posted 8 years ago #

    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.

  5. Ian Dunn
    Member
    Posted 8 years ago #

    Ah, you're right. Thanks :)

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags