3
I’m doing a download function with request via ajax
in my application, but it is not working.
If I access the address using the GET method with parameter in the address, the download works perfectly. download.php? option=download
But if I access the file download.php via ajax
with the script below the download is not performed.
index php.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<div class="container">
<form method ="" id="upload_form" >
<input id="upload_button" type='button' onclick="download()" name="upload_button" class="btn btn-info" value="Download" />
<br><br>
</form>
</div>
<br>
<script language="javascript">
function download(){
$.ajax({
type: "GET",
url: "download.php",
data: {
'opcao': 'download'
}
});
}
</script>
download php.
<?php
$reqmethod = $_SERVER['REQUEST_METHOD'];
$opcao = verificarMetodo($reqmethod);
if($opcao == 'download'){
$enderecoEntrega = './';
$nomeArquivo = "teste.pdf";
// Tempo máximo de execução
// Parâmetro 0 para as conexões lentas
set_time_limit(0);
baixarArquivo($enderecoEntrega, $nomeArquivo);
}
function verificarMetodo($reqmethod){
if($reqmethod == 'POST'){
$opcao = filter_input(INPUT_POST, "opcao");
}else{
$opcao = filter_input(INPUT_GET, "opcao");
}
return $opcao;
}
function baixarArquivo($caminho, $nome){
$validacao = false;
$nomeArquivo = "{$nome}";
$arquivo = "{$caminho}/{$nome}";
if(!empty($nomeArquivo) && file_exists($arquivo)){
header("Content-Type: application/pdf");
header("Content-Disposition: attachment; filename='{$nomeArquivo}'");
$bool = readfile($arquivo);
}
return $bool;
}
?>
I’m doing this feature via ajax
to not have update on the screen while downloading, and although I use only one parameter in the variable data
Javascript, I think to use the parameters with file name and address to then be performed a $enderecoEntrega = filter_input(INPUT_GET, "enderecoEntrega");
and $nomeArquivo= filter_input(INPUT_GET, "nomeArquivo");
and get dynamic the address and file of my download.
If you have an alternative way to solve my problem, feel free to post as an answer.
Have any response with JS-Vanilla?
– Jefferson Quesado
I saw some alternatives on Soen: here and here
– Jefferson Quesado
Dude, the only thing that’s in jQuery is Ajax. It’d just be exchange for XHR. You need to use?
– Sam
I do, but in a project without Jquery (or with a very bizarre access to Jquery, world of GWT). I know Jquery is just syntactic sugar to XHR, but I don’t have the experience to say what each Jquery thing maps to XHR vanilla.
– Jefferson Quesado
See if it was: https://jsfiddle.net/nf34ahdr/
– Sam
Thanks! It was something like =3 just adapt to GWT and suffer happily
– Jefferson Quesado