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
Related
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.
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 displaying a report to the client. I have made an ajax call that passes in a "delivery" variable, which is either "display" or "download".
Here is the ajax call:
$.ajax({
type: 'POST',
url: 'ajaxController.php',
dataType: 'json',
data: {
e: "getReport",
reportName: reportName,
delivery: delivery
},
success: function (data) {
if (delivery === 'display') {
$("#reportDisplayTableHeader").html('');
$("#reportDisplayTableBody").html('');
Lifestyle.selectedReportRows = data;
$.each(Lifestyle.selectedReportRows, function(key, row) {
rowHTML = '<tr>';
$.each(row, function(parameter, value) {
if (isHeader) {
rowHTML += '<td>' + parameter + '</td>';
} else {
rowHTML += '<td>' + value + '</td>';
}
});
rowHTML += '</tr>';
if (isHeader) {
$reportHead.append(rowHTML);
isHeader = false;
} else {
$reportTableBody.append(rowHTML);
}
});
$("#reportCaption").show();
}
}
});
And here is the server side PHP:
if ($delivery == 'display') {
echo json_encode($return);
} else if ($delivery == 'download') {
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header('Content-Description: File Transfer');
header("Pragma: no-cache");
header("Expires: 0");
echo "record1,record2,record3\n";
}
In the case of "display" it returns the json just fine and the client side displays a table.
In the case of "download", I want it to pop up a download dialog where it can save off the CSV that I echo'd to them.
But what is happening is that the call is completing and the headers / csv is crossing the wire (thanks Fiddler), but no download dialog is appearing and the client does not know that I pushed csv to them.
What do I need to do in order to get the download dialog to pop up?
Thanks.
An Ajax call can not download something, or at least it is really hard.
Better is to open a new window to the location of the php file (Then you should be using GET though) and then the user will be promted to download it.
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 have a simple search form with a search box and a result box.
When I type a search word a request is created like: http://www.site.com/php_handler.php?s=hello
In the php script and a result is given back to the script this way:
<?php return $s; ?>
The problem is that my htmlrequest stops at readyState 3 it doesn't get to 4.
The javascript looks like this:
var xmlhttp = sajax_init_object();
function sajax_init_object() {
var A;
try {
A=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
A=new ActiveXObject("Microsoft.XMLHTTP");
} catch (oc) {
A=null;
}
}
if(!A && typeof XMLHttpRequest != "undefined")
A = new XMLHttpRequest();
if (!A)
sajax_debug("Could not create connection object.");
return A;
}
function getSearchItem()
{
gs=document.forms.mainform.resultsfield;
var searchword=document.forms.mainform.searchform.value;
if (searchword.length>=3)
{
setWaitCursor();
clearResults();
var uri = "http://site.com/ajax_handler.php?s="+searchword;
console.log(uri);
xmlhttp.open("GET", uri, true);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4) {
processResults(xmlhttp.responseText);
removeWaitCursor();
}else{
console.log(xmlhttp.readyState);
}
}
xmlhttp.send(null);
}
else
{
alert("please add at least 3 characters .");
}
}
Can someone tell me why it stops at 3?
edit: here is also the php code:
<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
session_start();
//include main file
require_once($_SESSION["FILEROOT"] . "xsite/init.php");
//check if formulier is posted
$zoekterm = C_GPC::getGETVar("s");
$s="";
if ($zoekterm != "") {
$query="SELECT number,name,city,zib,zip_annex FROM articles WHERE version='edit' AND (naam LIKE '%$school%' OR brinnummer='$school') ORDER BY name";
if ($rs=C_DB::fetchRecordSet($query)) {
while ($row=C_DB::fetchRow($rs)) {
if ($row["plaats"]!="") {
$s.=$row["name"].", ".$row["city"]."|".$row["number"]."\n";
} else {
$s.=$row["name"].", ".$row["zip"].$row["zip_annex"]."|".$row["number"]."\n";
}
}
}
}
return $s;
?>
edit:
I missed a semicolon in my php script and now the ready state only gets to 2
edit:
The problem is even different. It gets to 4 but it doesn't show the result text.
1> Don't send Cache-Control: post-check=0, pre-check=0. These don't do what you think they do, and they're entirely unnecessary.
2> Your AJAX results page needs to send a Content-Length or Connection: Close header.
3> Try adding a random to your request URL to ensure you're not looking at a stale cache entry.
ReadyState 3 => Some data has been received
ReadyState 4 => All the data has been received
Maybe the XMLHTTPRequest object is still waiting for some data.
Are you sure your php script ends correctly ?
Is the content-length alright ?
To debug this you have two options, type the URL directly into the browser [since you are using a GET] and see what is happening.
OR
You can use a tool such as Fiddler and see what is exactly happening with the XMLHttpRequest