I have a custom REST route that imports a CSV file. Everything works so far, but I get a timeout error because it's a really big CSV and it takes a long time. I want to make my REST route start the import process, then return a response while continuing to import.

register_rest_route('lws-admin/v1', '/customer/import', array(
  'methods' => 'POST',
  'callback' => function($request) {
    // *start really long operation*

    return array(
      'message' => 'import started'
  • If you're getting a timeout, then that won't make it suddenly work, doing this would make your JS client think it's ok, but the PHP process will get terminated before the CSV import can finish, leading to an incomplete import, and your page would have no way of knowing. If you want to indicate to the user that the request has begun with an "import started" message, you don't need server side changes to do that, the solution is 100% javascript. Have a look at promise based requests that let you use .then(.... such as fetch or the jQuery based promise AJAX – Tom J Nowell Mar 14 at 21:30
  • @TomJNowell I am doing it with AJAX, that is what is timing out. I am already doing exactly what you described but that doesn't stop it from timing out. Is it possible to spawn a child process to complete the operation? I'd rather not simply just increase the maximum timeout since that just feels like a band-aid. How do the other importer plugins work? I've used plugins before that can import massive amounts of posts, and it never times out. – chrispytoes Mar 14 at 21:45
  • If you have already hit execution timeout - it's better to rewrite js code to send data in chunks and chain ajax requests to be called one after previous was completed. So the plan might be: 1) your js reads csv file, 2) it's splitted in chunks by let's say some sane amount of records 3) each chunk is send via queued ajax requests. As a result your code will be able to handle big amounts to be processed, and you'll have good progress indication as each chunk gets processed. – Mikhail Mar 15 at 20:41
  • @Mikhail Alright, that was my fallback anyway. Just wanted to know to see if I could get out of doing the work since it really doesn't need to be that pretty. – chrispytoes Mar 15 at 20:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.