This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 7 years ago.
I wanna send values with ajax to php, save the values in a txt-file, and give the user the option to save the file.
I get the error message:
Warning: Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/randomColors/webroot/incl/theme.php:26) in /Applications/MAMP/htdocs/randomColors/webroot/palettes.php on line 26
What am I doing wrong?
function exportColors() {
$.ajax({
type: "POST",
url: "palettes.php",
data: ({data: 'John'}),
success: function (data) {
}
});
}
This is the code in export.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 html involved is a div:
<div class="palettesDIV" data-id="220">
When it is clicked the value in "data-id" will be submitted to export.php with the exportColors-function. Right now I am only using {data: 'John'} as a placeholder.
The exportColors-function is trigged by this code (that is placed inside a for loop)
palettesDIVArray[x].addEventListener('click', exportColors, false);
In your code in this line:
data: ({data: 'John'}),
try without ():
data: {data: 'John'},
Can you please post your form used to post the data? Your error say that You don't have any index named 'data' in your $_POST array. Anyway you can not check the existence of a value the way you are doing, the correct way is:
if (isset($_POST['data']))
{
...
}
And not:
$data = $_POST['data'];
if (isset($data))
{
In this way you are asigning the poste value to a variable and then checking against it
Please note this is only pointing to this issue and not solving the error you are facing. Post your HTML and we try to help you.
Related
There is a question bothering me, pls help!
I use jquery's ajax to call a php api.
$.ajax({
type:"POST",
dataType:"json",
data:{type:type,fid:fid,model:'star'},
url:'Recommend/Star/mark',
success:function (data) {
//do something
},
...
});
php code in Recommend/Star/mark method:
error_reporting(0);
set_time_limit(0);
ob_implicit_flush(true);
ob_end_clean();
ob_start ();
echo json_encode($boolMark);
ob_flush();
flush();
sleep(3);
$this->afterMark($uid, $fid);
I want php echo result to ajax immediately, but my codes do not work.
How to make php send result to ajax immediately, and continue to execute remaining code?
....
echo json_encode($boolMark . "<br>\n");
// get the size of the output
$size = ob_get_length();
// send headers to tell the browser to close the connection
header("Content-Length: $size");
header('Connection: close');
ob_end_flush();
ob_flush();
flush();
/******** background process starts here ********/
ignore_user_abort(true);
/******** background process ********/
set_time_limit(0); //no time limit
/******** Rest of your code starts here ********/
You also need to call these two functions after flush():
session_write_close();
fastcgi_finish_request();
I am working on a timetable for a school shedule.
On the site, there is a jquery ui datepicker, that can be clicked to update the timetable (based on the date that has been clicked on the datepicker)
Everything works except I have to click twice to update the timetable. So every other click gets the job done.
I narrowed my problem down to several points:
Caching - The browser uses the cached Data for the time table
Caching on the PHP side - I have maybe not set the correct headers to tell the browser not to cache data - Tried several headers - Maybe I am doing it wrong
I have to set the Ajax option caching to false - Tried it- Not Working
I have to maybe make the call syncronous so the browser waits for the response - Not sure about this - tried it though
I am making an ajax call inside the jquery ui datepicker onselect option. Like this:
Jquery Ajax Code
onSelect: function (date) {
//defined your own method here
// $("#timTableMon").empty();
// $("#timTableTue").empty();
// $("#timTableWen").empty();
// $("#timTableThur").empty();
// $("#timTableFr").empty();
$.ajax({
url : 'ajaxDate.php',
dataType: 'json',
cache: false,
type : 'post',
data : {
'sendDate' : date
},
success : function(data, status) {
$("#weekHeader").text(data.week);
$("#timTableMon").html(data.Mon);
$("#timTableTue").html(data.Tue);
$("#timTableWen").html(data.Wen);
$("#timTableThur").html(data.Thur);
$("#timTableFr").html(data.Fr);
// location.reload();
// window.location.href = "http://localhost /timeTable /public/test.php";
},
error : function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
PHP Code
$date = $_POST['sendDate'];
// $log->log_action("date from ajax", $date);
$date = new DateTime($date);
$week = $date->format("W");
// $log->log_action("week from ajax", $week);
// $log->log_action("week from ajax", $week);
$_SESSION['week'] = $week;
$timetable->week = $week;
header('Cache-Control: no-cache, no-store, must-revalidate'); // HTTP 1.1.
header('Pragma: no-cache'); // HTTP 1.0.
header('Expires: 0'); // Proxies.
$messages = array();
$messages['week'] = $week;
$messages['Mon'] = $timetable->drawMon();
$messages['Tue'] = $timetable->drawTue();
$messages['Wen'] = $timetable->drawWen();
$messages['Thur'] = $timetable->drawThur();
$messages['Fr'] = $timetable->drawFr();
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
echo json_encode($messages);
Any help would be greatly appreciated. Thank you
I am having trouble executing this code in my index.php.
It says 'CartAction not set'
I need your help php gurus. I can display any files you need to fix this error.
Here is the code:
// Handle AJAX requests
if (isset ($_GET['AjaxRequest']))
{
// Headers are sent to prevent browsers from caching
header('Expires: Fri, 25 Dec 1980 00:00:00 GMT'); // Time in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
header('Content-Type: text/html');
if (isset ($_GET['CartAction']))
{
$cart_action = $_GET['CartAction'];
if ($cart_action == ADD_PRODUCT)
{
require_once 'C:/vhosts/phpcs5/presentation/' . 'cart_details.php';
$cart_details = new CartDetails();
$cart_details->init();
$application->display('cart_summary.tpl');
}
else
{
$application->display('cart_details.tpl');
}
}
else
trigger_error('CartAction not set', E_USER_ERROR);
}
else
{
// Display the page
$application->display('store_front.tpl');
}
It's because your code is expecting a parameter named 'CartAction' in the url
Example:
www.yoursite.com/?CartAction=ADD_PRODUCT
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character. Source
You check if $_GET['CartAction'] has a value ( from the above url this superglobal variable has the value 'ADD_PRODUCT' )
What #Mackiee (in comments) and your error message are both telling you is that the problem is that there is a query parameter missing. The URL that calls this needs to include either ?CartAction=ADD_PRODUCT or &CartAction=ADD_PRODUCT
I know there are already many questions about forcing a download with PHP, but I can't find what I'm doing wrong and what should I do.
I'm having an list with filenames, and I want to download one of them by clicking a button.
My jQuery:
$(".MappeDownload").on("click",function(e){
e.stopPropagation();
fileId=$(this).val()
$.post("ajax/DownloadFile.php",{ id : fileId})
})
and on the server side I have a table with the file names and the file path.
$sql = "SELECT vUploadPfad, vUploadOriginname FROM tabUpload WHERE zUploadId='$_POST[id]'";
$result = mysql_query($sql) or die("");
$file = mysql_fetch_array($result);
$localfile = $file["vUploadPfad"];
$name=$file["vUploadOriginname"];
$fp = fopen($localfile, 'rb');
header("Cache-Control: ");
header("Pragma: ");
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($localfile));
header("Content-Disposition: attachment; filename='".$name."';");
header("Content-Transfer-Encoding: binary\n");
fpassthru($fp);
exit;
The AJAX request is successful, I'm getting the right header(filesize, filename etc...) but the download are not starting.
You don't need ajax, just redirect to the address that forces the download. The page will not change so, instead of $.post("ajax/DownloadFile.php",{ id : fileId}) you should have location.href = "ajax/DownloadFile.php?id="+fileId and, in your PHP file, convert your $_POST to $_GET
The response to an AJAX request will never trigger a download. AJAX requests are silently handled in the background, they never trigger visible activity directly.
You need to redirect the main page or an iframe to trigger the download.
Return file name in ajax
Do window.location.href = 'returned file name' and download will start!
There is my solution:
<script>
//downloading the file
$(document).on('click', '.download_file', function(){
var path = $(this).data("name");
var action = "download_file"
$.ajax({
url: "action.php",
method: "POST",
data: {path:path, action:action},
success: function(data)
{
window.location.href = path;
}
})
})
</script>
And the action.php
<button type"button" name="download" data-name="'.$name.'" class="download_file btn btn-success btn-xs">Pobierz</button></td>'
I am trying to call a PHP function using AJAX. Below is the script I used.
<script type="text/javascript" src="jquery.1.4.2.js">
$(document).ready(function () {
// after EDIT according to
// #thecodeparadox answer
$('#local').click(function(e){
e.preventDefault();
e.stopPropagation();
promptdownload();
});
});
function promptdownload(e)
{
$.ajax({
type: "POST",
url: "js/prompt.php",
data: { "get" : "runfunction", "action" : "promptlocal" },
success: function (response) {
}
});
}
</script>
The corresponding PHP code (prompt.php) is:
<?php
$path1 = "downloads/1.jpg";
$browserFilename1 = "Local Travel";
$mimeType1 = "image/jpeg";
function promptToDownload($path, $browserFilename, $mimeType)
{
if (!file_exists($path) || !is_readable($path)) {
return null;
}
header("Content-Type: " . $mimeType);
header("Content-Disposition: attachment; filename=\"$browserFilename\"");
header('Expires: ' . gmdate('D, d M Y H:i:s', gmmktime() - 3600) . ' GMT');
header("Content-Length: " . filesize($path));
// If you wish you can add some code here to track or log the download
// Special headers for IE 6
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
$fp = fopen($path, "r");
fpassthru($fp);
}
if ($_POST["action"] = 'promptlocal')
{
promptToDownload($_GET[$path1], $browserFilename1, $mimeType1);//comments
}
?>
This is how I code the button that is supposed to trigger the function:
<input type="button" id="local" name="local" value="Local Travel">
My expected output is to have this button promt the user: "where to save 1.jpg file".
However I couldn't make it work.
Any advise is highly appreciated.
$('local').click(function(e){
should be
$('#local').click(function(e){
As local is an id so you should use # before it. And also in your php code there are some missing quotes.
Use Firebug(FF), Dragonfly(Opera), Developer Tools(Chrome). You can see all javascript errors, warnings and exceptions, and can see ajax requests data.
data: { "get" : "runfunction", "action" : "promptlocal" },
Try to remove the quotes from "get" and "action".
Like this :
data: { get : "runfunction", action : "promptlocal" },
It looks to me like you are trying to download a file with jquery/ajax. You will not get this to work with only ajax. This question has been answered several times on stackoverflow.
I hope this link will help you: Ajax File Download using Jquery, PHP