setInterval - load PHP with POST - return image - javascript

I'm trying to use setInterval() to reload an image from a given path. I have some similar code to reload a log file which is working fine:
var auto_refresh = setInterval(
function auto_refresh_log()
{
$('#log_output').load('refresh_log.php').fadeIn("slow");
}, 1000);
refresh_log.php:
<?php $file = "/var/www/html/mainLOG";
$contents = file($file);
$string = implode( $contents);
echo $string; ?>
Now, I want to do something similar only with 2 changes:
Instead of using a fixed path like in refresh_log.php, I want to pass the path from the JS function to the PHP file. How can I do that?
Instead of returning a string, I want to return an image, which is then used in my html document. How can I do that?
To be exact on what I want to do: I have an index.php on which a user can select a file path. After setting some further parameters, some calculations start in the background. The results are saved as TIFF-files which cannot be read by the browser. So I want to use a PHP script with imagemagick to convert them (which is working fine) and pass them back to the JS. Then, the image should be displayed on my HTML <img id="image_id" ... > and refreshed every couple of seconds just like the log file.
Thanks!

One way would be to change the src attribute of the img element.
The browser will download the resource when you change the the src of the img element. Use the jQuery attr to do this. You should append a timestamp parameter so the browser does not obtain a cached instance from the local browser cache.
function loadImg(src) {
// append a parameter of "_" to the url
$("#myimg").attr("src", src + "?_=" + Date.now());
}
setInterval(loadImg("path/to/img"), 1000);
On your PHP side you would need a script that servers the image up in your converted format from where ever you are storing it. An example of how to do that is here.

I've managed to come up with a solution using $.post instead of $.load. The function is called via:
setInterval(
function auto_refresh_img()
{
var img_path = document.getElementById("image_path").value;
$.post('refresh_img.php',
{path: img_path},
function(data) {
$('#my_div').html(data);}
);
}, 1000);
with refresh_img.php looking like this:
<?php $imagepath = $_REQUEST['path'];
if (file_exists($imagepath)) {
$img = new imagick($imagepath."[0]");
$img->setImageFormat('jpg');
$thumbnails0 = $img->getImageBlob();
echo "<img src='data:image/jpg;base64,".base64_encode($thumbnails0)."' id='reco_background' style='display:none' />";
}
else {
echo "Image does not exist.";
};
?>
The returned <img ... > may then be used for any purpose.

Related

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 save div content (img) on server

I am developing a web application where users can crop images.Users must be able to email the URL so others can view the cropped image. This means every cropped image must be stored on the server so that the URL will never die. The portion of my HTML that contains the cropped image is:
<div class="contain" id="myDiv">
<img src="" id="croppedImage">
</div>
The cropping function works fine and it is written in JavaScript. I am using PHP to parse through the DOM, extract the image and save it on the server but it is not working. Any help will be greatly appreciated.
<?php
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$divContent = $xpath->query('//img[id="croppedImage"]');
$my_server_img = $divContent;
$img = imagecreatefromjpeg($my_server_img);
$path = 'images_saved/';
imagejpeg($img, $path);
?>
After reviewing your code and checking out the functions you are using I looked at this part: $xpath->query('//img[id="croppedImage"]'); and compared to http://php.net/manual/en/domxpath.query.php you can see that the function returns a DOMNodeList element (even if nothing is found it will return the object with no children.. You are then taking this object and passing it to imagecreatefromjpeg($filename) that accepts a string as $filename, not an object. Also your xpath selector is wrong, you need to prefix id with # like so: $xpath->query('//img[#id="croppedImage"]');
So here is some code that will grab an <img /> element off a page by it's id and then download the URL of the src attribute and save it. You will want to make sure that the src of the image you are downloading is a jpg file otherwise imagecreatefromjpeg() will fail. You could use CURL or another method to download images (so you can get png images as well) but that is out of the scope of this answer.
$dom = new DOMDocument();
$dom->loadHTML('
<html>
<img src="http://images.freepicturesweb.com/img1/18/02/13.jpg" id="croppedImage2"/>
<img src="http://images.freepicturesweb.com/img1/18/02/14.jpg" id="croppedImage3"/>
</html>
');
$xpath = new DOMXPath($dom);
$imageElements = $xpath->query('//img[#id="croppedImage2"]');
// make sure $imageElements isn't empty
if($imageElements->length) {
// grab first item in list (should only be one)
/** #var DOMElement $imageElement */
$imageElement = $imageElements->item(0);
// get the src attribute off the <img>
$src = $imageElement->getAttribute('src');
// download and create image resource based off $src
$img = imagecreatefromjpeg($src);
// save image with random name to current directory
$filename = __DIR__.'/'.base_convert(sha1(uniqid(mt_rand(), true)), 16, 36).'.jpg';
imagejpeg($img, $filename);
echo "File saved to: ".$filename;
}
Should also be noted that you were assigning a variable to a variable. Things can get messy quick by doing this. If you want a variable to be called something else just set the name when you initialize it instead of assigning it to another variable with the name you want (I'm guessing this is just something you left over after trying some code out, but still worth mentioning).

How to create an Image object with a base-64 source?

I have a remote web page, on which I use CURL and DOMDocument to retrive the src attribute of an image.
I use the following code, mixing JS in a PHP echo
<?php
$toEcho = "";
$toEcho .= // some stuff here...
$toEcho.="
<script>
//I create the object
var img = new Image();
//I set the source with the PHP variable : I get an error because of unexpected token ":"
img.src = $imgsrc;
</script>"
echo $toEcho;
?>
I checked the source, it is valid, and displays properly in my browser(s).
Where could this come from ?
Set the source like this:
img.src = '$imgsrc';

Passing variables in a URL of a php page to JavaScript and to another PHP

Based on the code in this link http://webaudiodemos.appspot.com/AudioRecorder/index.html, I am making changes to send the recorded audio file to server by passing a sessionId via URL. The php page is http://xxxxx/abc.php?sessionId=Sam. PHP versions: PHP 5.4 PHP 5.5.22. I am using the 2nd method from this link:How to pass variables and data from PHP to JavaScript?. The abc.php page has reference to a few JS codes as with the index.html from the link above. abc.php page process the URL values correctly with the following code:
<div id="bottom">
<?php
$faid = $_GET["sessionId"];
echo htmlspecialchars($faid); // tested working
?>
</div>
On the recorder.js JavaScript,I have a function that tries to pass the URL values to another PHP while uploading the audio file to server - The fname is not being passed on ... it seems .. can the xhr.send(blob) will still send the fname?
Recorder.setupDownload = function(blob){
var div = document.getElementById("bottom");
var fname = div.textContent;
var xhr = new XMLHttpRequest();
xhr.open('POST', "./uploads.php?" + fname, true);
xhr.onload = function(e) {};
// Listen to the upload progress.
var progressBar = document.querySelector('progress');
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
progressBar.value = (e.loaded / e.total) * 100;
progressBar.textContent = progressBar.value; // Fallback for unsupported browsers.
}
};
xhr.send(blob);
The uploads.php in the server has the following script to receive the value and to create an audio file - but it is not creating the audio file - however, if I fix the file name (eg: "filename123") it writes the audio file - so the issue is in passing the variable name - I am a newbie and I wonder what am I missing?:
<?php
ini_set("display_errors", true);
error_reporting(E_ALL);
if(isset($_GET['fileId']) && !empty($_GET['fileId'])){
$id = $_GET["fileId"];
}
$fp = fopen( $id, 'wb' ); // writes the audio file
fwrite( $fp, $GLOBALS['HTTP_RAW_POST_DATA'] );
fclose( $fp );
?>
Update: It is working!
You didn't give your value a name, so you're passing a value that will appear as DIFFERENT key in every page.
e.g. each of your users will have something like
http://example.com?foo
http://example.com?bar
leading to $_GET['foo'] and $_GET['bar'] in PHP. But since foo/bar are some randomish value representing your session ID, you have no idea what that value will be. So... give it a name:
http://example.com?key=foo
Now you just do $key = $_GET['key'] and can always access your session value, no matter what value it really as - it'll always be assigned to the key.

exchange variables between html files in javascript

I am trying to share variables between two html pages. I am only using javascript and HTML5 to develop a windows 8 app. Based on an image which a user clicks on one page, I want a div on a second page to be populated with that image. Any ideas?
When I click on the image, I am currently calling the following function:
function imageClick(url) {
//var id = parsed.ClientID;
//window.location= url + "?" + id
window.location = url;
}
Then in my html file, I have this line:
<img onclick="imageClick('pages/page2/page2.html')"
data-win-bind="src:image" style="width: 133px; height: 125.5px;">
I was thinking of getting that id in the next page's url (if I were to uncomment the commented lines above) but it's a bit hackky and I don't actually know how to go about executing the retrieval of that on the next page..
Is there a more efficient and easy way of doing this in javascript? Like an equivalent of sessions in php or something?
Javascript does not have session variables because it runs on the client side. You can use URL parameters and cookies in order to achieve the same results.
You can get the URL parameter by using this function:
http://ziemecki.net/content/javascript-parsing-url-parameters
Add the link to the image to the query part of the url when they click. Something like you had in the comment, assuming you don't have a query part already:
function imageClick(url) {
//var id = parsed.ClientID;
window.location= url + "?src=" + url.src;
//window.location = url;
}
The other page can use window.location.search to extract it, strip off the src=. The code would look something like this:
var src = window.location.search;
if (src.indexOf("src=") == 0) {
src = src.substring(4);
}
newPageImageElement.src = src;
Where newPageImageElement is the <img> where you want to display the picture on the second page.

Categories

Resources