Question

Is there any way to return a response to AJAX call and keep the execution alive.

The file executions takes a way longer which delays the response from AJAX call. Can we return the output to AjAX first and then process the execution of rest of the script.

Was it helpful?

Solution

Yes there are a few approaches. All of which imply not being able to output errors after the initial output occurred.

Content-Length: xxx and Connection: close:

This implies knowing (or measuring) the length of the response (in bytes). To do this you need to use the output buffer to catch everything being outputted.

Having the content in a variable you can set a header specifying the content-length and Connection: close and then flush said content (in a weird mix of ob_flush_end() + flush()).

Shutdown function:

You can register a custom function / method to be run on end of script. If you can design your logic / application so that you can jam all of the needed functionality in a shutdown function then this is the easier approach.

There are several pitfalls to this -- not being able to use objects which have been constructed before the shutdown function is called (their destructors will have been called by now) -- so your application logic needs to initialize or reinitialize objects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top