I'm facing a problem with wp ajax performance. I'm initializing an ajax call from my javascript side but the response takes 3-5 secs to come back. I understand that admin ajax call has to load the whole wp core and that would definitely be a performance hit for us.

Is there a way to still use the admin ajax call, but without loading all plugins? Essentially in my php api, I'm only using some values from wp-config. Or is there any better ajax suggestions given my use case? Is it possible to use regular rest API(without going through admin-ajax) but could still use the values from wp-config?

Here is my js code(ajax.js):

jQuery.ajax({
        url: ajax_object.ajax_url,
        data: {
            action: 'geo_ip_api'
       },

        type: 'POST',
        success: function (output) {
            console.log(output);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr.status);
            console.log(xhr.responseText);
            console.log(thrownError);
        }
    });

Here is my php api(api.php):

function geo_ip_api(){
global $bannerRequiredRegions;
global $ipBlackList;
$isInEU = 'null';
$ipAddress = get_ip_address();
if(!in_array(strtolower($ipAddress), array_map('strtolower', $ipBlackList)))
{
    try
    {
        require_once 'HTTP/Request2.php';
        /* retrieving values from wp-config */
        $api_url = GEO_API_URL;


        $request = new Http_Request2($api_url);
        $url = $request->getUrl();

        //sending HTTP request logic here. No dependency on wordpress
    }
    catch (Exception $ex)
    {
        //TODO: put log here
    }
}

echo $isInEU;

}

Any help appreciated! Thanks in advance. I've searched lots of post and none of those could answer my question.

  • you are doing an http request in your ajax handler, there is no way you will get a fast response – Mark Kaplun Nov 1 '17 at 6:09

If your requests take 3-5 sec to finish, then there is most likely something else going on. The admin Ajax itself won't take that much to load. You might be having some heavy plugin, or having some hooks running expensive meta queries on load.

You can try the REST-API, which is slightly faster than Admin-Ajax. But the response will be in JSON, instead of plain HTML, you have to note that one.

Also, there might be an issue with the TTFB. Try disabling all the plugins, revert to default theme (move your code to default theme) and check if the problem still persists.

This might or might not work best for you, custom endpoints are generally useful for Polling and other sort of situations and not for regular ajax work. You might rather look into other methods like caching the results from your API.

Also from my discussion with Mark, I do agree that using this in a public plugin is not a very good idea as it requires a lot of changes on user end, and rather this is something to be used if you're building a solution specific to a site.

For the sake of information I'm adding the alternates to WP Ajax.

You can make use of WordPress constant SHORTINIT if you don't want to load the plugins. It might not help in making ajax request faster in this particular case since you're making a HTTP request as Mark mentioned in comments.

If SHORTINIT is set to true, WordPress doesn't loads most of the thing for a Ajax request, just the bare minimum.

And if you need to use any of other features, you can just load the required files from WordPress.

Here is a very nice article to help you get started, and there are 3 differnt approaches in here: https://deliciousbrains.com/wordpress-rest-api-vs-custom-request-handlers/

I'll just post a excerpt from the article for the use case of SHORTINIT. You need to create a PHP file in your theme or plugin that starts out with this code and add you handler for the rest of processing.

// Set SHORTINIT to true
define( 'SHORTINIT', true );

// get the path for wp-load.php, considering this file in root directory of plugin/theme
$wp_root_path = dirname( dirname( dirname( __FILE__ ) ) );
// Load wp-load.php file (which loads wp-config.php and bootstraps WordPress)
require( $wp_root_path . '/wp-load.php' );

// $wpdb class for any query you might need
global $wpdb;

// Do your PHP code for rapid AJAX calls with WP!
function geo_ip_api(){
 global $bannerRequiredRegions;
 global $ipBlackList;
 $isInEU = 'null';
 $ipAddress = get_ip_address();
 if(!in_array(strtolower($ipAddress), array_map('strtolower', $ipBlackList))) {
   try {
    require_once 'HTTP/Request2.php';
    /* retrieving values from wp-config */
    $api_url = GEO_API_URL;


    $request = new Http_Request2($api_url);
    $url = $request->getUrl();

    //sending HTTP request logic here. No dependency on wordpress
  }
   catch (Exception $ex){
    //TODO: put log here
   }
 }

 echo $isInEU;
}
  • if the shortinit is set in your plugin then plugins are already loaded, so the only option is to set it outside of the plugin, which means that user need to manually change code file, or handle the ajax in a direct request to a file in your plugin which is a totaal no-no as well. You might get away with it in a theme, but I would call it highly dangerous. – Mark Kaplun Nov 1 '17 at 6:52
  • No the plugins aren't already loaded. The user definitely needs to send the ajax request to custom URL and when you define shortinit true inside the custom ajax handler file while including wp-load.php, WordPress is gonna load the bare minimum and not all of plugins and themes. And for what reason it'd be a no or dangerous to use? – sven Nov 1 '17 at 8:50
  • and what would be that custom url? as I said most likely you will need to instruct the use to create one, or modify the config file which means that you will not be able to update the plugin without risking that the code added by the user will not be compatible with the new code – Mark Kaplun Nov 1 '17 at 9:00
  • .... and you can never know in a plugin where wordpress is installed which is why a direct access into the plugin directory is a total no-no – Mark Kaplun Nov 1 '17 at 9:01
  • Ok I get it, so yeah using shortinit in a public plugin is definitely a bad idea. My answer is rather for a personal usage pov, and that seems to be the use case in here. Like if you are building a custom theme/plugin specifically for a site. Also, I did updated the description that it is not very useful for regular Ajax requests and rather helpful in polling and very similar situations. – sven Nov 1 '17 at 9:10

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.