Molod
Molod

Reputation: 352

Uncaught SyntaxError Unexpected Number JSON.parse

Trying to get json data through ajax request, but always get this error :

Uncaught SyntaxError Unexpected Number

Here is my js code :

var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';

    $.ajax({
        url: ajaxurl,
        type: 'POST',
        dataType: 'json',
        data: { action : 'getPills' },
        success: function(data){
            product = JSON.parse(data);
            console.log(product);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(textStatus, errorThrown);
        }
    });

Here is my php code :

add_action('wp_ajax_getPills', 'getPills');
add_action('wp_ajax_nopriv_getPills', 'getPills');

function getPills(){

        $data = array(
            "test" => 'test'
        );

        error_log(json_encode($data), 0);

        echo json_encode($data);
}

called error_log to see what json data I trying to receive:

{"test":"test"}

I used ajxa+json before on other projects and it was all good. I have no idea how to fix it :(

Upvotes: 1

Views: 6822

Answers (2)

Molod
Molod

Reputation: 352

Found the solution.

I needed to add die() at the end of an AJAX handler function to prevent further content. Wordpress was adding 0 at the end of respond. Something like this:

{"test":"test"}0

So die() at the end of an AJAX handler function fixed the problem

Upvotes: 6

Musa
Musa

Reputation: 97707

By specifying dataType: 'json', the data passed to the success function will already be deserialized into an object, so you don't call JSON.parse on it

    success: function(data){
        console.log(data);
    },

Although that should would give you an error like SyntaxError: Unexpected token o and not Uncaught SyntaxError Unexpected Number. You should check developer tools to see exactly what is returned by the server.

Upvotes: 3

Related Questions