I want to to write data to file and force it to download (wherever user default download location is). I use ajax on button click to get data from database. Following code would write to file in Wordpress uploads directory.
 //js
var postData = [
        {name: 'action', value: 'foo_export_player'},
        {name: 'player_id', value: player_id},
        {name: 'player_title', value: player_title},
    ];
    $.ajax({
        url: apvr_data.ajax_url,
        type: 'post',
        data: postData,
        dataType: 'json',
    }).done(function(response){
        
    }).fail(function(jqXHR, textStatus, errorThrown) {
        console.log(jqXHR.responseText, textStatus, errorThrown);
    });
//php
function foo_export_player(){
        $player_id = $_POST['player_id'];
        $player_title = $_POST['player_title'];
        global $wpdb;
        $wpdb->show_errors(); 
        $tour_table = $wpdb->prefix . "apvr_tours";
        //player
        $stmt = $wpdb->prepare("SELECT * FROM {$tour_table} WHERE id = %d", $player_id);
        $result = $wpdb->get_row($stmt, ARRAY_A);
        if($result){
            $options = unserialize($result['options']);
            $data = stripslashes_deep($options);
            $data['title'] = $result['title'];
            $name = 'avpr_tour_id_'.$player_id.'_title_'.$player_title;
            $path = WP_UPLOADS_DIR.$name.'_'.date('m-d-Y_hia').'.txt';
            if(!file_put_contents($path, serialize($data))){
                return esc_html__('Failed to create backup file. Please try again!', APVR_TEXTDOMAIN);
            };
            header( "Content-Type: text/html" );
            echo json_encode($path);
        }
        wp_die();
        
    }else{
        wp_die();
    }
}
       
    });
This works, but how can I make it download file instead of saving file in $path location?