I have problem with logging visit duration.
I wrote test html file like this:
<!DOCTYPE html>
<html>
<body>
<script language="JavaScript" type="text/javascript">
function enter() {
this.chrono = new Date().getMilliseconds();
alert("test");
}
function leave() {
this.chrono = new Date().getMilliseconds() - this.chrono;
var myAjax = new Ajax.Request('visitor_log/ajax_store_visit_duration.php?visit_duration=' + this.chrono.toString(),{
method: 'get',
onComplete:handlerFunction
});
return null;
}
window.onload = enter;
window.onbeforeunload = leave;
</script>
</body>
</html>
PHP file (visitor_log/ajax_store_visit_duration.php):
<?php
if(isset($_GET["visit_duration"]))
{
$text = $_GET["visit_duration"];
log($text);
}
else die("error");
function log($text)
{
$myFile = "test.txt";
$fh = fopen($myFile, 'wb');
fwrite($fh, $text);
fclose($fh);
}
?>
When I type in browser:
http://localhost/visitor_log/ajax_store_visit_duration.php?visit_duration=123
it creates text file as I want, but it seems that AJAX call in onbeforeunload event is not working.
Whats wrong with my code?
Edit:
I created test function to find problem with AJAX call.
function testajax(){
this.chrono = new Date().getMilliseconds() - this.chrono;
var blockingRequest = new XMLHttpRequest();
blockingRequest.open("GET", "visitor_log/ajax_store_visit_duration.php?visit_duration=" + 123, false); // async = false
blockingRequest.send();
return null;
}
window.onload = testajax;
</script>
</body>
This is not working too.
Ok, so purposefully NOT using jQuery:
here's the PHP:
<?php
function loggit($text) {
$myFile = "/tmp/test.txt";
$fh = fopen($myFile, 'wb');
fwrite($fh, $text);
fclose($fh);
}
if(isset($_GET["visit_duration"])) {
$text = $_GET["visit_duration"];
loggit($text);
}
else die("error");
?>
here's the HTML:
<!DOCTYPE html>
<html>
<body>
<script language="JavaScript" type="text/javascript">
function enter() {
this.chrono = new Date().getMilliseconds();
}
function leave() {
this.chrono = new Date().getMilliseconds() - this.chrono;
alert("test" + this.chrono);
var blockingRequest = new XMLHttpRequest();
blockingRequest.open("GET", "http://localhost/_TempFiles/temp.php?visit_duration=" + this.chrono.toString(), false); // async = false
blockingRequest.send();
return null;
}
window.onload = enter;
window.onbeforeunload = leave;
</script>
</body>
</html>
you want to use an async request (see the false sent to blockingrequest.open) - but beware this is a BLOCKING request (hence the name).
Also I changed the name of the php function from "log" to "loggit" log is the php natural logarithm function...
Related
I have the following script:
function follow($file)
{
$currentSize = filesize($file);
$size = $currentSize;
$index=0;
while ($index<$currentSize) {
//echo "ENTERING LOOP!!!!";
clearstatcache();
$currentSize = filesize($file);
if ($size == $currentSize) {
usleep(100);
continue;
}
$fh = fopen($file, "r");
fseek($fh, $size);
while ($d = fgets($fh)) {
ob_end_flush();
echo $d;
ob_flush();
flush();
ob_start();
}
fclose($fh);
$size = $currentSize;
$index=$index+1;
}
}
follow("/var/www/devicemanagement/testFile.txt");
This script echoes a log file in real time and it works well when run in command line.
The following html code is meant to display the echoed lines from the php script:
<!DOCTYPE html>
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.js"></script>
<script>
var sentData = {
'param1': 'value1',
'param2': 'value2'
};
function successCallback(returnedData) {
$('#myDiv').html(returnedData);
}
function doAjaxCall() {
$.get('/labtool/controllers/tailor.php', sentData, successCallback);
//$.get('testFile.php', sentData, successCallback);
}
$(document).ready(function () {
var id;
$('#doStuff').click(function () {
clearInterval(id);
//$.get('testFile.php', sentData, successCallback);
});
id = setInterval(doAjaxCall, 1000);
});
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" id="doStuff">Change Content</button>
<div id="myDiv"></div>
</body>
</html>
I understand the key is using flush right, but despite my best efforts and a lot of experimenting I'm unable to get it to work.
Can anyone see what I'm doing wrong?
This works for me using info I gathered from probably many sources including stackoverflow, sorry about the formatting. Every time you have text to flush, simply call the function:
function flush_message($msg)
{
echo $msg;
// not a space, just '', I haven't tried removing it to see what happens
// cause I should really be working on something else right now!
echo str_pad('', 4096) . "\n";
ob_flush();
flush();
}
I also set
apache_setenv('no-gzip', 1);
ini_set('zlib.output_compression', 0);
at the beginning of script
Apparently there are lots of browser specific issues as well (regarding how big buffer until output is drawn) so you might want to test on different platforms to see how it performs.
If I embed my XHR file into my HTML document directly, everything works fine. As soon as I src it via
<script type="text/javascript" src="js/ajax_gallery.js">ajax_json_gallery('gallery');</script>
Nothing works, and I get no errors. I'm assuming it's something to do with the XHR being created in a separate file to the HTML. I just don't like XHR script cluttering up my HTML, I just want to load as an external JS file.
I've moved my main 3 scripts, galleryHandle.php, XHR.js, ajax_gallery.html all to the same dir level to keep things simple. And the gallery images are in a folder called "gallery", also on the same level.
Here's my code:
HTML
<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="css/gallery.css" />
</head>
<body>
<div id="pagetop"></div>
<div id="thumbnailbox"></div>
<div id="pictureframe"></div>
<script type="text/javascript" src="XHR.js">ajax_json_gallery('gallery');</script>
</body>
</html>
JavaScript
function ajax_json_gallery(folder) {
"use strict";
var httpRequest = new XMLHttpRequest();
document.getElementById("pagetop").innerHTML = "dynamic ajax json gallery";
var thumbnailbox = document.getElementById("thumbnailbox");
httpRequest.open("POST", "galleryHandle.php", true);
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4 && httpRequest.status === 200) {
var data = JSON.parse(httpRequest.responseText);
var pictureframe;
pictureframe.innerHTML = "<img src='"+data.img1.src+"'>";
thumbnailbox.innerHTML = "";
for (var obj in data) {
if (data[obj].src){
thumbnailbox.innerHTML += '<div onclick="putinframe(\''+data[obj].src+'\')"><img src="'+data[obj].src+'"></div>';
}
}
}
};
httpRequest.send("folder="+folder);
thumbnailbox.innerHTML = "Loading...";
}
function putinframe(src) {
"use strict";
var pictureframe = document.getElementById("pictureframe");
pictureframe.innerHTML = '<img src = " '+src+' " >';
}
PHP
<?php
header("Content-Type: application/json");
//bring in folder name
$folder = $_POST["folder"];
//start componding json
$jsonData = '{';
//compound directory path
$dir = $folder."/";
//open directory
$dirHandle = opendir($dir);
//init while looop
$i = 0;
while ($file = readdir($dirHandle)) {
if(!is_dir($file) && strpos($file, '.jpg')){
$i++;
$src = "$dir$file";
$jsonData .= '"img'.$i.'":{ "num":"'.$i.'","src":"'.$src.'", "name":"'.$file.'" },';
}
}
closedir($dirHandle);
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
?>
I understand there are some redundancies in my code but it's just a tutorial I'm going through to learn the basics of JSON building with POST, XHR.
Anyway, help appreciated as always.
Thanks
Explanation
FROM W3C:
<script type="text/javascript" src="myscript.js">
alert('I am pointless as I won\'t be executed');
</script>
Upon meeting this element in a page, browsers will then load the file myscript.js and execute it. Any content inside the script element itself will be skipped when you provide a src attribute. The [last] example will load the file myscript.js and execute the code in it but will not execute the alert inside the script element at all.
Solution
Try the following in your head tags:
HTML
<script type="text/javascript" src="XHR.js"></script>
<script type="text/javascript">
ajax_json_gallery('gallery');
</script>
<script type="text/javascript" src="XHR.js">
You can't have src attribute and javascript both in a single tag. Separate them out. Like this...
<script type="text/javascript" src="XHR.js"></script>
<script type="text/javascript">ajax_json_gallery('gallery');</script>
I need export html table to excel with .xls extension in javascript or php
I am using below code but it does not export to file with .xls extension
If possible in php code embedded in javascript code then its fine.
Link to fiddle.
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,',
template = '<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">
<head>
<!--[if gte mso 9]>
<xml>
<x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
<x:Name>
{worksheet}
</x:Name>
<x:WorksheetOptions>
<x:DisplayGridlines/>
</x:WorksheetOptions>
</x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook>
</xml>
<![endif]-->
</head>
<body>
<table>{table}</table>
</body>
</html>'
,base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))); }
,format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p];}) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
});
using a download lib from http://danml.com/js/download.js, it's easy.
function download(strData, strFileName, strMimeType) {
var D = document,
A = arguments,
a = D.createElement("a"),
d = A[0],
n = A[1],
t = A[2] || "text/plain";
//build download link:
a.href = "data:" + strMimeType + "," + escape(strData);
if (window.MSBlobBuilder) {
var bb = new MSBlobBuilder();
bb.append(strData);
return navigator.msSaveBlob(bb, strFileName);
} /* end if(window.MSBlobBuilder) */
if ('download' in a) {
a.setAttribute("download", n);
a.innerHTML = "downloading...";
D.body.appendChild(a);
setTimeout(function() {
var e = D.createEvent("MouseEvents");
e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
D.body.removeChild(a);
}, 66);
return true;
} /* end if('download' in a) */
; //end if a[download]?
//do iframe dataURL download:
var f = D.createElement("iframe");
D.body.appendChild(f);
f.src = "data:" + (A[2] ? A[2] : "application/octet-stream") + (window.btoa ? ";base64" : "") + "," + (window.btoa ? window.btoa : escape)(strData);
setTimeout(function() {
D.body.removeChild(f);
}, 333);
return true;
} /* end download library function () */
// code that implements OP's functionality:
function tableToExcel (table) {
if (!table.nodeType) table = document.getElementById(table);
download(table.outerHTML, "table.xls", "application/vnd.ms-excel");
}
works in IE10, FF, and Chrome, maybe others as well.
In you Current File:
<?php
//Your Table code.
<a href="http://your_site_url.com/export_excel.php" target="_blank">
<input id="export-btn" type="button" value="Export as Excel" onclick="export()"/>
</a>
?>
Inside export_excel.php
<?php
$filename = 'Youe_Filename_without_extension';
header('Content-type: application/vnd.xls');
header('Content-Disposition: attachment; filename="'.$filename.'.xls"');
//Your Table code.
?>
Example Url: Demo
Update:
If you want it in the same file [to avoid duplication of the same code], then following code'll help:
<?php
$same_page = $_POST['same-page'];
if(!empty($same_page) && $same_page == 1) {
$filename = 'Sample Table';
header('Content-type: application/vnd.xls');
header('Content-Disposition: attachment; filename="'.$filename.'.xls"');
}?>
//Your Table code.
<?php if(empty($same_page)): ?>
//write whatever you want to hide in excel like export button,heading etc.
<form method="POST" action="" target="_balnk">
<input type="hidden" name="same-page" value="1"/>
<input id="export-btn" type="submit" value="Export as Excel on Form Submit"/>
</form>
<?php endif; ?>
I am trying to save json data to a file using AJAX and PHP but the resulting file is empty. Why is it not working?
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>
var dataset = {"value1": 2, "value2": 1000};
$.ajax({
url: 'save.php',
type: 'POST',
data: dataset,
success: function() {
alert('Success');
}
});
</script>
</body>
</html>
save.php:
<?php
$map=json_decode($_POST['json_string']);
$file = "test.json";
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, $map);
fclose($fh);
?>
You're using wrong POST variable name. Firstly, send your AJAX request with:
data: {
json: dataset
},
And then use:
$map = $_POST['json'];
Don't decode it since you want to save JSON string, not an array. If you want PHP representation, better use var_export():
$map = var_export(json_decode($_POST['json'], true), true);
change this line $map=json_decode($_POST['json_string']); to $map=json_decode($_POST['dataset']);
this code almost works
this will output the entire page into a jpg
question: how can i grab only the content inside '#myDiv' and output that as a jpg file?
JS:
$('.myButton').click(function(){
$('#myDiv').html2canvas();//<< has no effect
var queue = html2canvas.Parse();
var canvas = html2canvas.Renderer(queue,{elements:{length:0}});
var img = canvas.toDataURL();
img.replace(/^data:image\/(png|jpg);base64,/, "");
$.post( "postIO.php", {img:img}, function(data) {
//$('#recieve').append(data);
});
return false;
});
postIO.php:
$canvasImg = $_POST['img'];
//$canvasImg = str_replace('data:image/png;base64,', '', $canvasImg);
$data = base64_decode($canvasImg);
$File = "z.jpg";
$Handle = fopen($File, 'w');
fwrite($Handle, $data);
fclose($Handle);
reference from here
I have download and try html2canvas, then I find out the jquery plugin does not complete (it's does nothing than capture the image and create canvas, no use) so I write capture code myself.
var el = $('div').get(0);
function saveData(dturl){
//Upload here
console.debug(dturl);
}
html2canvas.Preload(el, {
complete: function(image){
var queue = html2canvas.Parse(el, image, {elements: el}),
$canvas = $(html2canvas.Renderer(queue, {elements: el}));
saveData($canvas[0].toDataURL());
}
});
Hope it help you
so to use with your program you have to write
function saveData(dturl){
dturl.replace(/^data:image\/(png|jpg);base64,/, "");
$.post( "postIO.php", {img:dturl}, function(data) {
//$('#recieve').append(data);
});
}
$('.myButton').click(function(){
var el = $('#myDiv').get(0);
html2canvas.Preload(el, {
complete: function(image){
var queue = html2canvas.Parse(el, image, {elements: el}),
$canvas = $(html2canvas.Renderer(queue, {elements: el}));
saveData($canvas[0].toDataURL());
}
});
});
after var canvasImg = canvasRecord.toDataURL("image/jpg");, you may need to replace it using var data = canvasImg.replace(/^data:image\/(png|jpg);base64,/, "");
and is that $canvasImg = $_POST['canvasImg']; instead of $_POST['img']?