• I’m working on a plugin that uses AJAX to look up a user-inputted value (via a dropdown form) in the plugin DB table, and the plugin then returns the corresponding output from that database on the same page. The approximate logic goes like this:

    functions.php generates a shortcode
    – this shortcode calls the ajax.js script in the plugin folder
    – ajax.js sends the user-inputted data via GET to processing.php in the plugin folder
    – processing.php returns the responseText and it gets inserted into my results div

    My problem: processing.php isn’t connected to the WP database. I’ve tested that every other step in this chain is working by connecting the file manually to the WP database, but obviously that’s not workable for a universal plugin. How do I go about getting WP to recognize processing.php, or else include something in processing.php that generates the necessary database connection?

    This is my first time dabbling with anything plugin related, I’d appreciate any tips in the right direction!

Viewing 2 replies - 1 through 2 (of 2 total)
  • I think you’ll need a handler in your plugin to manage the request.

    E.g.

    add_action('wp_ajax_myplugin_getdata', 'myplugin_getdata');

    or

    add_action('wp_ajax_myplugin_getdata', array($plugin,'getdata'));

    if your plugin is in a class with $plugin as your plugin instance.

    In ajax.js you need to execute a GET with an action parameter matching the action above minus the wp_ajax_ bit,

    e.g.

    $.ajax({
        type:"GET",
        url: https://myblog/wp-admin/admin-ajax.php,
        data:"action=myplugin_getdata&"+data,
        success: function(returned_data) {
            $('#display').html(returned_data);
        }
    ....

    then in myplugin_getdata retrieve your GET parameters, perform a database lookup and issue a

    die('My returned data');

    You can get the AJAX url via admin_url( ‘admin-ajax.php’ ) and pass it to the ajax.js after calling wp_enqueue_script via wp_localize_script.

    For non-logged in users you’ll also need a,

    add_action(‘wp_ajax_nopriv_myplugin_getdata’, ‘myplugin_getdata’);

    Ian.

    Thread Starter phirephoenix

    (@phirephoenix)

    Ooh, awesome, I will dig into that and report back with the results. I’m not sure I understand why I need a separate action for non-logged-in users, though…?

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Secondary php plugin file isn't connected to the database’ is closed to new replies.