My ajax call output is always showing 0 as output don\'t know why
In functions.php
I have this code
function get_data() {
$abc = \'
I had the same problem. I was new to WordPress. Therefore, I am explaining here so that every new learner can understand how ajax is calling in WordPress.
First, create a function in function.php file that resides under wp-content/theme/selected_theme folder. Here, selected_theme maybe your theme name.
In the above question, a function is created with the name get_data()
;
function get_data() {
echo "test";
wp_die(); //die();
}
add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
add_action( 'wp_ajax_get_data', 'get_data' );
in the above two lines,
wp_ajax_nopriv_get_data
. Here, you can replace get_data with your choice. and the section parameter is get_data which is the function name that you want to call.wp_ajax_get_data
. Here, you can replace get_data with your choice. and the section parameter is get_data which is the function name that you want to call.Here, wp_ajax_nopriv call if the user is not logged in and wp_ajax called when the user is logged in.
jQuery.ajax({
type: "post",
dataType: "json",
url: "/wp-admin/admin-ajax.php", //this is wordpress ajax file which is already avaiable in wordpress
data: {
action:'get_data' //this value is first parameter of add_action,
id: 4
},
success: function(msg){
console.log(msg);
}
});