How to call ajax in wordpress

后端 未结 7 508
青春惊慌失措
青春惊慌失措 2020-11-28 10:49

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 = \'         


        
7条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 11:19

    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,

    1. The add_action method is used to implement the hook. Here, I am passing the two parameters, first is 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.
    2. In the second add_action, I am passing the two parameters, first is 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);
        }
    });
    

提交回复
热议问题