AJAX, JQuery and JSON in Wordpress: errorThrown: SyntaxError: Unexpected token in JSON at position 0

0

I am trying to use AJAX on my Wordpress site and I can not get data from the server. I've reduced my code to something super simple to see if I find the error and nothing!

add_action('wp_ajax_nopriv_vc_ajax_test', 'vc_ajax_test');
add_action('wp_ajax_vc_ajax_test', 'vc_ajax_test');

function vc_ajax_test(){

    $results = array(
        'success'  => true,
        'html' => 'algo'
        );  
    echo json_encode ($results);
    die();

}

// función jQuery

$( "#ajax-trigger" ).click(function() {
            console.log( '#ajax-trigger clicked!' );
            link = $(this);
            content = 
            id   = link.attr('id');

            console.log( 'id: ' + id );

            jQuery.ajax({
                url : jp.ajax_url,
                type : 'post',
                dataType: 'json',
                nonce: jp.nonce,
                data : {
                    action : 'vc_ajax_test',
                    message: 'Button has been clicked!'
                },
                beforeSend: function(){
                    link.html('Cargando ...');
                },
                error: function(jqXHR, textStatus, errorThrown){
                    console.log("jqXHR: " + jqXHR);
                    console.log("textStatus: " + textStatus);
                    console.log("errorThrown: " + errorThrown);
                },
                success : function(respuesta) {

                    link.html('#ajax-trigger');
                    $('#ajax-target').html('Debería funcionar: ');

                    console.log('Data:' + respuesta.html);

                }
            });

            return false;
        });

The error appears automatically when I place dataType: 'json'. The issue is that without that, doing echo the variable happens as "undefined". So my fight is to try to pass something from the server to the client to read it in jQuery, something that until now has been impossible for me.

  

jqXHR: [object Object] textStatus: parsererror errorThrown:   SyntaxError: Unexpected token < in JSON at position 0

will you help me?

    
asked by vivi 29.10.2018 в 21:10
source

0 answers