rushtoni88
rushtoni88

Reputation: 4665

AJAX to update mySQL in Wordpress Custom Table

I have followed Matt Van Andel's Custom List Table Example to create an admin table which displays enquiries to a website via an external MySql database.

Having implemented the displaying of my data correctly, I have added a select box column which will allow the admin to update the 'status' of the enquiry (Awaiting Response, Responded etc.) and I need this to update my database via AJAX.

I need a change in these select boxes to trigger an AJAX call which will update the database with the new value but I seem to be struggling to link my external AJAX file to my plugins .php file correctly.

I have reached a point where (in the Network tab) I can see I am loading the .js file like so:

Code in list-table.php:

function ajax_test_enqueue_scripts() {
        wp_enqueue_script( 'list-table', plugins_url( 'js/list-table.js', __FILE__ ), array('jquery'));
    }
    add_action( 'admin_enqueue_scripts', 'ajax_test_enqueue_scripts' );

And my AJAX:

jQuery('.status-select').on( 'change', function ajaxSubmit() {

    alert("IT WORKED!");

        $.ajax({
        url: ajaxurl,    
        type: "POST",
        cache: false,
        data: this.val()

    })
});

At the moment the file is showing but the 'on change' part doesn't seem to be firing (hence the 'alert' in the .js).

Apologies if this question is worded or organised poorly, it is my first time posting!

Hope someone can explain what/ where I am going wrong.

Upvotes: 2

Views: 3056

Answers (1)

rushtoni88
rushtoni88

Reputation: 4665

This is quite a specific requirement but for anyone else using custom tables in WordPress and wanting to update an external myqsl database via AJAX - here's how I did it.

The AJAX side of things -

     <script>
    jQuery('select.status').on('change', function() {

        var $statusSelect = jQuery( this );
        var $statusSelectCell = $statusSelect.parent();
        var enquiryStatusValue = $statusSelect.val();
        var currentBackgroundColor = $statusSelectCell.parent().css("backgroundColor");

        var ajaxData = {
                'action': 'update_status_db',
                'currentId': $statusSelect.attr('id'),
                'data': enquiryStatusValue
        }

        jQuery.ajax({

            type: "POST",
            url: "/wp-admin/admin-ajax.php",
            data: ajaxData,
            success: function( response ) {
                console.log("Data returned: " + response );
                $statusSelectCell.parent().css({"background-color": "#b3e6b3"});
                $statusSelectCell.parent().animate({backgroundColor: currentBackgroundColor}, 1200);
            },
            error: function() {
                alert("FAILED TO POST DATA!!");
            }

        });

    })
</script>

Note, the users success confirmation in this case is for the specific row to flash green. This is optional.

Next, the PHP to process the AJAX request. This is to be written outside the tables class.

wp_enqueue_script('jquery');

add_action( 'wp_ajax_update_status_db', 'update_status_db_callback' );

function update_status_db_callback(){

global $wpdb;

$newStatus = $_POST['data'];
$currentId = $_POST['currentId'];
$table = 'wp_enquiryinfo';
$result = $wpdb->update( $table, array( 'status' => $newStatus ), array( 'id' => $currentId ));

echo $_POST['data'];

if (!$result) {
    echo "FAILED TO UPDATE";
} else {
    $result;
    echo "WILL UPDATE SUCCESSFULLY - CALL RESULT FUNCTION";
};

wp_die();

}

Here are a couple of the things I was getting wrong originally: Firstly, the callback function HAS to end with _callback. Secondly, I didn't call the wp_die function at the end of this - this again is required.

Hopefully this may be of use to someone in the future.

Upvotes: 3

Related Questions