Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Ajax in WordPress

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

For example:

is_ajax() 
like image 877
Racura Avatar asked Jan 15 '13 22:01

Racura


People also ask

How do I know if WordPress is AJAX requested?

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. }

What is WP AJAX?

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.

Where do I put AJAX code in WordPress?

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).


2 Answers

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 */ } 
like image 82
webaware Avatar answered Oct 03 '22 16:10

webaware


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.

like image 27
Nate Weller Avatar answered Oct 03 '22 16:10

Nate Weller