Is Ajax in WordPress

后端 未结 7 985
萌比男神i
萌比男神i 2021-01-03 17:23

Is there anyway to detect if the current server operation is currently an AJAX request in WordPress?

For example:

is_ajax()
相关标签:
7条回答
  • 2021-01-03 17:56

    I know this is an old thread, but there is an issue with the accepted answer,

    Checking for the defined DOING_AJAX constant will always be true, if the request is to the admin-ajax.php file. (https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-admin/admin-ajax.php#L16)

    Sometimes admin-ajax.php hooks aren't used for AJAX request, just a simple endpoint (Paypal IPN for example).

    The correct way is what Ian and Spencer have mentioned.

    if( ! empty( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) &&
          strtolower( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ]) == 'xmlhttprequest' ) {
        //This is an ajax request.
    }
    

    (would have commented... but no rep)

    0 讨论(0)
  • 2021-01-03 17:58

    I am not sure if WordPress has a function for this but it can be done by creating a simple one yourself.

    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
    {
        // Is AJAX request
        return true; 
    }
    
    0 讨论(0)
  • 2021-01-03 18:01

    To see if the current request is an AJAX request sent from a js library ( like jQuery ), you could try something like this:

    if( ! empty( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) &&
          strtolower( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ]) == 'xmlhttprequest' ) {
        //This is an ajax request.
    }
    
    0 讨论(0)
  • 2021-01-03 18:03

    WordPress 4.7 has introduced an easy way to check for AJAX requests, so I thought I would add to this older question.

    wp_doing_ajax()
    

    From the Developer Reference:

    • Description: Determines whether the current request is a WordPress Ajax request.

    • Return: (bool) True if it's a WordPress Ajax request, false otherwise.

    It is essentially a wrapper for DOING_AJAX.

    0 讨论(0)
  • 2021-01-03 18:15

    Update: since WordPress 4.7.0 you can call a function wp_doing_ajax(). This is preferable because plugins that "do Ajax" differently can filter to turn a "false" into a "true".


    Original answer:

    If you're using Ajax as recommended in the codex, then you can test for the DOING_AJAX constant:

    if (defined('DOING_AJAX') && DOING_AJAX) { /* it's an Ajax call */ }
    
    0 讨论(0)
  • 2021-01-03 18:16
    if ( ! function_exists('is_ajax') ) {
        function is_ajax() {
            return defined( 'DOING_AJAX' );
        }
    }
    
    0 讨论(0)
提交回复
热议问题