简体   繁体   中英

Terminate connection to jQuery AJAX request, keep processing php on server side?

I have a signup form that calls a PHP script which can interact with our CRM's API, like so:

CRM API <--> PHP script <--> Signup form

  1. The signup form passes some information to the PHP script in one AJAX call
  2. The PHP script run a dozen API calls to the CRM to create an account and attach various data
  3. The CRM returns the new account id it just created to the PHP script
  4. The PHP script passes the account id back to the signup form, at which point the AJAX call is complete and the signup form can continue.

The problem is #2, those dozen calls take about 20 seconds to complete, but the data the signup form needs is generated after the first API call so it could in theory return that data much sooner and do the rest of the stuff server side without holding that AJAX call open the whole time.

I tried flush() and ob_flush() which does output account id to the client before processing is complete, but the jQuery AJAX connection remains open so I'm still stuck waiting for the connection to be closed on the signup form side before anything happens.

So what's the easiest route for returning that account id to the form as fast as possible?

Maybe break out using curl and exec?

 if(signing up){
      stuff
      exec(curl myself, notsignup)
 }
 else {
      bunch of api calls
 }

If you only need the information from the first API call to return the form, then I would probably try a different workflow:

  1. Form calls PHP Script
  2. PHP Calls first API Call
  3. PHP Returns to Form
  4. Form processes response
  5. Form calls second PHP Script to complete the process
  6. PHP finishes API Calls (the form can abandon at this point since it sounds like you don't care what happens from here on out).

The workflow requires a little more work and co-ordination for the developer, but presents the most responsive interface to the user.

You should probably think about creating a seperate process for the rest of the steps that are needed. One way is that you could after the #1 first api calls has been completed. It responds back to the user, and doesn't try to complete the rest of the 20 calls on the user side.

Then create a queue that will finish the rest. You could always create a table in mysql to store the queue.

Next just create a cronjob that will run in the background, knocking the queue out.

Note: You will not want this cronjob to just start and never stop. Maybe have it run every 5 minutes, but before it starts to run, check to see if another cron is still in progress. If it is then it will check in another 5 minutes to see if it is ok to run.

Hope this helps!

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