pause PHP untill event/function with javascript is complete - javascript

Here are my code:
<script type="text/javascript">
function SaveToDisk(fileUrl, fileName) {
var hyperlink = document.createElement('a');
hyperlink.href = fileUrl;
hyperlink.target = '_blank';
hyperlink.download = fileName || fileUrl;
var mouseEvent = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
hyperlink.dispatchEvent(mouseEvent);
(window.URL || window.webkitURL).revokeObjectURL(hyperlink.href);
}
</script>
</head>
<body>
<?php
$newtarget = "0C004B290BF2D95F";
$filename = 'C:/Users/FOO/Downloads/'.$newtarget.'.txt';
if (file_exists($filename)) {
unlink($filename);
}
?>
<script type="text/javascript">
SaveToDisk('http://www.ticketmaster.com/json/resale?command=get_resale_listings&event_id=<?php print $newtarget; ?>','<?php print $newtarget; ?>.txt')
</script>
<?php
$newlink = file_get_contents('C:\\Users\\FOO\\Downloads\\'.$newtarget.'.txt');
When the file is deleted the file_get_contents php function runs before the SavetoDisk rewrite the file on disk.
"failed to open stream: No such file or directory".
When I don't delete the file, it works. I tried to insert sleep(10) right after the call of the javascript function but still got the error, inexplicably the file is wrote after the 10 seconds... any tips on this?

PHP is processed by your server whereas Javascript is processed by the user's browser, therefore regardless of how you order functions within the same .php doc, the Javascript will always run after the PHP is processed.
If you need to run PHP after your Javascript has been executed, look at jQuery's post function to call a PHP file from your Javascript. I'd strongly recommend you take a look at some online learning tools like codecademy to get a better grasp of PHP / JS.

You can't do that. PHP is executed on the server and JavaScript is executed on the client (web browser).
Right click on your web browser and select View Source to check the content. You will not see your PHP there.

Related

How to print a pdf on client side from a groovy webApp?

I am know developping a webapp that as to create a pdf document and print it on client side.
Here is my problem:
i created the pdf using itext and stored it in a shared folder. i did it on a server side.
Now i need to print the created pdf on the client side, the client knows the path of the pdf and can access it.
To be on client side, i am trying to print that document using javascript or jquery.
I tried using embed in my html but it didn't work.
Thx for helping,
here is a working code on server side :
FileInputStream fis = new FileInputStream("test.pdf");
DocFlavor psInFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
Doc pdfDoc = new SimpleDoc(fis, psInFormat, null);
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
PrintService services = PrintServiceLookup.lookupDefaultPrintService();
DocPrintJob job = services.createPrintJob();
job.print(pdfDoc, aset);
and here is what i tried on client side :
// Grabs the Iframe
document.write('<embed type="application/pdf" src="\\SN782629\TempPartage\test.pdf" id="PDF" name="PDF" width="100%" height="100%" />');
var ifr = document.getElementById("PDF");
//PDF is completely loaded. (.load() wasn't working properly with PDFs)
ifr.onreadystatechange = function() {
if (ifr.readyState == 'complete') {
ifr.contentWindow.focus();
if ($.browser.msie) {
document.execCommand('print', false, null);
} else {
window.print();
}
}
ifr.parentNode.removeChild(ifr);
this second code is on the success section of ajax request, i can put the entire function if needed.
fyi: Recommended way to embed PDF in HTML?
and another point: you'll meet a lot of restrictions in different browsers when including pdf from local file system into a page loaded through HTTP.
i'll advice to expose your pdf through url on your server. for example http://myhost/getPdf/SN782629/TempPartage/test.pdf instead of ""\SN782629\TempPartage\test.pdf" and use this link in rendered page.

How to have every visitor on a website be on the same point of an audio file to simulate a scheduled live stream?

I am attempting to simulate a scheduled live audio stream without the use of any third party tools/software. In order to do so, I would need every visitor on the website to be on the same point on the audio file. My initial plan was to have a PHP script that keeps track of the time, and write to a .json file :
ini_set('max_execution_time', 0);
include 'mp3file.class.php';
$file = "./audioDuration.json";
$mp3file = new MP3File("Nightride.mp3");
$duration = $mp3file->getDurationEstimate();
$tracker = 0;
while($tracker < $duration){
$tracker++;
file_put_contents($file, $tracker);
sleep(1);
}
And the Javascript :
$.getJSON( "audioDuration.json",
function( returnedData ) {
document.getElementById('audioElement').currentTime = returnedData;
}
However, being completely new to PHP, I did not realize that any user can run this script on their own browser, and it would cause the audioDuration.json to contain the wrong data. I've done some research, and it appears that there are ways to have a PHP script only run if the server requests it. I am not sure if this is the most practical way to accomplish this.
I feel you should use a server side resource to be sure any client get the same "time" to set-up your audio file.
Why don't you use something like server date('H:i:s); function. If you get a 1hour long file you just need to dont take care about hours, and use only minutes and seconds to get which time should be used to start the audio file.
And you don't even need to use javascript to call server to get the value. If you use php to generate your HTML you can directly print value in the HTML's javascript when loading the page, something like :
echo '<script type="text/javascript">
document.getElementById('audioElement').currentTime = ' . $timer . ';
</script>';

How to know if php file is being called within a src="..."?

In my website I have
<script src="js.php"></script>
Question is very simple but I have no idea of the answer:
Within js.php, how can I check if the file has been called though a script src="..."?
Purpose is to change the returned HTML code of js.php depending on how this php script file is called (direct access or script src="...").
The way to do it would be to assign a session variable to true right before you call the js.php file
session_start();
$_SESSION['src'] = true;
<script src="js.php"></script>
Then in the php file
session_start();
if(isset($_SESSION['src']) && $_SESSION['src'] == true) {
// file was called from a src
$_SESSION['src'] = false; // this is important so that it can't be called from direct access
}
Cool question. Let me help ya.
I'll provide here some not 100%-reliable methods, that will work in standard, non-user-malicious cases.
First
For this solution you will be required to download mimeparser from here. It's your choice what kind of mimeparser you want to use, I found this just ad-hoc for purpose of this answer.
Theory
In theory browser is sending headers, that your script during response should match for proper browser-side parsing. Especially I have here in mind HTTP_ACCEPT header.
Code example
Once you have downloaded mimeparser, lets start with creating file test.php:
<?php // test.php
//https://code.google.com/p/mimeparse/
include_once('mimeparse.php');
$mimeMatch = Mimeparse::best_match(array('text/javascript', 'text/css', 'text/html', 'application/xhtml+xml', 'application/xml', 'image/*'), $_SERVER['HTTP_ACCEPT']);
switch($mimeMatch) {
case 'text/javascript': // via <script src>
echo('alert("this is loaded as script");');
break;
case 'image/*': // via <image src>
header('Location: http://i.stack.imgur.com/sOq8x.jpg?s=128&g=1');
break;
case 'text/css': // via <link href>
echo('body::before{content: "this is written via CSS"}');
break;
default:
var_dump('detected standard file request by matching to ' . $mimeMatch);
// if __FILE__ is first on a list, its not included
if(__FILE__ !== array_shift(get_included_files())) {
var_dump('file was included or required');
} else {
var_dump('file runs on its own');
}
// additional detect for ajax request.
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
var_dump('loaded via AJAX request');
} else {
var_dump('loaded via not-AJAX request');
}
break;
}
die();
You can visit it by now, to see that script detects, its loaded directly:
string 'detected standard file request by matching to text/html' (length=55)
string 'file runs on its own' (length=20)
string 'loaded via not-AJAX request' (length=27)
Inclusion - feature showdown
To see, whats happening with script in some special cases, you can create an example index.php:
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.php"/>
</head>
<body>
<script src="test.php"></script>
<img src="test.php"></img>
<?php require('test.php'); ?>
Description
By parsing some standard-behavior headers sent from browser, we can predict loosely, what was context of page load. It's not 100% reliable and not a very good practice, but great for writing rootkits ;) anyway.
Hopefully rest is commented-out in PHP code.
Tested with Apache serving and Chrome reading.

Loading JavaScript Inline

I am trying to load some JavaScript files inside another JavaScript file in the following case:
js/script1.js
var script_1_method = function () {
console.log("Hello Script 1");
}
js/init-script.js
console.log("Initiating Scripts...");
loadScriptMethod('js/script1.js');
script_1_method();
console.log("Hello Script 2");
index.html
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/init-script.js"></script>
</head>
<body>
</body>
</html>
The Console output should be
Initiating Scripts...
Hello Script 1
Hello Script 2
I have looked into many JavaScript loaders like curl.js, RequireJS, JSL almost all of them do an Asynchronous way of loading files requiring callbacks for my scenario.
Is there a library to load the scripts in a synchronous way as in the above case without requiring callbacks.
Please let me know if there are any JavaScript loader libraries which cater to the above case.
It's possible to load same-origin scripts using a synchronous XHR:
var scr = getViaSynchronousXHR('js/script1.js'),
el = document.createElement("script");
el.appendChild(document.createTextNode(scr));
document.documentElement.firstChild.appendChild(el);
script_1_method();
A script element without a source is parsed and executed synchronously, because there is no wait for the file to be downloaded/fetched from cache.
if all your scripts are on the same domain, you can run a synchronous ajax call to get the script, use eval to run it, and then continue
The thing you want to do is quite difficult. I had a lot of problems with synchronous AJAX requests to correctly load my javascript files dynamically.
Actually I implemented something that worked synchronously on my project which is the same as you want.
It is only possible if you have a server-side scripting engine (e.g. PHP) to generate your HTML page.
The idea is to parse the init-scripts.js on server side prior to include them into the html code.
Instead of writing echo <script type="text/javascript" src="js/init-script.js"></script> in my PHP script I write : JavascriptLoader::addJavascript('js/init-script.js');
JavascriptLoader is a PHP class which manages scripts to be loaded.
This addJavascript function parses the init-script.js and, each time it encounters a line which starts with "loadScriptMethod(",
it parses and uses the string between brackets (e.g loadScriptMethod('thisString')) as the scriptToLoad
and then calls recursively JavascriptLoader::addJavascript($scriptToLoad);
JavascriptLoader::addJavascript then do an echo '<script type="text/javascript" src="'.$scriptToLoad.'"></script>' to write
I cannot publish the JavascriptLoader code from my project, but here is a simplified example of PHP code:
class JavascriptLoader{
...
public static function addJavascript($filepath){
self::init(); //Init to write the javascript loadScriptMethod definition into HTML output
if (!self::isScriptAlreadyLoaded($filepath)){
self::parseFile($filepath);
echo '<script type="text/javascript" src="'.$urlScript.'"></script>',"\n";
self::ajouterScriptDejaCharge($chemin);
}
}
private static function parseFile($filepath){
if (file_exists($filepath)){
$lines = file($filepath, FILE_SKIP_EMPTY_LINES);
foreach($lines as $line){
$matches = array();
$test = preg_match ('/^loadScriptMethod\(\s*[\'\"](.+)[\'\"]\s*\)/' , $line , $matches);
if ($test > 0){
$scriptToLoad = $matches[1];
//On inclut le fichier
self::addJavascript($scriptToLoad);
}
}
}
else{
throw new Exception('javascript source file '.$filepath.' does not exist.');
}
This also stores the $scriptToLoad into an array to avoid loading twice the same script (functions isScriptAlreadyLoaded and addScriptToAlreadyLoadedList).

What is the equivalent of wget in javascript to download a file from a given url?

"wget http://www.example.com/file.doc" downloads that file to the local disk.
What is the equivalent of the above in javascript? for example, consider the following html snippet.
<html>
<head>
<script language="JavaScript">
function download_file() {
var url = "http://www.example.com/file.doc"
//
// Question:
//
// what should be done here to download
// the file in the url?
//
}
</script>
</head>
<body>
<input type="button" value="Download" onclick="download_file()">
</body>
</html>
Please suggest a solution that is compliant with all the browsers.
Sangeeth.
After a exploring more than a month, with a help of my friend, we were able to find out the following.
The website where the file is hosted is not allowing us to download the file using window.location = url; or window.open(url);
Finally we had to use the data-downloadurl support from HTML5 as follows
Click here to download the file
We embed this html into the host html and when clicked on the link, it triggers the download.
Why not use:
function download_file() {
var url = "http://www.example.com/file.doc"
window.location = url;
}
See https://developer.mozilla.org/en/DOM/window.location
If you need to open this in a new window/tab first then use:
function download_file() {
var url = "http://www.example.com/file.doc"
window.open(url);
}
See https://developer.mozilla.org/en/DOM/window.open
First thing that always comes in mind of every answerer to this question is executing wget shell command from java script.I'm almost certain that that's not possible because of
major security risk.
You pretty much need to have ajax which sends command to command line
either through php, or another scripting language via ajax...
You could probably make that happen with something like http://www.phantomjs.org/
I am saying probably because I read it from somewhere.

Categories

Resources