How to call ajax in wordpress

后端 未结 7 517
青春惊慌失措
青春惊慌失措 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:31

    In backend there is global ajaxurl variable defined by WordPress itself.

    This variable is not created by WP in frontend. It means that if you want to use AJAX calls in frontend, then you have to define such variable by yourself.

    Good way to do this is to use wp_localize_script.

    Let's assume your AJAX calls are in my-ajax-script.js file, then add wp_localize_script for this JS file like so:

    function my_enqueue() {
          wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );
          wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
     }
     add_action( 'wp_enqueue_scripts', 'my_enqueue' );
    

    After localizing your JS file, you can use my_ajax_object object in your JS file:

    jQuery.ajax({
        type: "post",
        dataType: "json",
        url: my_ajax_object.ajax_url,
        data: formData,
        success: function(msg){
            console.log(msg);
        }
    });
    

提交回复
热议问题