简体   繁体   中英

WordPress admin-ajax - defer actions until after response sent

I am using admin-ajax.php to respond to requests from JavaScript.

When I've pulled together the data I want and returned my response I also need to send some data to an external API and send an email to the user. Both of these things take a little bit of time.

I was hoping I could do something like this which would return the JSON response via AJAX before setting off the actions so they could essentially happen in the background after the response was back with the user:

function my_ajax_action() {
       //process the $_REQUEST ajax data here
       echo json_encode($results);

       do_action('request_successful', $results);

       wp_die();
}

...but it is obviously waiting to complete the actions before it dies (as PHP is not async) and the AJAX request doesn't complete until the response is provided.

Are there any known methods to defer these actions until after the response has been fully sent? The two functions attached to these actions are not required to deliver the response and are just adding a couple of seconds to the amount of time it takes for the results to show in the user's browser.

I am guessing I could store them in a cron job to happen very soon after but I feel it's likely that someone has already solved this issue in a better way.

thanks Aaron

it could be related to PHP session locking and if you already have a script using session data, then the later script that will also request session data access will be put on hold until the initial script is done. Read more how to avoid it: http://konrness.com/php5/how-to-prevent-blocking-php-requests/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM