php – How to load the page first then download the file with content-disposition?


Let me start by explaining what I want to achieve first. I have a download page where the user enters a URL with params example.com/join/123/456, where 123 is userId and 456 roomId it then connects with the API to fetch some data and append it to the file name.
Ideally, I want the page to load first and then download the file. I know I should reverse the process by loading the page and then to make the AJAX call to php but I am lost here.

This is my PHP script, I have used dummy api here which is not even used for the name change as I got this part covered. So the API will return a string which will be used to change the file’s name.

if ( is_page( 'xxx' ) && get_query_var('userId') && get_query_var('roomId')) {    
    $request = wp_remote_get( 'https://jsonplaceholder.typicode.com/todos/1' );
if( is_wp_error( $request ) ) {return false;}
    
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body );
if( !empty( $data ) ) {
$file_url = 'file-url';
$file = get_query_var('userId'); //gets the param from URL 
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header('Content-Disposition: attachment; filename="'. ($file) .'.exe"');
readfile($file_url);}

I have tried calling this script through AJAX call but I am not quite sure what I am doing with it. I also thought of fetching the string from API through AJAX and then pass it over to the php function.

I would really appreciate your help on how to resolve this issue.
Thank you