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
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:
client side(already enqueued):-