$post is undefined in wordpress loop [ajax]

Is it okay to call global $post; inside the loop in ajax or is there a better way to access the current post object?

I’d do it outside the loop but in the same scope to avoid duplication, but otherwise the answer is:

If it works, then it works, don’t stress about it, there is no canonical one way to rule them all for this.

global $post; works, and there is another option of $post = get_post(); but it’s rare. Most people just do global $post; out of habit.

You can also avoid it entirely by doing this:

if ( get_post_type() === 'foo' ) {

I figure the reason this happens is that there’s some other wp magic that runs behind the scenes and makes $post available in template files, but not in ajax. Hence, I added global $post; just before my if statements and now it works as expected.

Nope, this theory is incorrect, post loops work the same in AJAX handlers

$args = $_REQUEST['query'];
$request_query = new WP_Query($args);

This should be considered a major security hole, as now anybody can query for anything, and they can trigger super expensive queries that will hammer your database aka resource exhaustion attacks. Whitelist the arguments you allow and their valid values!