I've got a div that randomly shows 1 of 10 files on each pageload. I'd like this to reload on a set time interval of 8 seconds, giving me a different one of the 10 files each reload.
I've read a few of the related questions using jQuery .load as a solution but this doesn't quite work with my code since I'm not loading a specific file each time.
This is my div content:
<div id="tall-content">
<?
$random = rand(1,10);
include 'tall-files/' . $random . '.php';
?>
</div>
Thanks
Using only PHP to accomplish this is impractical. This example uses jQuery and PHP.
$(document).ready(function() {
$("#div").load("random.php");
var refreshId = setInterval(function() {
$("#div").load('random.php');
}, 8000);
$.ajaxSetup({ cache: false });
});
random.php
$pages = array("page1.php", "page2.php", "page3.php", "page4.php", "page5.php");
$randompage = $pages[mt_rand(0, count($pages) -1)];
include ($randompage);
while using PHP to generate the random content, you cannot get the div to reload that content without refreshing the entire page.
A better solution is to use AJAX. You can store that PHP code that's inside the div container as a seperate file, and use ajax to request that php file. You can also set an infinite loop to request the php file every 8 seconds. Here is a sample, but you will need to re-code it to your specification:
<script language="javascript" type="text/javascript">
<!--
function ajaxFunction(){
var ajaxRequest;
try{ajaxRequest = new XMLHttpRequest();} catch (e){try{ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {try{ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");} catch (e){alert("Error: Browser/Settings conflict");return false;}}}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById('tall-content').innerHTML = ajaxRequest.responseText;
}
}
var url = "random.php";
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
//-->
</script>
The only missing part is the refresh timer, since I do not program a lot in javascript I can't help you there. But the goal in this case is to create a file "random.php", put the random generator there, and use this script above to make an ajax request to random.php, which will place the output of that php script in the div container with the id of "tall-content". So really, you need to create another javascript which loops indefinitely calling the function "ajaxFunction()" and wait 8000 milliseconds .
If you want to do this while the user is sitting back in the chair on your page, the answer is javascript.
You could use this function for example.
function recrusive_timeout_function() {
setTimeout(function() {
recrusive_timeout_function();
}, 8000);
}
If you want to include a php file in that div (which outputs some html). Ajax is your friend and JQuery as a user friendly and easy to use javascript framework which handles your thinks really nice.
Related
I am building a chat. I have this Jquery working code which calls logs.php every second and refreshes the chat.
$(document).ready(
function(e) {
$.ajaxSetup({cache:false});
setInterval(function() {
$('#chatlogs').load('logs.php');
updateScroll();
}, 1000);
}
);
As you can see, also updateScroll, a JS function on my page, gets called. Updatescroll creates a variable, which I would like to pass on to logs.php, is there any way to do this? In other words, updatescroll basically checks everysecond if the user has scrolled up to the top of the chat. If so, I am gonna tell logs.php to load -say - another 10 messages. But in order to do this, I have to have something that from updatescroll passes on to the Jquery function and thus onto logs.php. You get it? Thanks
First, when it comes to ajax, I would recommend using a window.setTimeout, intervals can get tricky when you are running things asynchronously (if one call hangs you can end up with multiple calls to the same script).
so something more like:
(function($){
var update_messages = function(){
var count = updateScroll();
$('#chatlogs').load('logs.php?count='+count, function(){
window.setTimeout(update_messages, 1000);
});
}
$(document).ready(function(){
$.ajaxSetup({cache:false});
update_messages();
});
})(jQuery);
Then in your PHP script the "count" would be available via $_GET['count'].
EDIT: you can see an anonymous function is being sent as a second argument to load, this will be called AFTER the AJAX call is complete, so we can make sure only 1 of these is running at a time
I have a website where I need to update a status.
Like for a flight, you are departing, cruise or landed.
I want to be able to refresh the status without having my viewers to have and reload the whole page. I know there is a way to do it with AJAX and jQuery, but I don't have any understanding of how that works. I also don't want them to have and click a button.
If anybody knows how that would be done I much appreciate it!
This is typically achieved with a technique called AJAX. This technique loads data asynchronously (in the background) so it can update your content without needing to reload the page.
The easiest way to implement AJAX is with the jQuery load() method. This method provides a simple way to load data asynchronous from a web server and place the returned HTML into the selected element. The basic syntax of this method is: $(selector).load(url, data, complete); where the arguments are:
selector the existing HTML element you want to load the data into
url a string containing the URL to which the request is sent
data (optional) a plain object or string that is sent to the server with the request
complete (optional) a callback function that is executed when the request completes
The required URL parameter specifies the URL of the file you want to load.
The optional data parameter allows you to specify data (i.e. key/value pairs) that is sent to the web server along with the request. The optional complete parameter can be used to reference a callback function. The callback is fired once for each selected element.
A visualisation:
A simple example of using load(), where we load data dynamically when a button is pressed:
DEMO
// no need to specify document ready
$(function(){
// optional: don't cache ajax to force the content to be fresh
$.ajaxSetup ({
cache: false
});
// specify loading spinner
var spinner = "<img src='http://i.imgur.com/pKopwXp.gif' alt='loading...' />";
// specify the server/url you want to load data from
var url = "http://fiddle.jshell.net/dvb0wpLs/show/";
// on click, load the data dynamically into the #result div
$("#loadbasic").click(function(){
$("#result").html(spinner).load(url);
});
});
If you don't want to use the jQuery library, you can also use plain Javascript. Loading content is slightly more difficult that way. Here is an example of how to do it with javascript only.
To learn more about AJAX, you can take a look at https://www.w3schools.com/xml/ajax_intro.asp
Suppose you want to display some live feed content (say livefeed.txt) on you web page without any page refresh then the following simplified example is for you.
In the below html file, the live data gets updated on the div element of id "liveData"
index.html
<!DOCTYPE html>
<html>
<head>
<title>Live Update</title>
<meta charset="UTF-8">
<script type="text/javascript" src="autoUpdate.js"></script>
</head>
<div id="liveData">
<p>Loading Data...</p>
</div>
</body>
</html>
Below autoUpdate.js reads the live data using XMLHttpRequest object and updates the html div element on every 1 second. I have given comments on most part of the code for better understanding.
autoUpdate.js
window.addEventListener('load', function()
{
var xhr = null;
getXmlHttpRequestObject = function()
{
if(!xhr)
{
// Create a new XMLHttpRequest object
xhr = new XMLHttpRequest();
}
return xhr;
};
updateLiveData = function()
{
var now = new Date();
// Date string is appended as a query with live data
// for not to use the cached version
var url = 'livefeed.txt?' + now.getTime();
xhr = getXmlHttpRequestObject();
xhr.onreadystatechange = evenHandler;
// asynchronous requests
xhr.open("GET", url, true);
// Send the request over the network
xhr.send(null);
};
updateLiveData();
function evenHandler()
{
// Check response is ready or not
if(xhr.readyState == 4 && xhr.status == 200)
{
dataDiv = document.getElementById('liveData');
// Set current data text
dataDiv.innerHTML = xhr.responseText;
// Update the live data every 1 sec
setTimeout(updateLiveData(), 1000);
}
}
});
For testing purpose: Just write some thing in the livefeed.txt - You will get updated the same in index.html without any refresh.
livefeed.txt
Hello
World
blah..
blah..
Note: You need to run the above code on the web server (ex: http://localhost:1234/index.html) not as a client html file (ex: file:///C:/index.html).
You can read about jQuery Ajax from official jQuery Site:
https://api.jquery.com/jQuery.ajax/
If you don't want to use any click event then you can set timer for periodically update.
Below code may be help you just example.
function update() {
$.get("response.php", function(data) {
$("#some_div").html(data);
window.setTimeout(update, 10000);
});
}
Above function will call after every 10 seconds and get content from response.php and update in #some_div.
If you want to know how ajax works, it is not a good way to use jQuery directly. I support to learn the native way to send a ajax request to the server, see something about XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://some.com");
xhr.onreadystatechange = function () {}; // do something here...
xhr.send();
I've got a script in an HTML file that runs a php file every 30 seconds. The php file is intended to change a div's innerHTML. I don't seem to find the way to replace it.
I was using load() but there are several divs I want to keep updating every 30 seconds and I don't want to make the server GET that much requests. So I'm looking for one only php get and then change the innerhtml in those several divs
This is what i've got:
HTML:
<script type="text/javascript">
$(document).ready(function () {
$.get('php.php');
});
setInterval(function(){
$.get('php.php');
}, 30000);
</script>
<div id="foo"></div>
php.php:
document.getElementById("foo").innerHTML = '<?php
// some php code
?>';
I think the problem is I'm not being able to get the element from the parent HTML file. I don't know how to solve this...
Any suggestions will be more than aprecciated!
You are reinventing jQuery's load()
function fetchContent() {
$("#foo").load('php.php');
window.setTimeout(fetchContent, 30000);
}
$(fetchContent);
The server should just return the HTML content that you want to display.
EDIT
Since your comment is different from the original question.
function fetchContent() {
$("#foo").get('php.php', function(data) {
var html = $("<div/>").html(data);
$("#foo").html( html.find("#Section1").html() );
$("#bar").html( html.find("#Section2").html() );
$("#asd").html( html.find("#Section3").html() );
window.setTimeout(fetchContent, 30000);
});
}
$(fetchContent);
You would want to add an onError handler and might want to set the no cache option for the Ajax calls.
what you probably want is for your php.php to return some data, and then you use the success of the $.get to update your #foo; taking an example from http://api.jquery.com/jQuery.get/ and modifying it for your example
$.get("php.php", function( data ) {
$( '#foo' ).html( data );
});
hope that helps :)
Hope someone can help. I am new to javascript so please forgive any mistakes. I am trying to achieve the following:
I have an index page with an html table, split up into four quarters. Each quarter has a DIV ID, and an ajax load via jquery will reload individual DIV's with a PHP page sucessfully, after a certain delay.
What I am trying to do, is for one of the quarters, rotate three PHP pages in the DIV every 15 minutes, and keep looping. I had setup an array with three php sites in, and sucessfully used this with a counter variable to call the relavent entries in the array via jquery. If I put in the count number in the ajax code it works. I am now struggling to see how I can increment the counter, and also reset it once it has reached the third page.
I do not know if I can use the ajax.complete function to assist, as I dont know if I can put "standard" javascript inside this function.
Thanks for any assistance - my code is below:
var count = 0;
var page = new Array("page1.php","page2.php","page3.php");
var delay = ("9000");
(
function($)
{
$(document).ready(function()
{
$.ajaxSetup(
{
cache: false
});
var $container = $("#DivID");
$container.load(page[count]);
var refreshId = setInterval(function()
{
$container.load(page[count]);
}, delay);
});
})
(jQuery);
try this
var refreshId = setInterval(function()
{
$container.load(page[count]);
count = (count+1) % 3
}, delay);
This way when count reaches 3 it will be reset to 0. Percent sign is the module division
Do not use Set Interval.
it will lag and chain if the page load is slow, crashing your site
use setTimeout:
setTimeout(function_name, delay);
var function_name = function() {
$container.load(page[count], function(){
count = (count+1) % 3;
setTimeout(function_name, delay);
});
}
this way, the timeout isn't chained, it fires once the page load is completed
i am using MVC and my design for my website is that there is header and body and footer,
every page in my website will have the same header and the same footer, but with different body
and for ever page there is a JS file contains the jquery calls
and for many many pages when it is opening, jquery call works and get data from database using ajax and put that data in that page
my question is : sense the jquery calls begins with $(document).ready, so when i open any page, all the jquery call starts, i don't want that, but i want just the jquery for that page which is opening to be loaded
example
this jquery just for a page
$(document).ready(function(){
$.getJSON("http://localhost/Mar7ba/Cell/getAllCountries/TRUE",function(data){
var select = $("#countrySelector");
var options = '';
for(var i=0;i<data.length;i++){
options += "<option>"+data[i]+"</option>";
}
select.html("<option>Select Source</option>"+options);
});
});
and this jquery for another page , but it is loaded when i load the first page
$(document).ready(function(){
$.getJSON("http://localhost/Mar7ba/Type/getAllTypes/TRUE",function(data){
var options = '';
options+="<option>Select Type</option>";
for(var i=0;i<data.length;i++){
options += "<option>"+data[i]+"</option>";
}
$("#addPlace #apTypeSelect").html(options);
});
});
Test for the existence of the elements you're operating on, before you fire off the AJAX method. For instance, in your first example:
$(document).ready(function(){
var select = $("#countrySelector");
if (select.length) { // must test .length; 'select' always exists even if it's empty
$.getJSON("http://localhost/Mar7ba/Cell/getAllCountries/TRUE",function(data){
var options = '';
for(var i=0;i<data.length;i++){
options += "<option>"+data[i]+"</option>";
}
select.html("<option>Select Source</option>"+options);
});
}; // end if
});
If you don't want a script to run on a page then either:
Don't put it on the page in the first place or
Wrap it in a conditional that checks if running it would be appropriate for the current page
I think if you will put all the startup functions of all pages in document.ready then function will become too lengthy and readability will be effected. You should write different start-up function for each page and call them from page on loading , in this your code will remain simpler e.g.
In js file
function InitialFunctionOfPage1()
{//define all prerequisites}
function InitialFunctionOfPage2()
{//define all prerequisites}
and in each page you can relevant function on document.ready , ample for page 1
$(document).ready(function()
{
InitialFunctionOfPage1();
}