简体   繁体   中英

Ajax function call to php function

I have a simple php function as below defined in one of my php file

add_action('wp_ajax_test','test');
add_action('wp_ajax_nopriv_test','test');
function test(){
    echo "Hello";
}

I am calling above "test" function using below ajax function call

jQuery(document).ready(function(){ 
    jQuery('#prev_button_id').click(function(){
        jQuery.post(
            myAjax.ajaxurl,
            {
                action:"test",
                success: (response)=>{
                    console.log('Success:'+ response);
                },
                error:(response)=>{
               console.log('Failure:'+ response);
                }
        });
    });
});

I am expecting console output of "Hello" but I getting below undefined response

Success:undefined
Failure:undefined
jQuery(document).ready(function(){ 
    jQuery('#prev_button_id').click(function(){

        var params =  {action:"test"}

        jQuery.post(myAjax.ajaxurl,params,function(data){
            if( data ){
                console.log ( data );
            }

        });

    });
});



add_action( 'wp_ajax_test','test' );
add_action( 'wp_ajax_nopriv_test','test' );
function test() {
    echo "Hello";
    die;
}

Try this code and don't forget to die after AJAX call also make sure you are getting proper AJAX URL in myAjax.ajaxurl

I followed the below video, step by step and it worked. Probably it had something to do with nonce AJAX in WordPress using admin-ajax.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM