Is there anyway to detect if the current server operation is currently an AJAX request in WordPress?
For example:
is_ajax()
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. }
AJAX stands for Asynchronous JavaScript and XML. AJAX is combination of web scripts and technologies that enables web pages to be updated without reloading the entire page. In WordPress, you can see AJAX in action in the post edit screen, where you can add a new category while writing a post without reloading the page.
Here's what the process for using Ajax in WordPress looks like: The user triggers an Ajax request, which is first passed to the admin-ajax. php file in the wp-admin folder. The Ajax request needs to supply at least one piece of data (using the GET or POST method).
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 */ }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With