Search code examples
phpajaxconnection

How to let PHP run some script after the connection end


This is my system's flow:

                Form
User Input  ───────────►    Encrypt Library Scripts
                                           │
                                           │
Result     ◄─────────   Add DB    ◄────────┤

However, The script file is encrypted and something is missing. Also I want to add the log about this function.

So I am writing some code like this:

Frontend

$("#form").submit(function(e) {
     e.preventDefault();
     
     // Call API Here

     this.submit();
});

// Step 1: API to Save the User Input and timestamp to the log table

// Step 2: Cron job to Query the latest result of that user, and update the table id to the Step 1 log 


But it seems too complicated and need to manage the cron job.

So I want to write something like this

API

$data = $_POST['inputA']; 
...
..

// Step 1: Return the response to frontend first (Finish AJAX)
// Step 2: Wait 10s for the library adding result
// Step 3: Query the latest id, and add with the $_POST data from frontend

// Will Handle if the latest result not in 10s, assume add data failed , no need to retry

Is it possible in php ?


Solution

  • You can flushe all response data to the client

    fastcgi_finish_request();
    sleep(10);
    // do your task 
    

    Or better way is to use queques https://laravel.com/docs/8.x/queues