I have a small script written in JavaScript that is used to change picture every second. The problem is that image is not being changed.
The image file that shuld be displayed is overwritten every second, with the new data.
Displaying the first image on the webpage works fine, but getting all of the subsequent images does not work, always the same picture is displayed.
JQuery code contains time extension to force the browser to reload new image every time and to not take it from the cache.
You can see the JQuery code for image loading.
<script type="text/javascript">
var auto_refresh = setInterval(function (){
$('#image').load('camera_stream_worker.php?time=' + Date.now());}
, 1000);
</script>
This is the return of the worker file:
<?php
echo '<img src="/RAMdisk/image.jpg" />';
?>
On the picture ou can see the network traffic.
So my question is: how can I display different picture every second?
thanks
ajax method:
may need to specify different content-type in the header.
$.ajax({
method: 'get',
url: 'camera_stream_worker.php?time=' + Date.now())
}).success(function(data) {
$('#image').html(data);
})
Could be that the image names are all the same, therefore it doesn't get new ones. try to add a timestamp to your images:
<?php
echo '<img src="/RAMdisk/image.jpg?<TIMESTAMPHERE>" />';
?>
this answer assumes the result were image srcs.
have you tried changing the src instead of load?
<script type="text/javascript">
var auto_refresh = setInterval(function (){
$('#image').attr('src', 'camera_stream_worker.php?time=' + Date.now());}
, 1000);
</script>
The issue here appears to be the fact you are returning an html document instead of just the image that is changing. The HTML has a hardcoded image.jpg in the source and since that does not change it is being pulled from the cache.
What you would need to do is change that image source to fetch the latest image and not update the entire html snipplet around it.
Other option is to make the php append the timestamp to the html.
Related
I have a code set up where I use JS and PHP to write to a file and display the output to a html element (in this case a textarea). I have a huge problem about how to go about this. I know that PHP is executed before anything else happens. I use php to echo the file content using my own javascript function
output(string) // this outputs whatever into the html element text area
PHP:
<?php echo "output('".$someText."');"; ?>
Now my problem comes around when I update and add contents to that file, but the php has already been executed and trying to read from the file again, will only display results from the last time it executed the php. The only way around this is to refresh the page, thus 'rebuilding' the html content of the file.
This whole code of mine mimics the look and feel of a command line ( you have an output screen with an input box) How can i dynamically display the contents of a file as new content is being added to the file without having to refresh the window. Refreshing the window will work, but not at all what i need for this to work. Any help with this?
For more information about how my code is structured, below you will find a snippet of how the code executes:
// main.php
<?php
// displays the file into the output box
function displayFile($fileName){
$file_handler = fopen($fileName, "r");
while (!feof($file_handler)){
$line = fgets($file_handler);
$line = formatFileLine($line);
echo "output('".$line."');";
}
fclose($file_handler);
}
?>
switch(splitCmd[1]){
case 'permitted':
output('\nWells that have been permitted:\n');
<?php displayFile('permitted.txt'); ?> //calls the php function to display content.
break;
case 'drilled':
output('\nWells that have been drilled:\n');
<?php displayFile('drilled.txt'); ?>
break;
default:
output('Wrong syntax: show <permitted, drilled>');
}
You can do this with an AJAX request, there are multiple ways to do this, but the easiest is with jQuery (opinion based ofcourse!), here is a link to the documentation. jQuery AJAX
Example:
function ajaxCall(){
$.ajax({ url: 'PHPFILE.php',
success: function(e){
//e is what you get returned from the php file
$('#div').html(e);
}
});
}
Oh, and you should ofcourse have the jquery library linked. which you do this way:
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
You need to make an AJAX call to your PHP file. Take the output from the PHP script, and embed this into, say, a given div on your page.
Let's pretend you have a div set aside for display. Let's give you a button to refresh it whenever.
<div id="resultdiv"></div>
<input type = "button" id="rbutton" value="Click to Refresh">
Style it any way that you please.
Now, let's set up an AJAX call to load the results from the PHP.
<script type="text/javascript">
$(function() { //document ready psuedonym
function refreshdata(){
$.ajax({
type: "POST",
url: "my_data_script.php",
dataType: 'html',
data: {myparam1: 'abc', myparam2: '123'}, //these are optional parameters in case your PHP script needs them
success: function(data){
$('#resultdiv').html(data);
},
error: function(){
},
complete: function(){
}
}); //end ajax
} //end function
$("#rbutton").click(function() { //clicking the button refreshes the data on demand
refreshdata();
});
refreshdata(); //this will run the function when the page loads
});//end document ready pseudonym
</script>
I'm creating a Hangman game for a project. I have most of the functionality I need, however I am having one issue. When the last incorrect guess is made, it displays the alert box telling you you've lost, before loading the image. I want the image to load first and then the alert box.
I realize that the issue is with the way the DOM loads elements and that I should create a callback function in jQuery.
This is the line in my code that changes the image, and it works fine until it gets to the last one.
document.getElementById("gallows").src = displayGallows[incorrectGuesses - 1];
I have tried using a Jquery function to get this working but my knowledge of jQuery is pretty much non-existent.
var img = $("gallows");
img.load(function() {
alert("Unlucky, you lost. Better luck next time!");
});
img.src = displayGallows[incorrectGuesses - 1];
I have compared this to many posts I have found online and to my untrained eye, it looks OK. When I was troubleshooting I did realize that the img.src was assigned the correct value but the image didn't appear on my page or didn't fire the alert box.
This led me to believe that it may be an issue with linking to the jquery.js file. I have an HTML page that references the jQuery file in it's head tag.
<head>
<title>Hangman</title>
<link rel="stylesheet" href="base.css"/>
<script src="jquery.js"></script>
<script src="hangman.js"></script>
<script src="home.js"></script>
</head>
The file I am writing my JavaScript and jQuery from is the hangman.js file.
Do I also need to refer to the jquery.js file from the hangman.js file? While reading up on this I found that I may have to do this, so I've tried this:
///<reference path="jquery.js" />
and this
var jq = document.createElement('script');
jq.src = 'jquery.js';
document.getElementsByTagName('head')[0].appendChild(jq);
but to no avail, though I don't really understand the second one, as I found these examples on the internet.
Note that in my home.js file I have simple a simple jQuery function to em-bold the text on a button when you mouseover it and this works OK.
If anyone could help me out or point me in the right direction that would be great.
Your best bet here is probably not to use alert at all; instead, use modern techniques like an absolutely-positioned, nicely-styled div to show your message. Showing that won't get in the way of the browser showing the image once it arrives, whereas alert basically brings the browser to a screeching halt until the user clicks the alert away.
But if you want to use alert:
Your concept of waiting for the load event from the image is fine, but you may want to yield back to the browser ever-so-briefly afterward to give it a chance to display the image.
Not using jQuery, as you don't appear to be using it otherwise:
var img = document.getElementById("gallows");
img.onload = img.onerror = function() {
setTimeout(function() {
alert(/*...*/);
}, 30); // 30ms = virtually imperceptible to humans
};
img.src = displayGallows[incorrectGuesses - 1];
That waits for the load or error event from the image, then yields back to the browser for 30ms before showing the alert.
But if you pre-cache the images, you can make the load event fire almost instantaneously. Most browsers will download an image even if it's not being shown, so if you add
<img src="/path/to/incorrect/guess.png" style="display: none">
...to your page for each of the incorrect guess images, then when you assign the same URL to your #gallows image, since the browser has it in cache, it will load almost instantly. Here's an example using your gravatar and a 30ms delay after load: http://jsbin.com/fazera/1
Firstly, to get an object by ID in jQuery, you have to use #.
var img = $("#gallows");
You can not use src or other "vanilla" properties directly on a jQuery object. You can, however do any of these:
Get the actual element from the jQuery object.
var img = $("#gallows");
img.load(function() { ... }
img[0].src = "image.jpg"; // First element in jQuery object
Use the jQuery method attr (recommended).
var img = $("#gallows");
img.load(function() { ... }
img.attr("src", "image.jpg");
Get the element just like you do now.
var img = document.getElementById("gallows");
img.onload = function() { ... }
img.src = "image.jpg";
please make sure that you have your jQuery code that's within the HEAD tag, inside:
$( document ).ready(function() { ...your jQuery here... });
More info: Using jQuery, $( document ).ready()
Your question: "Do I also need to refer to the jquery.js file from the hangman.js file?"
No, but place <script src="hangman.js"></script> tag in the header after referring to your jQuery file:
<head>
<script src="jquery_version_that_you_are_using.js"></script>
<script src="hangman.js"></script>
<script>
$( document ).ready(function() {
//Your jQuery code here
});
</script>
</head>
I use ajax to save user posts/comments into a mysql table without page refresh.
First: I have this <div id="posts-container"></div>
Second: I've tried using Jquery load() to loop in table and echo the posts, with the following code:
var auto_refresh = setInterval(function() {
$('.posts-container').load("refresh_p.php").fadeIn();
}, 0 );
But it doesn't work, page refreshes but content doesn't load, anybody knows why?
Third: If i copy the code that contains refresh_p.php and paste into the data gets loaded successfully. A little weird? Yes. Hope get any help :)
EDIT:
I fixed it, the problem was in refresh_p.php it was expecting the parameter 'profile_id'
i modified the function to this:
1: profile.php
search_user = document.getElementById('user_from').value;
var auto_refresh = setInterval(function() {
$('.posts-container').load("refresh_p.php?search_user="+search_user).fadeIn();
}, 5000 );
2: refresh_p.php
$profile_id = $_GET['search_user'];
All good, but now the whole page refreshes every 5 seconds. I just want the div 'post-container' to refresh.
I've used this function before to refresh a chat box and it worked, only refreshes the div i wanted to. but here it refreshes the entire page.
Don't use setInterval. Do recursive calls on jQuery load complete, this way you make sure that calls are sent one AFTER another, not at the same time.
Try this:
var auto_refresh = function () {
$('.posts-container').load("refresh_p.php", function(){
setTimeout(auto_refresh, 800);
}).fadeIn();
}
auto_refresh();
Also, .fadeIn() only works the first time, after that you have to hide the div before showing it again.
Demo: http://jsfiddle.net/P4P9a/1/ (might be slow because it is loading an entire page).
LE: As I think you are not returning an HTML page you should use $.get instead of $.load .
$('.posts-container').get("refresh_p.php", function(data){
$(this).html(data);
setTimeout(auto_refresh, 800);
}).fadeIn();
var auto_refresh = setInterval(function(){
$('.posts-container').load("refresh_p.php").fadeIn(50);
},1000);
Changed the interval from 0 (which would just create a crazy load...) to 1000ms (1 second). Should work if your path is correct.
Make sure your interval is long enough for your requests to finish. Also think about less real-time options, such as sending an array of messages every 15 seconds, showing them one after another on the client side. Optimize your server side for quick response using caching and also think about using json data and client side templating instead of html responses.
I have a php code, which is in a div. It shows a random text placed in the random.txt file. I want to refresh this div, to load new text in every - let's say - 15 seconds without refreshing the whoe page.
I've found several solutions to reload divs without refreshing a page and it seems it can be done with AJAX or JS, but they only refresh it with a specific content or a specific file, however I can't figure out how to insert this code and have it refreshed.
This is how my div looks like:
<div id="randomtext">
<?php
include_once("GetRandomText.php");
$MPTextFile = "random.txt";
$MPSepString = "*divider*";
$MPTextToHTML = false;
MPPrintRandomText($MPTextFile, $MPSepString, $MPTextToHTML);
?>
</div>
It loads a random text to the div at every refresh.
I tried to refresh the div it with the JS below, but it's not working at all. Sorry, I'm not good in it.
<script>
var auto_refresh = setInterval(
function () {
var newcontent= '<?php
include_once("GetRandomText.php");
$MPTextFile = "random.txt";
$MPSepString = "*divider*";
$MPTextToHTML = false;
MPPrintRandomText($MPTextFile, $MPSepString, $MPTextToHTML);
?>';
$('#randomtext').html(newcontent);
}, 1000);
</script>
<div id="randomtext"></div>
Thanks in advance.
PHP Script and Javascript are executed in separate environments. (Your server and user's browser, respectively.)
What you need to do is to move the embedded PHP script into a separate PHP file. And using somthing like this:
content.php
<?php
include_once("GetRandomText.php");
$MPTextFile = "random.txt";
$MPSepString = "*divider*";
$MPTextToHTML = false;
MPPrintRandomText($MPTextFile, $MPSepString, $MPTextToHTML);
?>
Inside your html page
<script>
var auto_refresh = setInterval(
(function () {
$("#randomtext").load("path/to/content.php"); //Load the content into the div
}), 1000);
</script>
<div id="randomtext"></div>
Document for jQuery Load function: http://api.jquery.com/load/
As far as I understand you, you are trying to execute your PHP in a browser which is not possible. Your server parses the PHP and replaces that code with the random string.
You need a AJAX request to your server which evaluates this script and sends it back to the client. In a simplified way:
request = new XMLHttpRequest();
request.open("GET", "my.php");
request.send();
$("#randomtext").html(request.response);
how to display the image at last after loading all the other contents in a webpage.
I've an image on a page which is retrieved from the database when a button is pressed.
I'd like to load entire page first and the image at last after the contents are loaded.
any help?
If by load you mean download the various parts of the page and construct the DOM, then:
$(document).ready(function() {
$('#theimage').show();
});
You can load and add it to your html it in javascript using this function:
$(window).load(function() {
// in 2 steps for clarity, can be optimized
img_html = '<img src="/path/to/image" alt="bla bla" />'; // step 1, generate image html
$("#image_div").append(image_html); // step 2, append image to some div
// optional, see my comment below
$("#image_div img").load(function() {
// triggers when newly added image is completely loaded
});
});
That makes sure loading of the image starts when everything else has finished loading.
Note that the image in the example shows while loading, if you want to load it first and then display it, you'll have to hide it and use the .load event of the image to display it.
$(document).ready(function() {
$('#imageid').attr( "src", "/new/path/to/image.jpg" );
});
In your initial load of the page you can just write a placeholder (div, span, even an image with nothing assigned to it.)
Then attaching to the button click event you can use JQuery + Ajax to callback (not postback, or is there any reason for the postback OTHER than to get the image?) to your server (or a webservice) to get the image path and assign that to the place holder. You can augment that with various jquery animations to "fade in" your image or slide down... what ever you like.
can you use javascript to dynamically set the image url after the dom loaded?
If you have html structure
<image id="image_id"/>
Then use the following jquery code:
$(document).ready(function() {
$("#image_id").attr("src", "link_to_image");
});
Or else, you can use some css trick, hide the image first, so it won't download from server.
Then use the following jquery code to show the image once DOM is ready:
$(document).ready(function() {
$("#image_id").show();
});
At the same time, looks at image preload. this may be useful to you http://www.techrepublic.com/article/preloading-and-the-javascript-image-object/5214317