I have a PHP function
function ExportExcel()
{
// code
}
and a link on the page Download in Excel
<a>Download in Excel</a>
So what I want is when users clicks on that link, PHP function would be called and data will be downloaded in excel.
I may need to Ajax for that. How do I go about doing that ?
You could possibly just use a GET statement, so it would look something like this...
HTML
Download in Excel
PHP
function ExportExcel()
{
// code
}
if($_GET['init'])
{
ExportExcel();
}
here is the function i implemeted recently:
$('#toexcel').live("click",function() {
$.ajax({
url: "toExcel.php",
data: "sql="+encodeURIComponent(sql),
beforeSend: function(){
$("#wait").show();
},
complete: function(){
$("#wait").hide();
},
success: function(response){
window.location.href = response.url;
}
});
});
where sql variable actually stores sql query to the server,
and then toExcel.php if getting passed sql, submitting it to the server and outputs the result using PHPExcel() object.
EDIT
i think i understood what you trying to achieve. your ExporExcel() function already outputs the results you need, right? is so, then you can do it as follow:
$('#toexcel').click(function() {
$.ajax({
url: "toExcel.php", // should contain and _call_ you ExportExcel() function
beforeSend: function(){
$("#wait").show(); // this is loading img to show
},
complete: function(){
$("#wait").hide(); ;// this is loading img to hide once complete
},
success: function(response){
window.location.href = response.url;
}
});
});
first let me make sure you know php is only parsed when the page is first being distributed. If you click a link on the page, it has no idea the php function on the same page exists because the function only existed server-side while the code was being parsed. That being said, you can easily make a separate page called download.php and call your function on that page. Then your link can just link to that page.
If you want your custom download page to return to the user as an excel file, you can use custom php headers to convince the browser that it is downloading an excel file. (you'd have to specify the MIME type for excel files)
edit:
this would cause a download to start of an excel file created by your function call and activated by your link click. You don't need any JS or JQuery for this.
edit2:
here's example code for the download file to get you started
<?php
header("Content-type: application/excel");
print($data); /* print out the contents of the excel file here */
exit();
?>
If you do it like this, your php page will not redirect from your original page, but will bring up a download box from the browser instead. If your using csv files instead of xls files, you'll need to change the mime type.
you can handle the request in your js scrpit file
$("a").click(function(){
jQuery.ajax({
url: "path/to/controller",
type: "POST",
dataType: 'json',
data: {'mentod':'ExportExcel'},
success: successCallback,
error:failureCallback
});
});
Just provide link of that excel file in href of anchor , browser will download automatically
If your file form DB then providelink of excel.php , and in excel.php do processing of getting excel file and creation of it .
read this artical..do like that
Related
I have a web page that the user can select a team and when they do, I want an image.src to change to reflect the new choice. When the user makes the change, the teamID is saved in a settings file. I can't get the AJAX call to access the PHP file or function.
When it makes the AJAX call it looks like it can't access the PHP file- I get an error
POST: http://192.168.1.104/.....functions.inc.php 404 not found - I tried every path I could think of to get to the functions.inc.php file but it didn't work.
Here is the Ajax code: (the functions.inc.php file is in the same directory as this file)
function updateLogo(){
<?error_log("In update logo "); ?>//test to see if it gets in the function
$.ajax({
url: 'functions.inc.php',
data: {action: 'getLogo'},
type: 'post',
success: function(output) {
alert(output);
}
});
alert (output);
document.getElementById('teamLogo').src = 'output';
}
Any suggestions?
Because the device is running its own PHP server and deamon, the correct url is a unique url to this device.
Thanks for the help
I've read all the articles but cant seem to get my ajax response into a PHP variable. Please can you advice. I want to assign rowid to a PHP variable.
$(document).on('click', '#updateid', function() {
var vallab = $('#idval').val();
var rowid;
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
console.log(rowid);
return rowid;
});
my a.php code is below
<?php
# Fetch the variable if it's set.
$lab_id = (isset($_POST["labid"])) ? $_POST["labid"] : null;
echo $lab_id;
?>
I am getting the response back with the id, and want to use it on that page
I want to pass rowid into a PHP function so I need to get the value of rowid.
Please can you advice?
I cant seem to get my ajax response into a PHP variable
Well, the AJAX response came FROM a PHP file, right? So why don't you do whatever you need to do with the response right in that PHP file?
$.ajax({
url:'THIS IS YOUR PHP FILE',
type: 'POST',
data: {THIS IS THE DATA YOU SEND TO PHP},
success: function(data){
console.log(data); //THIS IS THE RESPONSE YOU GET BACK
}
});
You can't use it. Javascript is a scripting language which run in browser when the dom is loaded and elements are visible.
PHP is a serverside language and run on server before the page is loaded.
You need to understand the lifecycle of your application. Your php code executes once, it runs the full script from top to bottom when the page loads. At the point the script starts if can only access the post that came with the request (e.g if you clicked submit on a form then the 'action' of the form receives the post). Any number of things can happen in your script, but once it's finished the php is gone, and so is the post (in basic terms). So you no longer have any access to the php which created this page.
Ajax allows you to update a section of your page - it sends a request to your sever and runs some php code - you must understand that this is a new and separate request, so the new post submission only exists in the lifecycle of this new execution and is in now way linked to the page that has already finished loading. Now you could ask Ajax to call your original script, but that wouldn't affect your page at all because the page does not reload. What you would get is a strange looking response which you (probably) couldn't do anything useful with.
Ajax allows small specific changes to the page, so when you get your response (which I assume you get in a format you want since you don't ask about it and you have a console.log) you then need to do something with jQuery/javascript. Instead of returning rowid write a javascript function like :
function printRowId(rowid) {
$('#your html div id here').text('Row id is ' + rowid);
}
and then call it in your response:
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
printRowId(rowid);
return rowid;
You can use Ajax to update your data, update your database and then reflect the changes on the current page, but you cannot use it to pass directly to the php that has already finished executing
i have a simple form when user submits form i send form data from ajax to controller where my pdf generated code is, but after successful ajax call PDF is not downloading
here is my controller code
$temp=TempInvoice::where('id',$id)->get();
$pdf = PDF::loadView('pages.pdf', ['data'=>$temp]);
$pdf->download('invoice.pdf');
and my javascript ajax
var data2=result
$.ajax({
type: 'POST',
url: '/tyre/api/pdf',
data: {data:j},
success: function (data) {
console.log(data);
},
})
can you please help me with this,
(for normal request it works fine but for ajax request it wont work)
can you please help me with any solution or should i submit form first and then generate pdf?
please let me know any inputs you want from my side,
any tips or comments
Replace this code with $pdf->download('invoice.pdf');
return $pdf->stream('invoice.pdf')
->header('Content-Type','application/pdf');
used stream function with header
The alternative way (As per my comment used return)
$pdf = PDF::loadView('pages.pdf', ['data'=>$temp]);
return $pdf->download('invoice.pdf');
Finally: make sure you you configure package properly. Reference for package configuration
I need to send data to php file and download it.
My script is working correctly when I call it directly, but when I send data with AJAX it doesn't download at all.
My question would be: How to send data to php file and download file automatically but of course stay on the same page?
Part of the code that is working when called directly...
PHP file
header('Content-Description: File Transfer');
header("Content-type: application/ms-word");
header("Content-Disposition: attachment;Filename=ponuda.doc");
$productsArr = json_decode($_POST['object']);
$html = "<tr>";
foreach($productsArr as $product)
{
//something
}
....
echo $html;
AJAX call:
$.ajax({
type: "POST",
url: "test_download.php",
data: { object:productsJSON },
cache: false
});
I do the following:
Include the exchanger.js javascript file in your head section
Initialize the exchanger object on page load: theBuffer = new exchanger('dwnld');
Create a javascript function that you will call whenever you want to initiate a file download
:
function downloadFile(){
// you can add parameters to the function as needed to pass in dynamic data sent to the back end download handler
data = "http://your_backend_file_download_handler.php?param1=val1¶m2=val2&etc=whatever"; // send whatever data you need to the php program via query string parameters
theBuffer.sendData(data); // initiate the file download
}
Note: The php back end file download program that handles the requests can do whatever it needs to do with the parameters you send it in order to put together/retrieve the correct data/file for download. After much tinkering this combination is what consistently works for me
Include this little bit of html in your body section. I usually put it just before the closing body tag:
<iframe name="dwnld" id="dwnld" style="width:0;height:0;border:0">
</iframe>
Note: the id value assigned to the iframe is the same value given in step 2 when initializing.
The result is that the user never leaves the current page to download any number of files because the actual download is handled in a separate page (aka the iframe). I have used it without issue in all of my projects for years now.
I think You can't send header to browser by ajax, but You can use this, great thing.
http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/
$.fileDownload('file.mp3')
.done(function () { alert('File download a success!'); })
.fail(function () { alert('File download failed!'); });
I have an application where a user is allowed to save some text data into a MYSQL database through a web interface. In addition, they can also attach a file to this text and I save this into a blob field. The file types that get attached are simple .txt files.
I am able to save this data into the database but I am having trouble retrieving it. This is what I am doing to retrieve it right now:
//Events that take place when trying to retreive an attached file
function getFile(rowid){
//Make an AJAX Request to fetch the file
$.ajax({
type: 'get',
url: 'point-of-contact.php',
data: 'page=attachment&row='+rowid,
dataType: 'text',
success: function(data) {
console.log (data);
}
});
}
The AJAX request above leads to the following PHP code:
$attachments = $poc -> getPOC($_GET['row']);
header('Content-type: text/plain');
echo $attachments;
The problem I face is that when I console log the data received from the AJAX request I get this:
How do I go about getting the data in simple text format?
Could it be that the way I am uploading the file to the database is incorrect? This is how the file is uploaded to the DB:
//File upload code
var fileInput = document.getElementById('upload');
var file = fileInput.files[0];
//Hide the save button
$("#save-button-1").hide();
//Make the AJAX request
$.ajax({
type: 'post',
url: 'point-of-contact.php?page=add',
data: 'point_of_contact=' + $("#textarea1").val() + '&point_of_contact_attachment=' + file,
success: function(data) {
$('#done-1').show();
setTimeout(function() {
$('#done-1').fadeOut();
}, 2500);
$('.loader').fadeOut();
}
});
There is problem in your upload section. The line
var file = fileInput.files[0];
assignes file object into file variable. Later, when you add it to
"point_of_contact_attachment="
it gets converted to string. So you will have
"point_of_contact_attachment=[object file]"
And that is it.
try pointing the browser directly to the file instead of using ajax.
Like this
document.location = point-of-contact.php?page=attachment&row='+rowid;
Since it is not a file the browser can read, it will just download it.
However you will still need to get the TXT via ajax, because document.location redirect to the user to a plain text page.