A simple Ajax call in wordpress doesn't give t

2019-08-17 04:23发布

问题:

Here is my javascript file:-

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

$('#test_button').click(function(e){

        alert("test");

$.ajax({
    url : my_ajax_object.ajaxurl ,
    type : 'post',
    dataType : 'json',
    data : {
        action : 'do_ga'
    },
    complete: function(res, status) {

        if( status == 'success' ) {

          console.log("success "+res);

        } else {
            console.log("fail "+res);

        }
    }
});



});
});

here is my php code in functions.php:-

function do_ga() {
    die("test" );
}

add_action( 'wp_ajax_do_ga', 'do_ga' );
add_action( 'wp_ajax_nopriv_do_ga', 'do_ga' );
//this is the script en queuing 
function my_enqueue() {
    wp_enqueue_script( 'ga-loadmore', get_template_directory_uri() . '/pl-custom/front-end-assets/js/ga-loadmore.js', array('jquery') );
    wp_localize_script( 'ga-loadmore', 'my_ajax_object',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );

So,upon the click of the button with id "#test_button" , instead of outputting success [object][object] , it outputs fail [object][object]. What needs to be done here. Precisely , i want "success test". please add the json_encode and decode wherever required in the solution.Thanks

回答1:

I've separated the PHP code in another file and included it in functions.php and also separated the enqueuing, and changed the syntax of the request a little. I hereby attach my code and it works:

function do_ga() {//server code
     $x="test";

      wp_die( $x);
      exit;
}

add_action( 'wp_ajax_do_ga', 'do_ga' );
add_action( 'wp_ajax_nopriv_do_ga', 'do_ga' );

client side(already enqueued):-

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

$('#test_button').click(function(e){
    url = window.location.origin + '/wp-admin/admin-ajax.php?action=do_ga';
        alert("test");
$.ajax({
    async: true,
    type: 'POST',
    url: url,
    data: {
        'my_number':1 //you need not pass data
    },
    complete: function(res, status) {

        if( status == 'success' ) {

           alert("success "+ res.responseText);


        } else {

           alert("unable to process request");
        }
    }
})



});
});