CRAIG
CRAIG

Reputation: 1029

Unexpected token < in JSON error with Wordpress autocomplete Jquery

I am trying to get a JQuery autocomplete script to work in Wordpress. I believe I have everything set up correctly as I do get an error when I enter data into the input field, but then I get the following error. So, I am supposing something is wrong with the JSON, but I am just not sure how to debug that.

Uncaught SyntaxError: Unexpected token < in JSON at position 0
        at JSON.parse (<anonymous>)
        at Function.n.parseJSON (jquery.js?ver=1.12.4:4)
        at Function.a.parseJSON (jquery-migrate.min.js?ver=1.4.1:2)
        at Object._transformResult [as transformResult] (jquery.autocomplete.js?ver=4.9.8:133)
        at Object.<anonymous> (jquery.autocomplete.js?ver=4.9.8:584)
        at i (jquery.js?ver=1.12.4:2)
        at Object.fireWith [as resolveWith] (jquery.js?ver=1.12.4:2)
        at y (jquery.js?ver=1.12.4:4)
        at XMLHttpRequest.c (jquery.js?ver=1.12.4:4)

Here is the JSON that is being returned:

["Hello world!","Email Notification","Email Notification","Formidable Style","Email Notification","Email Notification","Email Notification","Chapter Maintenance - Admin View","Chapter Info - All","Featured Members"]

From other posts I have looked at the comment is that it isn't being parsed correctly, but I can't determine from my research how to resolve that.

Here is the Jquery:

jQuery(document).ready(function($) {    

    $('#autocomplete-id').autocomplete({
        source: function(name, response) {
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: '/wp-admin/admin-ajax.php',
                data: 'action=get_listing_names&name='+name,

                success: function(data) {
                    response(data);

                }
            });

        }
    });

});

Here is the function in Wordpress's functions.php I am using to return the JSON via the admin-ajax.php

add_action('wp_ajax_nopriv_get_listing_names', 'ajax_listings');
add_action('wp_ajax_get_listing_names', 'ajax_listings');


    function ajax_listings() {
        global $wpdb; //get access to the WordPress database object variable

        //get names of all businesses
        $name = $wpdb->esc_like(stripslashes($_POST['name'])).'%'; //escape for use in LIKE statement
        $sql = "select post_title 
            from $wpdb->posts 
            where post_status='publish' LIMIT 10";

        $sql = $wpdb->prepare($sql, $name);

        $results = $wpdb->get_results($sql);

        //copy the business titles to a simple array
        $titles = array();
        foreach( $results as $r )
            $titles[] = addslashes($r->post_title);



        echo json_encode($titles); //encode into JSON format and output

        die(); //stop "0" from being output
    }

I have tried to console.log(data) into the success area, but all I get back is the error without any data.

When I look at the Network tab I see the requests from when I enter a letter into the input box, but all they show are ?query=a or ?query=b.

If I click on one of those it loads up the same page I am currently on (with the autocomplete input box) with ?query=a tacked onto the end of it, so that doesn't look right.

I'm just not sure why though, if it is set up correctly to get the data from admin-ajax.php.

My main question is, what can I do to debug this further?

Upvotes: 0

Views: 2259

Answers (1)

Jaydeep Jagani
Jaydeep Jagani

Reputation: 74

Here is my code, Maybe this will help you.

JS file(global.js) Code

jQuery(document).ready(function($) {    

var searchRequest;
$('#autocomplete-id').autoComplete({
    minChars: 2,
    source: function(name, result){
        try { searchRequest.abort(); } catch(e){}
        searchRequest = $.post(global.ajax, { name: name, action: 'get_listing_names' }, function(res) {
            result(res.data);
        });
    }
});

});

Functions.php File code

    <?php
/**
 * Enqueue scripts and styles.
 *
 * @since 1.0.0
 */
function ja_global_enqueues() {
    wp_enqueue_style(
        'jquery-auto-complete',
        'https://cdnjs.cloudflare.com/ajax/libs/jquery-autocomplete/1.0.7/jquery.auto-complete.css',
        array(),
        '1.0.7'
    );
    wp_enqueue_script(
        'jquery-auto-complete',
        'https://cdnjs.cloudflare.com/ajax/libs/jquery-autocomplete/1.0.7/jquery.auto-complete.min.js',
        array( 'jquery' ),
        '1.0.7',
        true
    );
    wp_enqueue_script(
        'global',
        get_template_directory_uri() . '/js/global.js',
        array( 'jquery' ),
        '1.0.0',
        true
    );
    wp_localize_script(
        'global',
        'global',
        array(
            'ajax' => admin_url( 'admin-ajax.php' ),
        )
    );
}
add_action( 'wp_enqueue_scripts', 'ja_global_enqueues' );


add_action('wp_ajax_nopriv_get_listing_names', 'ajax_listings');
add_action('wp_ajax_get_listing_names', 'ajax_listings');


function ajax_listings() {
    global $wpdb; //get access to the WordPress database object variable

    //get names of all businesses
    $name = $wpdb->esc_like(stripslashes($_POST['name'])).'%'; //escape for use in LIKE statement
    $sql = "select post_title 
        from $wpdb->posts 
        where post_status='publish' LIMIT 10";

    $sql = $wpdb->prepare($sql, $name);

    $results = $wpdb->get_results($sql);

    //copy the business titles to a simple array
    $titles = array();

    foreach( $results as $r ){
        $titles[] = addslashes($r->post_title);
    }

    wp_send_json_success( $titles );        

}

Upvotes: 2

Related Questions