@abobakrdy I think there's been a fundamental misunderstanding of AJAX here
you can't conditionally register admin AJAX handlers based on the page you're on
that's not how AJAX works, it's not how HTTP works
when you load a page your browser sends a request to the server, and WP gets loaded, it's loaded from a blank slate
and it responds. Any AJAX requests are brand new requests sent to the server, and WP gets loaded from a blank slate, nothing is persisted or carried over
so if I'm on example.com/helloworld and use the admin AJAX API, then I've made a request to wp-admin/admin-ajax.php
so to say you're "on that page" in an ajax request makes no sense
you always have to register the handler
@MayeenulIslam no but I think the point of intertiajs is that you use it for the entire stack both client+server
@TomJNowell Lol, you are right, i did overlook the very basic here. However, i did find a way to conditionally register the ajax handler, by adding the same query paramater to the ajax request and the normal request.
@abobakrdy wouldn't it be easier to just always register it? What you have is that it's only registered when it's being used, which is just added complexity that doesn't make sense
you're trying to solve a problem that isn't an issue
just register the handler, nothing more needs to be done
Its more practical to avoid the overhead of requring extra code (large ajax handlers in this case) when you dont need them. I should however, probably refactor the class so it doesnt threat the ajax request as a normal request since the normal request does a lot of non-ajax stuff.
I usually set up objects with their default values in a constructor and assign any dependencies, but I don't register any hooks or do any processing
what Fuxia says 👆
an object has a lifecycle, and it pays to separate it out
so initialise your defaults/store injected variables in the construction
have a run or initialise or register type method that adds actions and filters
then do all your work on those actions/filters
that way you can just add the action for your ajax handler, and if it's not an AJAX request or it's for a different AJAX action, it won't get called, so there's no cost
or just copy paste the handlers contents into the callback of a register_rest_route and change the URL on the frontend JS
@TomJNowell I get your point, but the action handlers are singleton methods so the class needs to be instantiated regardless. Anyways, ive come to refactor the class the way you guys described - separate ajax code from normal code depending on the request type and it works pretty well.
Same. I usually split my functionality into classes and controllers, where controllers are singletons and add in all related hooks. There's no need to have more than one instance of hook controllers.