WordPress Ajax and GET method to check duplicate entry in custom table

I made a custom table in wordpress and i’m trying to make an ajax request to check if an entry already exists while the user inputs value to a field.
While the response seems successful, the data returns “0” when i make a “console.log(data)”.

JS:

jQuery(document).ready(function($) {
var nameInput = $("#create-item").find("input[name='name']");
nameInput.keyup(function() {
    $.ajax({
        type: "GET",
        url: ajaxurl,
        dataType: 'html',
        data: {
            action: 'items_check_name_action',
            name: 'name='+nameInput.val()
        },
        success: function (data) {
            console.log(data);
        },
        error: function (data) {
            console.log('error');
        }
    });
});});

PHP:

function items_check_name_callback() {
global $wpdb;
$table_name = $wpdb->prefix . "items";
$name = $_GET['name'];
$sql = "SELECT * FROM ".$table_name." WHERE name =`".$name."`";

$result = $wpdb->query($sql);
$rows = $result->num_rows;

if($rows == 0) {
    echo 'ITEM_AVAILABLE';
}
else {
    echo 'ITEM_EXISTS';
}}

HOOK:

add_action('wp_ajax_items_check_name_action',   'items_check_name_callback');

What am i doing wrong?

Read more here: WordPress Ajax and GET method to check duplicate entry in custom table

Leave a Reply

Your email address will not be published. Required fields are marked *