2

I am trying to send files to the client via jQuery, AJAX, and PHP. I am using jQuery v1.11.2 and xampp v3.2.1,

Here is my jQuery code:

<script>
$(document).ready(function(){
    $("#myBtn").click(function(){
        $.ajax({ // post file name
            type: "POST",
            data: {
                file: "testfile.xlsx"
                },
            url: "sendfile.php",
            context: $("#result"),
            success: function(data, status, xhr){
                $(this).html(data);
            }
        });
    });
});
</script>

sendfile.php:

<?php

FUNCTION send_file($name) { // function ... send file to client
  OB_END_CLEAN();
  $path = $name;

//cek connection if lost connection with client
  IF (!IS_FILE($path) or CONNECTION_STATUS()!=0) RETURN(FALSE);
//header
//-------------------------------------------------------------
  HEADER("Cache-Control: no-store, no-cache, must-revalidate");
  HEADER("Cache-Control: post-check=0, pre-check=0", FALSE);
  HEADER("Pragma: no-cache");
  HEADER("Expires: ".GMDATE("D, d M Y H:i:s", MKTIME(DATE("H")+2, DATE("i"), DATE("s"), DATE("m"), DATE("d"), DATE("Y")))." GMT");

//set last modified property
  HEADER("Last-Modified: ".GMDATE("D, d M Y H:i:s")." GMT");
  HEADER("Content-Type: application/octet-stream");
  HEADER("Content-Length: ".(string)(FILESIZE($path)));
  HEADER("Content-Disposition: inline; filename=$name"); // file
  HEADER("Content-Transfer-Encoding: binary\n");
//-----------------------------------------------------------------
  IF ($file = FOPEN($path, 'rb')) { // send file
   WHILE(!FEOF($file) and (CONNECTION_STATUS()==0)) {
     PRINT(FREAD($file, 1024*8));
     FLUSH();
   }
   FCLOSE($file);
  }
  RETURN((CONNECTION_STATUS()==0) and !CONNECTION_ABORTED());
}

// send file
if(!send_file($_POST['file'])){
    echo "error.";
}

When I press the button no files received instead of random sentences in #result

If I use directly in PHP functions are working properly

send_file("testfile.xlsx");

Are there more effective methods?

Bijan
  • 7,737
  • 18
  • 89
  • 149
Error Person
  • 33
  • 1
  • 4

1 Answers1

-1

if you're looking for another method similar to that, try using 'uploadify' its free and easy --> http://www.uploadify.com/demos/

mpalencia
  • 5,481
  • 4
  • 45
  • 59