在文件附件下载的同时检索值

在文件附件下载的同时检索值

问题描述:

I have a form that triggers a file download:

function downloadEnhancedSubtitle ($subtitle,$totalSequences,$filename) {
    // Build string
    $subtitleString = '';
    foreach ($subtitle as $thisSegmentKey => $segment) {
        $sequenceString = $segment->sequence."
";
        $sequenceString .= formatMilliseconds($segment->startTimeInMilliseconds).' --> '.formatMilliseconds($segment->endTimeInMilliseconds)."
";
        if(isset($segment->textLine1)) $sequenceString .= utf8_decode($segment->textLine1)."
";
        if(isset($segment->textLine2)) $sequenceString .= utf8_decode($segment->textLine2)."
";
        if(isset($segment->textLine3)) $sequenceString .= utf8_decode($segment->textLine3)."
";
        $sequenceString .= "
";
        $subtitleString .= $sequenceString;
    }
    $subtitleString .= ($totalSequences+1)."
99:99:90,000 --> 99:99:99,999
Enhanced
";

    // Download string
    header("Content-Type: text/plain;charset=windows-1252");
    header('Content-Disposition: attachment; filename="'.$filename.'"');
    header("Content-Length: " . strlen($subtitleString));
    echo $subtitleString;
}

The user submits a subtitle file and it is "optimized" on the server and sent back to the user as an attachment download. But I would like at the same time (same form view where the file is downloaded) to trigger a modal with some data of the process, for example, how many lines where optimized.

As "Content-Disposition: attachment" automatically downloads everything printed on screen, is there any way I could retrieve the value of a variable using that response? Maybe changing everything to be an ajax request? (using PHP on the backend)

Firstly you need to save file on server then you can get response with all variables, but it's one problem - you need to delete all generated files for safety.

function downloadEnhancedSubtitle ($subtitle,$totalSequences,$filename) 
{
    [...]
    // Response for ajax
    echo json_encode(
        [
            'filename' => $filename,
            'link' => 'http://localhost/uploads/' . $filename,
            'subtitle' => $subtitleString
        ]
    );
}

Javascript (jQuery)

You are getting all your variables from server.

$.ajax({
    [...],
    success: function(response) {
        // if response is not object
        var obj = JSON.parse(response),
            filename = obj.filename,
            link = obj.link,
            subtitle = obj.subtitle;

        // if response is object
        var filename = response.filename,
            link = response.link,
            subtitle = response.subtitle;

    }
});