1

Ok so say I have the following pages.

index.php

<form action="create_file.php" method="get">
    <input type="number" name="num_lines">
    <button type="submit">Download File</button>
<form>

create_file.php

<?php
     $num_lines = $_GET['num_lines'];
     //create a file with $num_lines lines
?>

How would I be able to:

1.) Create a text file with $num_lines lines and serve it to the user

2.) Send a jquery alert to the user to say the download was successful. Ideally the message would be created by create_file.php.

All while staying on index.php?

user2827048
  • 539
  • 6
  • 18
  • You could try something like this http://stackoverflow.com/questions/5560373/php-create-file-for-download-without-saving-on-server – VishwaKumar Jan 19 '17 at 07:32

2 Answers2

1

you can use ajax. please check below link that will alert text which dies in the create_file.php .. check it once

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="get">
    <input type="number" id="numLines" name="num_lines">
    <button id="button" type="button">Download File</button>
<form>

<script>
$(document).on('click','#button',function(){
var val=$('#numLines').val();
$.post('create_file.php',{val:val},function(r){
 alert(r)
});

});
</script>

create_file.php

<?php
     $num_lines = $_GET['num_lines'];
    die($num_lines);
?>
Jyothi Babu Araja
  • 10,076
  • 3
  • 31
  • 38
0

Client-side approach: http://jsfiddle.net/uselesscode/qm5ag/

Or, you could do something like:

<?php
$num_lines = $_GET['num_lines'];
$ext = '.txt';
$tmpfname = tempnam("./", "numLines_");
if (file_exists($tmpfname)) {
  unlink($tmpfname);
  file_put_contents($tmpfname . $ext, $num_lines);
  echo json_encode(array('fileUrl' => basename($tmpfname) . $ext));
} else {
  echo 'err';
}
?>

<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(function(){
  $.get('create_file.php', {'num_lines': 42}, function(res){
    var response = $.parseJSON(res)

    if(typeof response =='object') {
      var downloadableFileLink = $('<a></a>').attr('href', response.fileUrl).html("Click here to your file, yo.")

      $('#downloadTheRapper').append(downloadableFileLink)
      console.log('Oh snap.')
    } else {
      console.log('err')
    }
  });
});
</script>
</head>
<body>
<div id="downloadTheRapper"></div>
</body>
</html>