I wrote a small script using only PHP to test file download functionality using a experimental API, where this worked fine. When I decided to commit this code to my project, I added the same code to the handler for my AJAX call, however it does not start the download as it did before.
I believe this is due to the fact I am using AJAX, however as I was using header() to initiate the file download on the client, I am at a loss as to how to work around this.
Can anyone suggest an alternative method to do this now?
AJAX:
$.ajax({
type: "POST",
url: "handler.php",
data: { 'action': 'downloadFile', 'filename': curSelectedFile },
dataType: 'json',
success: function(data)
{
//Success
}
});
PHP Handler:
case "downloadFile":
{
$filename = '';
if (isset($_POST["filename"]))
{
$filename = $_POST["filename"];
}
$pos = 0; // Position in file to start reading from
$len = 32; // Length of bytes to read each iteration
$count = 0; // Counter for the number of bytes in the file
do
{
$result = $fm->getFileChunk($filename, $pos, $len);
$chunk = $result->result;
if (!empty($chunk))
{
$chunk = base64_decode($chunk);
$count += strlen($chunk);
echo $chunk;
}
$pos += $len;
}
while (!empty($chunk));
header('Content-Disposition: attachment; filename="'. $filename .'"');
header('Content-Type: application/octet-stream');
header('Content-Length: ' . $count);
$response['status'] = "success";
echo json_encode($response);
break;
}
You can encode your file in base64 and create File Object using JavaScript.
I wouldn't recommend this for large files!
Alternative:
Save your file on server and you can just retrieve file location and redirect using location.href in Ajax callback.
You can decode base64 using atob() and create typed array. refer to following link for creating Binary Object on client side. You create typed array like answered here.
Related
I want to generate a csv file with a dynamic filename which came from the values I got using an ajax jquery request. These values will be used as filename for my generated csv file. My program does not generate the csv file. What should I do for the csv file to be generated?
I am a newbie when it comes to php and especially AJAX and Jquery so I am still a bit confused on how an AJAX request works.
I'm using a free trial version of Sublime IDE and localhost for php. The program displays the contents of the csv file through an alert box but it doesn't generate a csv file.
This is my jquery ajax request file:
var selectedLanguage = $('#selectLanguage').val();
var length;
length = selectedLanguage.length;
for (var i = 0; i < length; i++)
{
var selectedLanguage = $('#selectLanguage').val();
$.ajax({
crossDomain: true,
async: false,
url: "downloadFile.php",
type: "GET",
data: {"seLang": selectedLanguage[i]},
success: function(data)
{
alert(data);
location.reload();
}
});
}
This is my downloadFile.php code:
<?php
$id="";
if(isset($_GET['seLang'])){
$id = $_GET['seLang'];
$filename = "File_".$id.".csv";
$f = fopen('php://memory', 'w');
//set headers for column
$fields = array('Content1', 'Content2', 'Content3','Content4');
fputcsv($f, $fields, ',');
fseek($f, 0);
header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . $filename . '";');
fpassthru($f);
}
else
{
echo "<script type='text/javascript'>alert('Empty');</script>";
}
?>
Edit 1:
Thank you Prvn and Sunday Johnson for trying to help. Although, I've found the actual problem. I've read from another post in this site that it is isn't possible to download the generated csv file using AJAX. What else can I do for me to download a csv file?
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$fields = array('Content1', 'Content2', 'Content3','Content4');
$fp = fopen('php://output', 'wb');
foreach ( $fields as $line ) {
$val = explode(",", $line);
fputcsv($fp, $val);
}
fclose($fp);
Output
One comment about the Ajax code, why are you iterating over the value?
About the php code, use this instead:
<?php
$id="";
if(isset($_GET['seLang'])){
$id = $_GET['seLang'];
$filename = "File_".$id.".csv";
$f = fopen($filename, 'w');
//set headers for column
$fields = array('Content1', 'Content2', 'Content3','Content4');
fputcsv($f, $fields, ',');
fclose($f);
}
else
{
echo "<script type='text/javascript'>alert('Empty');</script>";
}
?>
I just start to learn javascirpt, php about 2 days. The problem I face is I already have a x.dcm file under server root, and I already known that path(e.g. http://localhost:8888/....)
My question is how can I simply grab that file from server to use, maybe something like:
var file= 'http://localhost:8888/....'; ////file is not an object
I ask this question because I already known how to use input method:
<input type="file" name="file" id="file">
<script>
$('#file').on('change',function(e){
var file = e.target.file; ///file is an object
});
</script>
but that is not what I want, what I want is to use an existed file rather than input.
So the whole thing is that:
<form id="input" method="post" enctype="multipart/form-data">
<input type="file" id="fileToUpload" name="fileToUpload">
</form>
I firstly make a input to upload some file,then in script
<script>
$("form#input").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: 'segmentation.php',
type: 'POST',
data: formData,
async: false,
success: function (html) {
$('#segbound').html(html);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
</script>
I sent this file(e.g image.dcm) to do something( run a exec) on the server side, then it generates another image(imgproc.dcm) in an expected path(http://localhost:8888/....), and then the next thing is that I what that processed image display on the screen. To do that I need to use a js called cornerstone, and the function in it imageLoader.fileManager.get(file)
which file is that one I what to display.
When I select from input using var file = e.target.file; as I mentioned above, it works perfect, then I check the file type it is a [file object].
But when I want to simply display that 'imgproc.dcm' by using var file= 'http://localhost:8888/....'; the file type is not an object which comes out my question, how can I simply grab that known path image to use as an object.
Or, to improve that, it is possible to get the return (generated imgproc.dcm) directly after it process on server side, and then to use that return(maybe give it an id...do not know) to display (call cornerstone function imageLoader.fileManager.get(file))
On server side, it looks like:
<?php
$target_dir = "/Applications/MAMP/htdocs/dicomread/temp/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (file_exists($target_file)) {
echo "file has already been uploaded.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file)) {
echo "The file ". basename( $_FILES['fileToUpload']['name']). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
$cmd = "/Applications/MAMP/htdocs/dicomread/abc 2>&1";
$Output_fileName = "imgproc.dcm";//$_FILES['fileToUpload']['name'];
exec("$cmd $target_file $Output_fileName);
echo "<br/>done";
?>
Any help would be appreciated.
Use fopen with URL to the file:
$file = fopen("http://localhost:8888/x.dcm", "r");
Refer to this for fopen: http://php.net/manual/en/function.fopen.php
This is my jQuery request to upload an image file
$('#upload-image').change(function(e){
var file = e.target.files[0];
var imageType = /image.*/;
if (!file.type.match(imageType))
return;
console.log(file);
var form_data = new FormData();
form_data.append('file', file);
console.log(form_data);
$.ajax({
url: 'http://localhost/upload.php',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
This is upload.php on local webserver
<?php
header('Access-Control-Allow-Origin: *');
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . $_FILES['file']['name'];
echo $target_path;
}
?>
When I upload the image and send request. It returns and logs for me complete code lines of upload.php, not the result from echo command line that I want. I check console Network tab and see that the response is nothing except complete code of upload.php. It truly does not handle anything server-side. What did I do wrong?
You need to make sure that PHP runs server-side. If there's no PHP handler installed, the server will return the content of your upload.php file as text. I think that's your primary problem.
Based on your platform, you may try:
http://www.wampserver.com/en/ (windows)
https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu-14-04 (Ubuntu)
https://www.mamp.info/en/ (MacOS)
First of all make sure your PHP works, by creating a file called info.php in your webroot folder with the following content
<?php
phpinfo();
This should display your configuration. Then you can start debugging the Javascript. The content type should by multipart/form-data so that the server knows it expects an upload.
Good luck!
I have currently a problem with my code. I would like to send JSON data with Ajax to a PHP script but it doesn't work. What does work is that the PHP script can be called by the Ajax code but it can't put the code into the .txt file. I have tried several things but I can't get it working. (I am trying to set the users array in the .txt file)
jQuery code:
var users = [];
$.ajax({
type: "POST",
url: hostURL + "sendto.php",
dataType: 'json',
data: { json: JSON.stringify(users) },
success: function (data) {
alert(data);
}
});
PHP Code:
<?php
$json = $_POST['json'];
$data = json_decode($json);
$file = fopen('test.txt','w+');
fwrite($file, $data);
fclose($file);
echo 'Success?';
?>
You must know that in PHP json_decode generates an Array that you can't write into an text file.
So only remove the json_decode command.
Since json_decode() function returns an array, you can use file_put_contents() that will save each array element on its own line
<?php
$json = $_POST['json'];
$data = json_decode($json, true);
file_put_contents('test.txt',implode("\n", $data));
?>
I'm trying to use Javascript to read stock data from yahoo finance at "http://table.finance.yahoo.com/table.csv?s=000001.sz", which returns a csv file and convert the data into json format as in http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-ohlcv.json&callback=? to be used in highcharts.
I tried using $.ajax get and jquery.get but neither worked. Can somebody tell me how to read the data from the url and convert it into json? Thanks a lot.
This can be easily done with PHP.
<?php
file_put_contents("data.csv", fopen("http://table.finance.yahoo.com/table.csv?s=000001.sz", 'r'));
//reads the CSV file and save value into an associative array
function csv_to_array($filename = '', $delimiter = ',')
{
if (!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE) {
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
if (!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
$arr = csv_to_array('data.csv');
//<pre></pre> tags appear only to prevent white-space collapsing
//prints the associative array
echo "<pre>";
print_r($arr);
echo "</pre>";
//displays the the JSON
echo "<pre>";
echo json_encode($arr, JSON_PRETTY_PRINT);
echo "</pre>";
?>
Now depending on the format of JSON that it acceptable to Highcharts API, you are required to tweak how the array is encoded into JSON.
Also avoid using JSON_PRETTY_PRINT if the size of the incoming data is large.
I guess you are facing Cross Domain issue. Use jsonp calls for Cross Domain requests. Use something like this
$.ajax({
url : "http://xx.xx.xx.xx/xxx/xxx",
type: "GET",
dataType: "jsonp",
jsonp : "callback",
success: function(data) {alert("Success");},
error: function(data) { alert("Error"); }
});
});