CSV download with PHP/jQuery - javascript

I'm trying to develop a way for users to download a table in CSV format via jQuery/PHP.
My aim is to send the jQuery request to the server using PHP.
PHP then creates the CSV content and returns it.
jQuery then forces the browser to download the content as a CSV file.
I've got 90% working, the last bit is that I need to force the CSV download in the users browser using jQuery.
My PHP script
<?php
class Export {
public static function tocsv($results = array(), $fields = array(), $filename) {
$fh = fopen('php://output', 'w');
ob_start();
fputcsv($fh, $fields);
if(!empty($results)) {
foreach($results as $row) {
fputcsv($fh, (array) $row);
}
}
$string = ob_get_clean();
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$filename");
exit($string);
}
}
?>
My jQuery script
$(function() {
var btnName;
$('.button').click(function() {
btnName = $(this).attr('name');
btnValue = $(this).attr('value');
});
$("#spendReports").submit(function(event) {
event.preventDefault();
var formData = $('#spendReports').serializeArray();
formData.push({ name: btnName, value: btnValue });
$.post('spendReports.php', formData, function(data)
{
var data = $.parseJSON(data);
$.each(data, function(i, val) {
var newRow = '<tr><td class="dates-col" data-th="Date">' + data[i]["dates"] + '</td><td data-th="Project name">' + data[i]["project"] + '</td><td data-th="Total budget">' + data[i]["budget"] + '</td><td data-th="Plot numbers">' + data[i]["plots"] + '</td><td data-th="Categories">' + data[i]["categories"] + '</td><td data-th="Day work spent">£' + data[i]["day_work_spent"] + '</td><td data-th="% spend">' + data[i]["day_work_spent_percent"] + '%</td><td data-th="Price work spent">£' + data[i]["price_work_spent"] + '</td><td data-th="% spend">' + data[i]["price_work_spent_percent"] + '%</td><td data-th="Agency work spent">' + data[i]["agency_work_spent"] + '</td><td data-th="% spend">' + data[i]["agency_work_spent_percent"] + '%</td><td data-th="Subcon spent">' + data[i]["subcon_work_spent"] + '</td><td data-th="% spend">' + data[i]["subcon_work_spent_percent"] + '%</td><td data-th="Supervision spent">' + data[i]["supervision_spent"] + '</td><td data-th="% spend">' + data[i]["supervision_work_spent_percent"] + '%</td><td data-th="Total spent">£' + data[i]["total_spent"] + '</td></tr>';
$("#results > tbody").append(newRow);
});
});
});
});
This is different from Download File Using jQuery as i'm not physically creating a file on the server and therefore do not have a phsical link to send to jQuery.

Have a look at this answer: https://stackoverflow.com/a/4551467/563802
In your case it should be something like this:
var uriContent = "data:text/csv," + encodeURIComponent(data);
newWindow=window.open(uriContent, 'newDocument');

Related

How to hyperlink data in popup? [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 1 year ago.
I would like to hyperlink my url data in popup, where user can click those website. However, it did not work.
Below is my source code:
if ($rowCount > 0) {
//Array for JSON output
$rows = array();
//Get the SQL results
while($row = $result->fetch_array()){
$fid = $row["Id"];
$Name = $row["Name"];
$address = $row["address"];
$Star = $row["Star"];
$latitude = $row["latitude"];
$longitude = $row["longitude"];
$hp = $row["hp"];
$url = $row["url"];
$rows[] = array(
"fid" => $fid,
"Name" => $Name,
"address" => $address,
"Star" => $Star,
"latitude" => $latitude,
"longitude" => $longitude,
"hp" => $hp,
"url" => $url
);
}
echo "var dataPOIs = ";
//Output to JSON format
echo json_encode($rows, JSON_NUMERIC_CHECK);
echo ";\n";
echo '
for (var i=0; i<dataPOIs.length; i++){
L.marker([dataPOIs[i].latitude, dataPOIs[i].longitude],{icon: createIcon(), title:dataPOIs[i].Name}).bindPopup("Name: " + " " + "<b>" + dataPOIs[i].Name + "</b>" + "</br>" + "</br>" + "Star: " + "<b>" + dataPOIs[i].Star + "</b>" + "</br>" + "</br>" + "Address: " + " " + "<b>" + dataPOIs[i].address + "</b>" + "</br>" + "</br>" + "Hp: " + " " + "<b>" + dataPOIs[i].hp + "</b>" + "</br>" + "</br>" + "Website: " + " " + "<a href='" + dataPOIs[i].url + "'>" + "</a>").addTo(pois);
}
';
}
It shows
Parse error: syntax error, unexpected '" + dataPOIs[i].url + "'
(T_CONSTANT_ENCAPSED_STRING), expecting ';' or ','
in Popup line
I can see from the image link you shared that you were trying to implement a tooltip on a map on the frontend but you shared a backend (php) script.
This has nothing to do with your php code.
You should focus more on reading the map's documentation(google map) and see how you can implement a tooltip with hyperlink.
What you are looking for is called Info Window.
https://developers.google.com/maps/documentation/javascript/examples/infowindow-simple.
Ps:
Learn to write better codes. Try seperating views from business logic.

To get image instead of url in AJAX call

Following is relevant part of my html page, I want to get image instead of image address(result[i].url). Also I want to know if it is possible because I am using certain style(CSS) here.
function BindStudents() {
$.ajax({
type: 'GET',
dataType: 'json',
url: "http://127.0.0.1:8000/memes", success: function (result) {
var totalCount = result.length;
var structureDiv = "";
for (let i = 0; i < totalCount; i++) {
structureDiv += "<tr>" +
" <td>" + result[i].id + "</td>" +
" <td>" + result[i].name + "</td>" +
" <td>" + result[i].url + "</td>" +
" <td>" +result[i].caption + "</td>" +
" <td><button class='btn btn-link' onclick='return confirm(\"Are you sure you want to delete this record?\",DeleteRow(" + result[i].id + "))'>Delete</button></td>" +
" </tr>";
}
$("#divBody").html(structureDiv);
}
});
}
If the server sends a URL then the server sends a URL.
If you want an image then you'll need to either:
change the server-side code so it sends an image (but there is no image, file, or blob type for JSON so you'll need to encode it as text … and then write client-side code to decode the encoded image … and then find some way of displaying it … which will probably involve encoding it as a data: URL)
make a send Ajax request to fetch the image from the URL you were given
It would probably be much simpler to just create an <img> element with the src set to the URL from the JSON when you create all the other HTML.
Just add a HTML element <img>:
structureDiv += "<tr>" +
" <td>" + result[i].id + "</td>" +
" <td>" + result[i].name + "</td>" +
" <td><img src=\"" + result[i].url + "\"></td>" +
" <td>" +result[i].caption + "</td>" +
" <td><button class='btn btn-link' onclick='return confirm(\"Are you sure you want to delete this record?\",DeleteRow(" + result[i].id + "))'>Delete</button></td>" +
" </tr>";

Empty Div tag issue for dynamically rendered table

I am creating dynamic table and appending it to Div tag on my .php page. On my .php page, I have dynamic buttons and if I click on any of the dynamic buttons, the dynamic table is rendered which has multiple headers and rows (for which I have written for loops with ajax requests). The issue is that, if i click on any of the dynamic buttons again, the current dynamic table data is appended to the previous dynamic table, instead I want to remove previously appended table data and render the current dynamic table data. I tried to empty the div tag but nothing seems working here. Hope I get some help, thanks in advance. Below are my .php and .js files:
.php file- I didnt post the function definition for get_Btns() as it is the basic php function to fetch data from the database:
<?php
function get_Btns() {
include "config.php";
$btns = $stmtDivision->fetchAll(PDO::FETCH_ASSOC);
foreach($btns as $btn){
echo "<input type='button' id='".$btn['divisionid']."' value='".$btn['division_name']."'
onclick=getData('".$btn['divisionid']."') >" ; echo "<br/>"; ?>
<script src="./user.js"></script>
<?php }
}
?>
<?php include "templates/header.php"; ?>
<div id="buttons_panel" style="text-align:center">
<?php echo get_Btns();?> </div>
<div id="div" class="divClass" ></div> <br/>
.js file:
function getData(value) {
document.getElementById("div");
var tableHtml = $('<table></table>');
var selectedManager = value;
var isEmpty = $('#div').empty();
// document.getElementById("div").innerHTML === "";
// document.getElementById("div").HTML === "";
// var isEmpty = $("#div").html() === "";
//$(".divclass").empty();
var teams = null;
$.ajax({
url: 'data.php',
method: 'post',
data: 'selectedManager=' + selectedManager,
async: false,
success: function(data) {
teams = JSON.parse(data);
}
});
for (var k = 0; k < teams.length; k++) {
const selectedteam = teams[k];
var selectedteamid = team[k].teamid;
var htmlth = "";
var html = "";
htmlth = "<tr>" + "<th id='thgrp' colspan='4' background-color: #013466;>" + teams[k].teamname + "</th>" +
"<th colspan='2' background-color: #62b8b6;>" + "<a href='Update.php?groupid=" + selectedteam.teamid + "' >" +
'Update Team member' + "</a>" + "</th>" + "</tr>" +
"<tr>" + "<th>" + "<img src='images/member.png'>" + "<b>" + "<div>" + 'Member' + "</div" + "</th>" +
"<th>" + "<img src='images/phone.png'>" + "<b>" + "<div >" + 'Phone' + "</div" + "</th>" +
"<th>" + "<img src='images/email.png'>" + "<b>" + "<div >" + 'Email' + "</div" + "</th>" + "</tr>";
tableHtml.append(htmlth);
var members = null;
$.ajax({
url: 'data.php',
method: 'post',
data: 'selectedteamid=' + selectedteamid,
async: false,
success: function(data) {
members = JSON.parse(data);
console.log(members);
}
});
for (var i = 0; i < members.length; i++) {
html += "<tr>" + "<td>" + members[i].name + "</td>" +
"<td>" + members[i].phone + "</td>" + "<td>" + members[i].email + "</td>";
}
tableHtml.append(html)
}
$("#div").append(tableHtml);
value = "";
}
Issue solved, I tried to empty the dynamic table that I have created instead of emptying the div tag on my html page. I did this earlier but I didn't do it properly. Thank you so much everyone for your time
This is the code:
tableHtml.attr('id', 'tableHtmlId');
$('#tableHtmlId').empty();

How to apply style sheet on dynamic generate radio button?

here, I am using form wizard. Using ajax to load the data and data are append in html.
ajax code :
$.ajax({
url: '<?php echo base_url(); ?>booking/listSiteUrl',
type: 'post',
dataType: 'json',
success: function (response) {
if (response.success == 1) {
var row = '';
var i = 1;
$.each(response.row_data, function (index, value) {
row += "<tr><td>" + i + "</td><td>" + value.url + "</td><td>" + value.p1_name + "</td><td hidden>" + value.id + "</td><td hidden>" + value.f_n + "</td><td><div class='radio-list'><label><input type='radio' id='f_n_val' name='select_val' data-url='" + value.url + "' data-pub='" + value.p1_name + "' data-id='" + value.id + "' data-follow='" + value.f_n + "' required='required'></label></div></td></tr>";
i++;
});
$("#results").html(row);
// $("input[type=radio]").uniform();
} else {
var row = '';
row += "<tr><td colspan='4' class='text-center'>No Records Found</td></tr>";
$("#results").html(row);
}
}
});
How to apply style sheet on a radio button? you can show in image very clearly...
When I am using uniform style i.e. ($("input[type=radio]").uniform();) work fine and radio button style is applied bt problem in when I am checking validation that time it will look like in below image :
Please help me to find out the way to solve this.
You can create your class in css as
.myradio{
// your code here
}
and then
$("input[type=radio]").addClass('myradio');

Ajax Webpage Not Displaying Most Update to Date Content After Redirect

I have page that displays images from different directories and can change the file names of files in a folder, based on their order in a jQuery sortable list.
So far everything is working except that after I Save the new file names and the Save page redirects to the Edit page I have to do a "Empty Cache and Hard Reload" in order for the new file order to be displayed.
Edit Page
<!DOCTYPE html>
<?php
session_start();
if (!$_SESSION['username']) {
echo "<script>window.location = './index.php'</script>";
}
?>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Cache-control" content="no-cache">
<meta http-equiv="Expires" content="-1">
<link rel="stylesheet" href="../js/jquery/jquery-ui-1.11.4/jquery-ui.css">
<script src="../js/jquery/jquery-2.1.4.min.js"></script>
<script src="../js/jquery/jquery-ui-1.11.4/jquery-ui.js"></script>
<script>
$(window).load(function() {
$(document).ready(function() {
$("#btnRefresh").click(function() {
window.location.reload(true);
});
$.ajax({
url: 'getPics.php',
success: function(resultOfAjaxCall) {
xmlDoc = $.parseXML(resultOfAjaxCall);
$xml = $(xmlDoc);
html = "";
$xml.find('Folder').each(function(index) {
//console.log($(this).attr('Name'));
city = $(this).attr('Name');
html += "<h3 class='accordion-header'>" + city + "</h3>";
html += "<div class='accordion-section'>";
html += "<button id='" + city + "_Save'>Save " + city + "</button>";
html += " ";
//Upload Form
html += '<form enctype="multipart/form-data" action="uploader.php" method="POST">';
html += '<input type="hidden" name="MAX_FILE_SIZE" value="100000" />';
html += '<input type="hidden" name="City_Folder" value="' + city + '" />';
html += 'Choose a file to upload: <input name="userfile" type="file" /><br />';
html += '<input type="submit" value="Upload File" />';
html += '</form>';
//Save Form
html += '<form enctype="multipart/form-data" action="save.php" method="POST" id="' + city + '_Save_Form">';
html += '<input type="hidden" name="City_Folder" value="' + city + '" />';
html += '</form>';
html += "<ul class='" + city + "-sortable-list'>";
$(this).find('File').each(function(index) {
//console.log($(this).text()
fileName = $(this).find('File_Name').text();
filePath = $(this).find('File_Path').text();
fileRealPath = $(this).find('File_Real_Path').text();
//console.log(fileName);
//console.log(filePath);
html += '<form enctype="multipart/form-data" action="delete.php" method="POST" id="' + fileName + '_Delete_Form">';
html += '<input type="hidden" name="Delete_Path" value="' + filePath + '" />';
html += '</form>'
html += "<li id='" + fileName + "' class='ui-state-default' value='" + fileRealPath + "'>" + fileName + " ";
html += "<button id='" + fileName + "_Delete'>Delete</button>";
html += "<br>"
html += "<img src='" + filePath + "' style='width:150px;'/>";
html += "<br></li>";
})
html += "</ul>";
html += "</div>";
//window.location.reload(true);
});
$("#accordion").append(html);
var $accordion = $("#accordion").accordion({
collapsible: true,
heightStyle: "content",
active: false
});
$("[class$=-sortable-list]").sortable({
update: function(event, ui) {
console.log(ui);
var order = [];
$("[class$=-sortable-list] li").each(function(e) {
order.push($(this).attr("id") + "=" + ($(this).index() + 1));
});
var positions = order.join();
// alert(positions);
},
stop: function(event, ui) {
console.log("an item was moved");
$accordion.find("#tmp").remove();
},
start: function(event, ui) {
$accordion.append("<ul id='tmp'></ul>");
$accordion.find("#tmp").append(ui.item);
}
}).disableSelection();
//Save Click
$("[id$=_Save_Form]").submit(function(event) {
folder = event.target.id.replace("_Save_Form", "");
$("." + folder + "-sortable-list li").each(function(e) {
//alert(folder);
//alert($(this).index());
//alert($(this).attr("value"));
$("<input />").attr("type", "hidden")
.attr("name", "path[" + $(this).index() + "]")
.attr("value", $(this).attr("value"))
.appendTo("#" + event.target.id);
});
});
$("[id$=_Save]").click(function(event) {
$("#" + event.target.id + "_Form").submit();
});
}
});
});
});
</script>
<title>Edit Slider</title>
</head>
<body>
<?php ?>
<p>You are logged in as <?= $_SESSION['username'] ?> (Logout)</p>
<p><button id="btnRefresh">Refresh</button></p>
<div id="accordion">
</div>
</body>
</html>
Save Page
<?php
$root = filter_input(INPUT_SERVER, "DOCUMENT_ROOT", FILTER_SANITIZE_STRING, FILTER_SANITIZE_MAGIC_QUOTES);
require $root . '/CC_Library/CC_Folder.php';
require $root . '/CC_Library/CC_String.php';
$folder = filter_input(INPUT_POST, "City_Folder", FILTER_SANITIZE_STRING, FILTER_SANITIZE_MAGIC_QUOTES);
$dir = "";
$i = 0;
$s = new CC_String;
$tmp = $s->generate_rand(5);
foreach ($_POST['path'] as $value) {
$CC = new CC_File($value);
$dir = $CC->get_File_Dir();
echo "Changing " . $CC->get_Full_File_Name() . " to " . $tmp . str_pad($i, 10, '0', STR_PAD_LEFT) . "." . $CC->get_File_Extension() . "<br>";
$CC->Rename($tmp . str_pad($i, 10, '0', STR_PAD_LEFT) . "." . $CC->get_File_Extension());
$i++;
}
$j = 0;
//echo $dir;
$F = new CC_Folder($dir);
$Files = $F->get_Folder_Files();
foreach ($Files as $value) {
echo "Changing " . $value->get_Full_File_Name() . " to " . $folder . "-" . str_pad($j, 8, '0', STR_PAD_LEFT) . "." . $value->get_File_Extension() . "<br>";
$value->Rename($folder . "-" . str_pad($j, 8, '0', STR_PAD_LEFT) . "." . $value->get_File_Extension());
$j++;
}
echo "<script>window.location.replace('Edit_Slider.php')</script>";
I dont want to read all of that notorious code. Your problem is client sided, not server sided so your code is irreverent.
Your webbrowser is caching and not updating your images. A fix for this would be to extend the current image source with a timestamp like so:
<img src="image.jpg?lastmod=12345678"
//javascript
function(img_src){
var timestamp = (new Date()).getTime();
img_src += "lastmod?" + timestamp;
}
how to clear or replace a cached image
The reason this works is because the source URL is different each time because of the timestamp will always be different & web browsers remember content relative to the URL.

Categories

Resources