I am trying to build a CSV file in PHP, then call the PHP file from an AJAX call, which will then initiate a download of the CSV file upon success of the AJAX call. This works fine if I save a physical copy of the .csv on the server, but I would like to use php://ouput so I do not have to worry about physical files clogging up the server. Is it possible to initiate a download from returning php://output to AJAX? Here is my code:
HTML/jquery:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script type="text/javascript" language="javascript" src="jquery.js"></script>
<script type="text/javascript">
$("#download").live("click", function() {
var request = $.ajax({
dataType: 'html',
url: 'php.php',
success: function(response) {
alert('Finished');
}
})
})
</script>
</head>
<body>
<h1 id="download">DOWNLOAD</h1>
</body>
</html>
PHP:
<?php
header('Content-type: application/vnd.ms-excel');
header('Content-disposition: attachment; filename="test.csv"');
$f = fopen('php://output', 'w');
fwrite($f,'this,is,a,test');
fclose($f);
readfile('php://output');
return;
?>
I am not sure how to get this to return a File Save dialog from my AJAX call.
This has to be simple, but I can't seem to find any examples that combines these two issues.
You can do this by creating and sending form via jquery (page not reloaded):
$(document).on('click', '#download', function () {
var form = $(document.createElement('form'));
form.attr('action', 'php.php');
form.attr('method', 'GET');
form.appendTo(document.body);
form.submit();
form.remove();
});
Also you can pass post parameters if need:
$(document).on('click', '#download', function () {
var form = $(document.createElement('form'));
form.attr('action', 'php.php');
form.attr('method', 'POST');
var input = $('<input>').attr('type', 'hidden').attr('name', 'x').val('x value');
form.append(input);
form.appendTo(document.body);
form.submit();
form.remove();
});
The following works, but is highly inneficient as it calls the php.php file twice. Does anybody have any better ideas?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script type="text/javascript" language="javascript" src="jquery.js"></script>
<script type="text/javascript">
$("#download").live("click", function() {
var request = $.ajax({
dataType: 'html',
url: 'php.php',
success: function(response) {
window.open('php.php');
}
})
})
</script>
</head>
<body>
<h1 id="download">DOWNLOAD</h1>
</body>
</html>
Is there anyway to cache 'php.php' for just this instance so that it loads instantly under window.open('php.php'), but will reload contents when I click download next?
Why does window.open(response) not work the same?
look this:
if (!headers_sent()) {
// seconds, minutes, hours, days
$expires = 60*60*24*14;
header('Pragma: public');
header('Cache-Control: maxage=' . $expires);
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT');
}
Note: this will not work with POST requests, just GET.
To allow for a file download, you can simply call the below code (say on a button's onclick):
window.open(<file-url>);
Hope this helps.
Related
When I do:
<html>
<head>
</head>
<body>
<?php
$value = isset($_GET['send_request']) ? $_GET['send_request'] : false ;
if ($value) {
echo $value;
return;
}
?>
A
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function test() {
// data to send
var data = { send_request: 'Yes'}
request = $.ajax({
method: 'get',
data: data
});
request.done(function(response){
console.log(response);
});
}
</script>
</body>
</html>
In the console I am getting:
<html>
<head>
</head>
<body>
Yes
Why is this?
The error here is that your php code executes after you have already outputted this part:
<html>
<head>
</head>
<body>
Move the php code to the top of the page and it will fix this :)
Keep in mind that when you execute php script, php will not ommit html, but rather consider it output and just carry on :)
The best practice is to move your PHP codes to a separate PHP file and specify it's path in the url option of your ajax function. That new PHP file should of course not contain HTML before your PHP codes as already pointed out.
I'm tryin to get a value in URL from php file via $.get(), here is the code:
PHP folder called 'jquery_con4.php':
echo (isset($_GET['req'])) ? 'found':'notfound';
JQuery called 'pass.js':
$.get('connection/jquery_con4.php', function(data){
alert(data);
});
the main folder called 'password_c.php' which include the javascript called 'pass.js' which has $.get but it shows me in note 'notfound', & if remove if echo, it shows be 'undefined index:req'
--- URL is: 'http://localhost/series/skyface/password_c.php?req=65yDq0zI39UcRSF'
Thanks!
http://localhost:8888/series/skyface/password_c.php?req=65yDq0zI39UcRSF
In order to pass the 'req' value from the URL querystring to the jquery_con4.php script, you need a JS function that will grab it for you and pass it into an ajax request.
Below is an example of how that might work.
/series/skyface/password_c.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="../../main.js"></script>
</body>
</html>
/main.js:
jQuery(document).ready(function($) {
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
function success(data) {
console.log(data);
}
$.ajax({
url: '/connection/jquery_con4.php',
data: {req : getParameterByName('req')},
success: success
});
});
/connection/jquery_con4.php:
<?php echo(isset($_GET['req'])) ? 'found' : 'notfound'; ?>
this is the server side code
<?php
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 01 Jan 2016 00:00:00 GMT');
header('Content-type: application/json');
$id = $_GET['id'];
$data = array("Hello", $id);
echo json_encode($data);
?>
and this is the client side code
<html>
<head>
<script src="jquery-1.1.1.min.js"></script>
<script language="javascript">
function show(json) {
alert(json);
}
function run() {
$.getJSON("/localhost/jserver1.php",
{ id: 567 },
show);
}
window.onload=run;
</script>
</head>
<body>
JSON Test Page.
</body>
</html>
What i want to do here is i want to send messages between client and server using php and json. when i run the server side code i am getting the output as hello with the id given in the url in the localhost,but when i run the client side code i am getting only the body of the html page,I am not getting the alert with the input id that is there in the run method.Please someone tell me what is the problem
Instead of
$.getJSON("URL",
{ id: 567 },
show
);
window.onload=run;
Use -
$.getJSON("URL",
{ id: 567 },
function(response){
show(response);
});
window.onload=run();
Try removing the / in front of /localhost/jserver1.php and adding http://.
Currently it refers to localhost/localhost/jserver1.php
Still very bad code, you should split up your files. But here we go:
<?php
if($_GET['id']) {
$id = $_GET['id'];
$data = array("Hello", $id);
echo json_encode($data);
} else {
?>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
function show(json) {
alert(json);
}
function run() {
$.ajax({
url : '/whatever/this/page/is',
type : 'GET',
data : 'id=567',
success: function(res) {
show(res);
}
});
}
window.onload=run;
</script>
</head>
<body>
JSON Test Page.
</body>
</html>
<?
}
Try with this code
function show(json) {
alert(JSON.stringify(json));
}
I'm doing GeoRef application. This is my index.php:
<!doctype html>
<html lang="es">
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="http://www.ign.gob.ar/argenmap/argenmap.jquery.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
url: 'getcoord.php',
dataType: 'json',
error: function(){
alert("ERROR");
},
success: function(res) {
var ico;
ico='Icon.png';
var marcador;
$('#mapa').argenmap();
$('#mapa').centro(-34.597907,-58.385557)
$('#mapa').zoom(4);
$('#mapa').capaBase('satellite');
for(var i=0;i<res.length;i++)
{
marcador=[{lat: res[i].latitud, lng:res[i].longitud,icono:ico}];
$('#mapa').argenmap().agregarMarcadores(marcador);
}
} });});
</script>
</head>
</html>
And this is my getcoord.php file:
<?php
include("config.php");
require("db.inc");
$sql = "SELECT * FROM datos_mapa";
$res = buscar($sql);
$arry=array();
foreach ($res as $r)
{
$arr = array('longitud' => $r['longitud'],'latitud' => $r['latitud']);
array_push($arry,$arr);
}
echo json_encode($arry);
?>
My problem is that, when I run getcoord.php using json_encode($arry), I see the information I want but, it doesn´t return to index.php. I´ve tried:
Using json in dataType. Gives me a Json Object but with Object in each field instead of latitude and longitude.
Using jsonp in dataType. Results an error.
Using text in dataType. I get the information I want, but as a string not as an Object.
Replacing echo json_encode($arry) with:
a) json_encode($arry);
b) print_r(json_encode($arry));
c) echo $_GET['receive'].'('.json_encode($arry).');';
But getting the same error.
Why I´m not getting the information in the format I want?
I was trying this code at work where apache is configured and didn´t work (keeps getting error when using dataType: 'json'). In my personal computer, using xampp, it works. So I think the code is right. Is there anything else I should configure?
My question is that how to pass query string variables on same page without refreshing the page in php? My code is given below:
<img src="a.jpg">
<?php
$a = $_GET['id'];
$b = $_GET['pid'];
?>
Please help me to resolve this issue
<html>
<head>
<title>Test</title>
<meta name="" content="">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#image_id").click(function(){
var dataString = 'a=10&b=20';
$.ajax({
type:'POST',
url:'foo.php',
data:dataString,
success:function(data) {
if(data=="Something") {
// Do Something
} else {
// Do Something
}
}
});
});
});
</script>
</head>
<body>
<img id="image_id" src="images/bg.jpg" />
</body>
</html>
Then in the 'foo.php' page do this
if(isset($_POST['a'])) {
// DO SOMETHING
}
Remember the things that you want to send to the 'data' of
success:function(data)
must be echoed out in the foo.php page
You can't.
PHP requires execution on the server and so you'd have to either use AJAX and update your page accordingly, or just refresh your page.
You can by sending an AJAX request to the server. Ajax is a way to send asynchronous request via Javascript. Notice that jQuery has a good library about it.
Use jquery to resolve this. By using the $.ajax in jquery you can do the stuff you need without page refresh.