How to call ajax in wordpress

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

    Actually, WordPress comes with a handy function to access admin-ajax.

    Requirements

    • In wp-admin you do not need to do anything, the js library is always loaded
    • In the front-end you need to enqueue the script wp-util, like this:

      add_action( 'wp_enqueue_scripts', 'my_enqueue_function' );
      
      function my_enqueue_function() { 
          // Option 1: Manually enqueue the wp-util library.
          wp_enqueue_script( 'wp-util' );
      
          // Option 2: Make wp-util a dependency of your script (usually better).
          wp_enqueue_script( 'my-script', 'my-script.js', [ 'wp-util' ] );
      }
      

    The JS Library

    The wp-util script contains the wp.ajax object that you can use to make ajax requests:

     wp.ajax.post( action, data ).done( okCallback ).fail( errCallback )
    

    Your example:

    wp.ajax.post( "get_data", {} )
      .done(function(response) {
        alert("Your vote could not be added");
        alert(response);
      });
    

    PHP code

    Of course, you still need to create the wp_ajax_* hooks in your PHP script.

    add_action( 'wp_ajax_nopriv_get_data', 'my_ajax_handler' );
    add_action( 'wp_ajax_get_data', 'my_ajax_handler' );
    
    function my_ajax_handler() {
        wp_send_json_success( 'It works' );
    }
    

    Tip:

    For Ajax responses WordPress provides two functions:

    wp_send_json_success( $my_data ) and wp_send_json_error( $my_data ) - both functions return a JSON object and instantly terminate the request (i.e., they exit;)

    0 讨论(0)
提交回复
热议问题