WordPress.org

Ready to get started?Download WordPress

Forums

Secondary php plugin file isn't connected to the database (3 posts)

  1. phirephoenix
    Member
    Posted 1 year ago #

    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!

  2. ianhaycox
    Member
    Posted 1 year ago #

    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: http://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.

  3. phirephoenix
    Member
    Posted 1 year ago #

    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...?

Topic Closed

This topic has been closed to new replies.

About this Topic