I have the following javascript code which I need to be executed in a PHP file.
I need to know how should I enter the php tags to this javascript code.
I am new to web programming.
The javascript used here is to export content in the html page to a .csv file.
<!-- Scripts ----------------------------------------------------------- -->
<script type='text/javascript' src='https://code.jquery.com/jquery-
1.11.0.min.js'></script>
<!-- If you want to use jquery 2+: https://code.jquery.com/jquery-2.1.0.min.js -->
<script type='text/javascript'>
$(document).ready(function () {
console.log("HELLO")
function exportTableToCSV($table, filename) {
var $headers = $table.find('tr:has(th)')
,$rows = $table.find('tr:has(td)')
// Temporary delimiter characters unlikely to be typed by
keyboard
// This is to avoid accidentally splitting the actual
contents
,tmpColDelim = String.fromCharCode(11) // vertical tab
character
,tmpRowDelim = String.fromCharCode(0) // null character
// actual delimiter characters for CSV format
,colDelim = '","'
,rowDelim = '"\r\n"';
// Grab text from table into CSV formatted string
var csv = '"';
csv += formatRows($headers.map(grabRow));
csv += rowDelim;
csv += formatRows($rows.map(grabRow)) + '"';
// Data URI
var csvData = 'data:application/csv;charset=utf-8,' +
encodeURIComponent(csv);
// For IE (tested 10+)
if (window.navigator.msSaveOrOpenBlob) {
var blob = new Blob([decodeURIComponent(encodeURI(csv))], {
type: "text/csv;charset=utf-8;"
});
navigator.msSaveBlob(blob, filename);
} else {
$(this)
.attr({
'download': filename
,'href': csvData
//,'target' : '_blank' //if you want it to open in a
new window
});
}
//------------------------------------------------------------
// Helper Functions
//------------------------------------------------------------
// Format the output so it has the appropriate delimiters
function formatRows(rows){
return rows.get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim);
}
// Grab and format a row from the table
function grabRow(i,row){
var $row = $(row);
//for some reason $cols = $row.find('td') || $row.find('th')
won't work...
var $cols = $row.find('td');
if(!$cols.length) $cols = $row.find('th');
return $cols.map(grabCol)
.get().join(tmpColDelim);
}
// Grab and format a column from the table
function grabCol(j,col){
var $col = $(col),
$text = $col.text();
return $text.replace('"', '""'); // escape double quotes
}
}
// This must be a hyperlink
$("#export").click(function (event) {
// var outputFile = 'export'
var outputFile = window.prompt("What do you want to name your
output file (Note: This won't have any effect on Safari)") ||
'export';
outputFile = outputFile.replace('.csv','') + '.csv'
// CSV
exportTableToCSV.apply(this, [$('#dvData > table'),
outputFile]);
// IF CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
};
</script>
use this, add ?> before it and <?php after script
<?php
/* your php code */
?>
<script type='text/javascript'>
// your script
</script>
<?php
/* your php code */
?>
Top answer from a previous question
<script type="text/javascript">
var my_var = <?php echo json_encode($my_var); ?>;
</script>
works if you define and use the variable in PHP, and want to pass the variable in the Javascript.
If you are running in a PHP file (which you are) you can also use
function foo()
{
var i = 0 ;
i = <?php echo $my_var; ?>
}
Related
Current setting:
In the same PHP document I have a PHP randomizer function and the HTML that calls that function -- a separate txt document with strings that are called by the php function:
Function
<?php
function rand_line($fileName, $maxLineLength = 4096) {
$handle = #fopen($fileName, "strings.txt");
if ($handle) {
$random_line = null;
$line = null;
$count = 0;
while (($line = fgets($handle, $maxLineLength)) !== false) {
$count++;
if(rand() % $count == 0) {
$random_line = $line;
}
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
fclose($handle);
return null;
} else {
fclose($handle);
}
return $random_line;
}
}
?>
I call the function in the HTML using:
<?php echo rand_line("strings.txt");?>
<input type="button" value="Another String" onClick="window.location.reload()">
This tends to be slow when multiple users access the page and press the button to obtain a new status.
What I would like to achieve:
Improve the performance and make the whole thing not so heavy: maybe the randomizer is unnecessarily complicated and I could work with AJAX calls for example, but if possible keeping the string list inside the strings.txt file and separated from the PHP script and HTML.
Sorry if I don't know what I'm talking about... I'm not a proficient programmer. Just a guy that hacks stuff together once in a while :)
You really don't want to use window.location.reload();
That is terrible... You do not want to refresh a page...
location.reload() sends http request for a whole new page (whole HTML), and then not only that your browser needs to render whole HTML again, you have to transfer more duplicated data through a network, from point A to point B.
You should send HTTP request only for a data that you need (you don't need whole HTML again, you loaded it the 1st time you visited page).
Instead, use XMLHttpRequest javascript library (AJAX) to request only for a portion of data (in your case => random line string)
HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<script type="text/javascript">
function loadDoc(url, cfunc) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
cfunc(xhttp);
}
};
xhttp.open("GET", url, true)
xhttp.send();
}
function randomLine(xhttp) {
alert(xhttp.responseText);
}
</script>
</head>
<body>
<input type="button" value="Get random line" onClick="loadDoc('http://localhost:8080/myScript.php', randomLine)">
</body>
</html>
PHP:
myScript.php
<?php
function rand_line($fileName, $maxLineLength = 4096)
{
...
}
echo rand_line("strings.txt");
?>
*EDIT #2*
Fully-functioning script. Grabs initial strings via PHP, and stores in array for later JavaScript usage. Minimizes # of calls.
PHP to grab strings from file; generates a default (random) string, as well as an array of strings for later use with button.
/**
* #input array $file
* #return array (mixed) [0] => string, [1] => array
*/
$randomStringFromFile = function($file) {
if (!$file) return false;
/**
* #return Removes carriage returns from the file
* and wraps $val with single-quotes so as
* to not break JavaScript
*/
$add_quotes = function(&$val) {
return str_replace("\n", "", "'$val'");
};
return [$file[rand(0, count($file)-1)], array_map($add_quotes, $file)];
};
$randomString = $randomStringFromFile( #file('strings.txt') ) ?: false;
JavaScript
<div id="string_container"><?php echo $randomString[0]; // defaults random string to page ?></div><br>
<button onclick="getString();">Another String</button>
<script>
var getString = function() {
var arr = [<?php echo implode(',', $randomString[1]); ?>],
setString = document.getElementById('string_container').innerHTML = arr[Math.floor(Math.random() * arr.length)];
};
</script>
Place the above in your page and you should be good to go.
EDIT (ORIGINAL)
We can remove PHP from the equation entirely using the following (fastest method):
<div id="string_container"></div><br>
<button onclick="getString();">Another String</button>
<script>
var getString = function() {
var request = new XMLHttpRequest(),
file = 'strings.txt';
request.open('GET', file);
request.onload = function() {
if (request.status === 200) {
var arr = request.responseText.split("\n"), /** assuming line breaks in file are standard carriage returns (Unix); "\r" if Windows */
setString = document.getElementById('string_container').innerHTML = arr[Math.floor(Math.random() * arr.length-1)];
}
};
request.send();
};
</script>
ORIGINAL w/PHP
We can simplify the PHP even further, removing loops from the equation altogether.
$randomStringFromFile = function($file) {
if (!$file) return false;
return $file[rand(0, count($file)-1)];
};
echo $randomStringFromFile( #file('strings.txt') ) ?: 'No worky!';
Using file() will return the contents in an array, thus allowing you to simply select a key at random and return the value.
NOTE On average, $file[rand(0, count($file)-1)] outperformed array_rand() (E.g. $file[array_rand($file)];) when selecting a key at random. By negligible amounts, have you.. ~0.0002s vs ~0.0005s, respectively.
You can simplify your code
function rand_line($fileName, $maxLineLength = 4096) {
$f = file($fileName);
$length = $maxLineLength + 1;
do {
$line = $f[array_rand($f)];
$length = strlen($line);
} while ($length > $maxLineLength);
return $line;
}
Here is what I did to get the file renaming working:
Dropzone.js - How to change file name before uploading to folder
From index.php:
$(document).ready(function() {
Dropzone.autoDiscover = false;
var fileList = new Array;
var i =0;
$("#some-dropzone").dropzone({
addRemoveLinks: true,
init: function() {
// Hack: Add the dropzone class to the element
$(this.element).addClass("dropzone");
this.on("success", function(file, serverFileName) {
fileList[i] = {"serverFileName" : serverFileName, "fileName" : file.name,"fileId" : i };
//console.log(fileList);
i++;
});
this.on("removedfile", function(file) {
var rmvFile = "";
for(f=0;f<fileList.length;f++){
if(fileList[f].fileName == file.name)
{
rmvFile = fileList[f].serverFileName;
}
}
if (rmvFile){
$.ajax({
url: "http://localhost/dropzone/sample/delete_temp_files.php",
type: "POST",
data: { "fileList" : rmvFile }
});
}
});
},
url: "http://localhost/dropzone/sample/upload.php"
});
});
From upload.php:
<?php
$ds = DIRECTORY_SEPARATOR; // Store directory separator (DIRECTORY_SEPARATOR) to a simple variable. This is just a personal preference as we hate to type long variable name.
$storeFolder = 'uploads'; // Declare a variable for destination folder.
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name']; // If file is sent to the page, store the file object to a temporary variable.
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds; // Create the absolute path of the destination folder.
// Adding timestamp with image's name so that files with same name can be uploaded easily.
$date = new DateTime();
$newFileName = $date->getTimestamp().$_FILES['file']['name'];
$targetFile = $targetPath.$newFileName; // Create the absolute path of the uploaded file destination.
move_uploaded_file($tempFile,$targetFile); // Move uploaded file to destination.
echo $newFileName;
}
?>
New file delete_tmp_files.php:
<?php
$ds = DIRECTORY_SEPARATOR; // Store directory separator (DIRECTORY_SEPARATOR) to a simple variable. This is just a personal preference as we hate to type long variable name.
$storeFolder = 'uploads';
$fileList = $_POST['fileList'];
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
if(isset($fileList)){
unlink($targetPath.$fileList);
}
?>
Here I need dropzone to call PHPExcel or sheetJS. I have sheetJS parsing to CSV in a static page using ajax here:
<html>
<head>
<title>AJAX XLS TEST</title>
</head>
<body>
<br/><div id="fileurl"></div>
<pre id="out"></pre>
<br />
<script src="js/iemagic.js"></script>
<script src="js/shim.js"></script>
<script src="js/jszip.js"></script>
<script src="js/xlsx.js"></script>
<script>
function to_csv(workbook) {
var result = [];
workbook.SheetNames.forEach(function(sheetName) {
var csv = XLSX.utils.sheet_to_csv(workbook.Sheets[sheetName]);
if(csv.length > 0){
result.push("SHEET: " + sheetName);
result.push("");
result.push(csv);
}
});
return result.join("\n");
}
function process_wb(wb) {
var output = to_csv(wb);
if(out.innerText === undefined) out.textContent = output;
else out.innerText = output;
if(typeof console !== 'undefined') console.log("output", new Date());
}
var url = "uploads/fw.xls";
var oReq;
if(window.XMLHttpRequest) oReq = new XMLHttpRequest();
else if(window.ActiveXObject) oReq = new ActiveXObject('MSXML2.XMLHTTP.3.0');
else throw "XHR unavailable for your browser";
document.getElementById('fileurl').innerHTML = 'Download file';
oReq.open("GET", url, true);
if(typeof Uint8Array !== 'undefined') {
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
if(typeof console !== 'undefined') console.log("onload", new Date());
var arraybuffer = oReq.response;
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var wb = XLSX.read(arr.join(""), {type:"binary"});
process_wb(wb);
};
} else {
oReq.setRequestHeader("Accept-Charset", "x-user-defined");
oReq.onreadystatechange = function() { if(oReq.readyState == 4 && oReq.status == 200) {
var ff = convertResponseBodyToText(oReq.responseBody);
if(typeof console !== 'undefined') console.log("onload", new Date());
var wb = XLSX.read(ff, {type:"binary"});
process_wb(wb);
} };
}
oReq.send();
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-36810333-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
Question 1: How do I get dropzone to call this ajax csv output? A. There is "queuecomplete" but where to put the quecomplete code (body? head? index.php? Upload.php? Another option would be using PHPexcel (below) but again not sure how to get dropzone to call it after renaming is done:
| Excel To Array
|--------------------------------------------------------------------------
| Helper function to convert excel sheet to key value array
| Input: path to excel file, set wether excel first row are headers
| Dependencies: PHPExcel.php include needed
*/
$filePath = "uploads/fw.xls";
function excelToArray($filePath, $header=true){
//Create excel reader after determining the file type
$inputFileName = $filePath;
/** Identify the type of $inputFileName **/
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
/** Create a new Reader of the type that has been identified **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/** Set read type to read cell data onl **/
$objReader->setReadDataOnly(true);
/** Load $inputFileName to a PHPExcel Object **/
$objPHPExcel = $objReader->load($inputFileName);
//Get worksheet and built array with first row as header
$objWorksheet = $objPHPExcel->getActiveSheet();
//excel with first row header, use header as key
if($header){<SNIP>
I really think PHPexcel would be much easier when it comes to culling out specific data from the xls as I only need specific fields to populate the following javascript form, but again, where do I put the PHPexcel script? Do I use queuecomplete to call the file? I think if I use queuecomplete and reference phpexcel_parse.php I could get it going from there but I just can't seem to get dropzone to do something with the file after uploading and renaming is complete. Any help is much appreciated. Thanks!
I am using vivagraphs to generate dynamic svg element but when I click capture button, no nodes and edges are shown.
This is the script:
$(document).ready(function() {
//var testdiv = document.getElementById("testdiv");
$('#btn').click(function(){
html2canvas($("#graph1"), {
onrendered: function(canvas) {
var myImage = canvas.toDataURL("img/png");
window.open(myImage);
}
});
});
While I inspect for elements svg is shown after rendering graph but snapshot does not contain nodes and edges.
Is there an alternative for html2canvas or can I fix this issue?
if you want to save the image from canvas to some image format here is some help for you. hope this will help you out.
$(document).ready(function() {
$('#btn').click(function(){
html2canvas(document.getElementById('graph1'), {
onrendered: function(canvas) {
var cs = new CanvasSaver('save_img.php',canvas,'myimage')
}
});
});
});
here CanvasSaver() function define is here below which take three parameters one is a php file which process image from RAW date to some image format. i'll write the code of 'save_img.php' belwo this script part and save that file in your root directory.
function CanvasSaver(url, cnvs, fname) {
this.url = url;
if(!cnvs || !url) return;
fname = fname || 'picture';
var data = cnvs.toDataURL("image/png");
data = data.substr(data.indexOf(',') + 1).toString();
var dataInput = document.createElement("input") ;
dataInput.setAttribute("name", 'imgdata') ;
dataInput.setAttribute("value", data);
dataInput.setAttribute("type", "hidden");
var nameInput = document.createElement("input") ;
nameInput.setAttribute("name", 'name') ;
nameInput.setAttribute("value", fname + '.jpg');
var myForm = document.createElement("form");
myForm.method = 'post';
myForm.action = url;
myForm.appendChild(dataInput);
myForm.appendChild(nameInput);
document.body.appendChild(myForm) ;
myForm.submit() ;
document.body.removeChild(myForm) ;
}
in above script whatever the image formate you want to save from browser give that image extension in this function above script
nameInput.setAttribute("value", fname + '.jpg');
now here is the code for your 'save_img.php' and save it in your root directory.
<?php
# we are a PNG image
header('Content-type: image/png');
# we are an attachment (eg download), and we have a name
header('Content-Disposition: attachment; filename="' . $_POST['name'] .'"');
#capture, replace any spaces w/ plusses, and decode
$encoded = $_POST['imgdata'];
$encoded = str_replace(' ', '+', $encoded);
$decoded = base64_decode($encoded);
#write decoded data
echo $decoded;
?>
you maybe using beta version of lib , goto releases on github page of html2canvas and download stable alpha version
This is an example of the PHP script I want to get the output from within my javascript file:
data.php
<?php
$input = file_get_contents('data.txt');
echo $input."\n";
?>
script.js
$(document).ready(function(){
var data;
// get output from data.php
console.log( data );
});
I just want a way to test to see if the data from within the data.txt file that is being stored in a php variable can be passed into the javascript file and then printed within the javascript console on the html page.
I want to do this so that I can store a variable in the text file and then reference it as it dynamically is updated from multiple users at the same time.
I've seen ways to do this, but it involves the javascript being in the same file as the html, which is not the case here. I'm also using jquery so I don't know if that makes a difference. I've never used php before and am new to javascript, so any help would be appreciated.
You can put you php code in the javascript file if you change the extension to "php". As "php" extensions will get delivered as Html per default, you have to state that it is Javascript in the code.
script.js.php
<?php header('Content-Type: application/javascript');
?>console.log("<?php
$input = file_get_contents('data.txt');
echo $input."\n";
?>");
$(document).ready(function(){
$("#imgTag, #img2").on("click", process);
var size = 0;
function getTarget(evt)
{
evt = evt || window.event;
return evt.target || evt.scrElement;
}
var temp;
console.log("before get");
console.log("post get");
console.log(size);
function changeSize(myName, myOther)
{
var name = myName;
var other = myOther;
if($("#" + name).height() < 400)
{
$("#" + name).height($("#" + name).height() + 5);
$("#" + name).width($("#" + name).width() + 5);
$("#" + other).height($("#" + other).height() - 5);
$("#" + other).width($("#" + other).width() - 5);
}
}
function process(event)
{
var name = getTarget(event).id;
var other;
if(name == "imgTag")
{
other = "img2";
}
else
other = "imgTag";
console.log($("#" + name));
console.log("Changing size!!!");
console.log( $("#" + name).height());
changeSize(name, other);
}
});
You can read that text file directly with jquery like this:
$.ajax({
url : "data.txt",
dataType: "text",
success : function (data) {
// Display the data in console
console.log(data);
// Or append it to body
$('body').append(data);
}
});
The same way you can read output from your php file, in which case you should change the url to point to your php file. Another thing you should read about is different options of communicating server-client side like json data structure etc.
Documentation: https://api.jquery.com/jQuery.ajax/
I am getting userid from the url.
This is what I have at the moment. I want to replace the one with $userid but I don't know how. It doesn't work and I can't seem to find the right syntax, please can someone help?
function returnimages($dirname = "Photos/1")
Basically I am trying to create a photo slideshow using html, php and javascript. I had something working before I started adding php into my code. I had html and an external javascript that changes the photos and they fade in and out in a loop. I have a photo array in javascript. Right now I am trying to add php to my html. I want to be able to get userid via url and then from that get the photos from a specific path to the userid in the directory. Then I am hoping to create an array of these photos and use them in my javascript. Here is my php code embedded in my html:
<?php
$user_id = $_GET['userid'];
print " Hi, $user_id ";
function returnimages($dirname = "Photos/1") { //will replace 1 with userid once something starts working
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";';
$curimage++;
}
}
closedir($handle);
}
return($files);
}
echo 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
And my javascript:
$ (document).ready(function(){
var photodisplay =
[
$("#photo1"),
$("#photo2"),
$("#photo3"),
$("#photo4"),
$("#photo5"),
];
//photodisplay[0].hide().fadeIn(3000);
var user = new Array();
[1, 2, 3, 4, 5];
// List of images for user one
/*var userphoto = new Array();
userphoto[0] = "Photos/1/1.jpg";
userphoto[1] = "Photos/1/2.jpg";
userphoto[2] = "Photos/1/1.jpg";
userphoto[3] = "Photos/1/1.jpg";
userphoto[4] = "Photos/1/1.jpg";*/
//preloading photos
var userphoto = <? echo json_encode($galleryarray); ?>;
function preloadingPhotos() {
for (var x=0; x<5; x++)
{
photodisplay[x].attr("src", "Photos/1" + userphoto[x]);
photodisplay[x].hide();
console.log("preloaded photos");
}
displayPhoto();
}
function displayPhoto(){
photodisplay[0].fadeIn(3000);
photodisplay[0].delay(3000).fadeOut(3000, function() { //first callback func
photodisplay[1].fadeIn(3000);
photodisplay[1].delay(3000).fadeOut(3000, function() { //second callback func
photodisplay[2].fadeIn(3000);
photodisplay[2].delay(3000).fadeOut(3000, function() { //third callback func
photodisplay[3].fadeIn(3000);
photodisplay[3].delay(3000).fadeOut(3000, function() { // fourth callback func
photodisplay[4].fadeIn(3000);
photodisplay[4].delay(3000).fadeOut(3000, function() {
setTimeout(displayPhoto(), 3000);
});
});
});
});
});
}// end of function displayPhoto
window.onload = preloadingPhotos;
}); //end ready
My url to get userid:
http://example.com/code.php?user_id=1
Thank you for your time!
The problem is that you are always setting the dirname instead of letting calling the function set it. You could change:
function returnimages($dirname = "Photos/1") {
to
function returnimages($dirname) {
because otherwise the $dirname is always Photo/1. Then, when you call the function, use:
returnimages('Photos/'.$user_id);
You can concatenate in PHP by using the dot '.'. This will concatenate two string and then assign them to the variable $dirname. For example:
$dirname = "Photos/" . $_GET['ID'];
The variable $dirname can then be placed in the function returnimages, like:
returnimages($dirname);