About Ajax modal window - not sure how to do that.
About other question (write all data to file or database).
There are few functions made for that purpose, inside Foreach function there is special function called [[FOREACH_DATA]] (look in the description of the function) and, you can manipuliate it for Filesystem -> Write to File (https://prnt.sc/17z1wsu), you will need to set new resource at the start of the script and use that resource as the file you are writing to, then you can use this file and manipulate it as you wish with variables to save to Database.
If you are using Multi-threaded script, you will need to use Global Variable so other threads won't override your current Thread.