I want to save a value to a txt-file and download it to the user.
Right now, the value is being printed into the txt-file correctly, but the readfile function is not triggered, thus no downloading begins.
The php, this code is located on the same page as the ajax call.
<?php
if (isset($_POST['data']))
{
$handle = fopen("file.txt", "w");
fwrite($handle, $_POST['data']);
fclose($handle);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');
exit;
}
?>
The javascript, there is no url because the data is to be sent to the current page.
function exportColors() {
var exportData = this.dataset.id;
$.ajax({
type: "POST",
data: {data: exportData},
success: function (data) {
console.log(data);
}
});
}
You need to separate the functionality, that is, post the data to PHP first, save the content of the text file and then, in a second request, let the user download the file. So one (skeleton) approach would be:
JS File:
function exportColors() {
var exportData = this.dataset.id;
$.ajax({
type: "POST",
data: {data: exportData},
success: function (data) {
// redirect or print out a link
}
});
}
PHP File for the first request (saving the content):
<?php
if (isset($_POST['data'])) {
$handle = fopen("file.txt", "w");
fwrite($handle, $_POST['data']);
fclose($handle);
// give back some unique id or the unique filepath
}
?>
PHP File for the second request (be it through clicking on a link or after having been redirected):
// essentially everything that outputs your file
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');
exit;
Comments:
Either give back a unique filepath or via a handle through a database (more secure, but more complex as well). Besides, why should the user download the unchanged data he has formerly submitted? Is there more to it than meets the eye?
Ok I'm going out on a limb so take this with a grain of salt.
You said this request is going to the current page? Does that mean you've excluded (for the sake of brevity) HTML content from the PHP file you're showing us? If you have ANY content above your opening <?php tag, then any call to header will fail with an error (because headers must come before the body of a request). This would cause the script to terminate and prevent the readfile line from ever being reached.
Are your headers being sent? Do you see anything in the error log? If the answers to these are yes and no respectively then I'm wrong and you can ignore this.
Due to security reasons, ajax won't be able to download/save the file to the client's system because of java-script constraints.
Instead you can use
jquery.fileDownload.js
Please have a look at http://jqueryfiledownload.apphb.com/
Hope this helps.
you can't
beacuse javascript is not able to write on user file system.
see answer
Download a file by jQuery.Ajax
explain problem very well
The following Ajax generates a new file on the server at runtime AND downloads it to the client machine's /downloads directory with a single click. It uses Javascript to download the file, not PHP readfile().
await $.ajax("generateFile.php", {
type: "POST",
data: {
param_1: param_1,
param_2: param_2
},
success: function(data){
var a = $("<a>")
.attr("href", "path/filename_on_server.txt")
.attr("download", "filename_on_client.txt")
.appendTo("body");
a[0].click();
a.remove();
},
error : function(data) {
alert("ajax error, json: " + data);
}
});
Related
I’m trying to cut the plugin for WordPress. Help, who than can, please 🙂
The JavaScript data is taken from the backend and returned to PHP, which creates a file on the server. The task is to give it to the user in the browser. Old script gave it without problems download.php:
header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename='$name;');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($name));
if (ob_get_contents()) ob_end_clean();
flush();
readfile($name);
But for security, you must prohibit direct access, OK:
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
Accordingly, the call to AJAX hung on success began to open an empty window:
$.ajax ( {
type: "POST",
url: myAyax.ajax_urls.write_url,//Here, the function hooked via the hook to admin-ajax.php is called
data: {
ids: [], //This is some kind of data
action: 'write_file_server', //We pass the hook. Who writes a file with data to the server.
},
success: function ( result ) {
window.location = myAyax.ajax_urls.download_url //Here was a link to the direct call download.php (see above)
}
} );
Tried to cause, in function caused through a hook: include (‘download.php’);
Called, sends the contents and code to the buffer 200, but does not swing;)
The link in succes-e on the file opens its contents, and also does not swing, of course 🙂
Help ideas, please.
I cleaned up your javascript formatting a little, and it seems to be working for me. Is that what you were looking for?
$.ajax ( {
type: "POST",
url: myAyax.ajax_urls.write_url,//Here, the function hooked via the hook to admin-ajax.php is called
data: {
ids: [], //This is some kind of data
action: 'write_file_server', //We pass the hook. Who writes a file with data to the server.
},
success: function ( result ) {
window.location = myAyax.ajax_urls.download_url //Here was a link to the direct call download.php (see above)
}
} );
I found a solution :) I need to do a hook on the Get request, and call it with a link:
window.location = window.location.href+'&filename=file.file';
I'm using PHP to compile an app on an apache server based on the input provided by the user and then provide the app to them using the readfile() method.
The problem that I'm facing is that instead of actually downloading the app, the .apk file is being opened as a text file.
I have added the android app mime type in the PHP code.
My php code is :
<?php
echo "Please wait while the app is being generated, it can take around 10 minutes for the build to finish.The completed app will be mailed to you ";
if(isset($_POST['timestamp']))
{
$uid = $_POST['timestamp'];
exec("sudo python /var/www/html/appgenserver.py $uid");
header("Content-Description: File Transfer");
header("Content-Type: application/vnd.android.package-archive");
header("Content-Transfer-Encoding: Binary"); //Adding or removing this hass no effect
header('Content-Disposition: attachment; filename="Foo.apk"');
ob_clean();
flush();
readfile("/var/www/html/".$uid."/releaseapk.apk");
exit();
}
?>
Any help would be appreciated.
I think you can solve it by removing the echo. Don't output to the page before the headers have been sent.
The garbled output caused by the buffer is not clean, search for the output on the page before headers or Try using ob_end_clean() instead of ob_clean() and put it before your header()
So what I did was, rather than return the app from PHP script, I returned it URL to the AJAX call.
From there I navigated to that URL and the download initiated automatically.
PHP code :
<?php
{
echo "http://server_ip/release/".$uid."/releaseapk.apk";
}
?>
Ajax cal :
$.ajax({
type: "POST",
url: "/test.php",
data: { timestamp : timestamp },
success: function(response){
console.log("Success",response);
window.location = response;
}
});
can any one help me please
What Im trying to do is a phone app using HTML5, JQUERY, Json and PHP. I cannot use PHP pages in this as I will be packaging it with Phone Gap Cloud Compliler.
I have tried using many scripts and suggestions that I have researched on the internet but cannot seem to get this to work.
On the page I need to retrieve data from the database there are 6 text boxes or divs I wish to populate using a on page ajax request to a PHP processing page that gets the required data and forms it into a Json string, the following scripts will show where I am at presently.
PHP Page:- this works as far as getting the data from the database and from the research I have done succssefully parces it into a Json format
PHP Script **********************************************
<?php
include_once 'db_connect.php';
header("Content-Type: application/json"); //this will tell the browser to send a json object back to client not text/html (as default)
session_start();
$return_arr = array();
$sql = "SELECT * FROM `autumnTerm`"; //query
$result = mysqli_query($mysqli, $sql);
while($row = mysqli_fetch_array($result)) {
$row['term1start'] = date('d-m-y', strtotime($row['term1start']));
$row['term1finish'] = date('d-m-y', strtotime($row['term1finish']));
$row['term2start'] = date('d-m-y', strtotime($row['term2start']));
$row['term2finish'] = date('d-m-y', strtotime($row['term2finish']));
$row_array['term1start'] = $row['term1start'];
$row_array['term1finish'] = $row['term1finish'];
$row_array['term2start'] = $row['term2start'];
$row_array['term2finish'] = $row['term2finish'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
?>
this returns the following json :-
[{"term1start":"01-04-15","term1finish":"02-04-15","term2start":"03-04-15","term2finish":"04-04-15"}]
which I believe to be the right format.
The Jquery:-
<script>
I think I am right in believing that document ready should run the jquery script on page load
$(document).ready(function() {
the processing page address which is associated to a variable
var url = "http://www.newberylodge.co.uk/webapp/includes/retrieveAutumn.inc.php";
The ajax request defining the request elements
$.ajax({
type: "POST",
cache: false,
url: url,
dataType: "json",
success: function(data) {
$('#termoneError').text('The page has been successfully loaded');
},
error: function() {
$('#termoneError').text('An error occurred');
}
});//ajax request
});//ready function
</script>
If anyone would be so kind as to helping me figure this out I would be most greatful, I have been trying to resolve this for over a week now
I havent posted the html trying not to swamp the question with code, but if its needed I will put it up on request
try this:
$.ajax({
type: "GET",
cache: false,
url: url,
dataType: "json",
success: function() {
console.log()
$('#termoneError').text('The page has been successfully loaded');
},
error: function() {
$('#termoneError').text('An error occurred');
}
});//ajax request
});//ready function
</script>
and try to see the console is there any error?
you should try for the error Cross-Origin Request Blocked to put proper header
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET,POST,OPTIONS');
header('Access-Control-Allow-Credentials: true');
the rest code its ok
I follow what it's write here Downloading a file with a different name to the stored name .
But i'm not sur too understand everything because it's don't work when i try do it with ajax. I signal that i use Smarty.
This is my html code :
// In $attache.id their is the id of the data i want to dowload in the database
<a href='javascript:uploadAttachFile({- $attache.id -});'><img src='../tools/telecharger.gif' /></a>
This is my jQuery code :
function uploadAttachFile(idAttache)
{
$.ajax({
//This permit me to go to the php function
url: ajaxURL("attacheUpload"),
type: "POST",
data: {
idAttache: idAttache
},
success: function(data)
{
alert(data);
}
})
}
This is my php code :
//Permit to have the path and new title of the file
$attacheEntite = Model_AttacheDB::getNameAndPathAttachFile(request('idAttache'));
$file = 'path' . $attacheEntite['path'];
if (file_exists($file))
{
header('Content-disposition: application/force-download; filename="' .$attacheEntite['titre']. '"');
header("Content-Type: application/pdf");
header('Content-Transfer-Encoding: binary');
header("Content-Length: " . filesize($file));
header("Pragma: ");
header("Expires: 0");
// upload the file to the user and quit
ob_clean();
flush();
readfile($file);
exit;
}
I know that it pass by my php code because the ajax reuest pass by succes and alert an incomprehensible code who is certainly the code of the pdf file when i read it.
You can't make the client download the file through an ajax request.
What you are doing here is reading the file server-side with PHP and returning his content to the caller script ( in fact you see the content in the "data" variable )
Without ajax, you can call the script like this:
<a href='path/to/your/phpscript.php' target='_blank' ><img src='../tools/telecharger.gif' /></a>
And it will send the file to the browser
EDIT: if you add the attribute target="_blank" to the anchor it will open the download in a new tab, without reloading the current page
I am trying to send data that i got from a jquery call and now i want to save it to a file on the server with php.
function getSVG(){
svghead = svghead + $('#test').html();
$.ajax({
type:"POST",
data: svghead,
url: "xyz.php",
success:function(data){
.....
}
});
}
and in php my code is:
<?php
header('Content-Type: text/html; charset=utf-8');
$data = $_POST['data'];
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
fwrite($myfile, $data);
fclose($myfile);
?>
but the created file never contains any value. it s just empty. as far as i tested, i guess it is just a syntax mistake but where or what is wrong? thx for any help
You need to specify the parameter name in order to PHP recognize it:
data: {
data: svghead
}
With the object above you're sending a data paramenter with the value equal to your svghead variable.