Calculating loading time of multiple iframes with javascript - php

First i create an iframe for each url i have:
$url = array();
$url[] = 'example1.com';
$url[] = 'example2.com';
foreach($url as $u){
echo '<div class="frame_container">
<iframe "width="200" height="200" id="myiframe" src="http://www.'.$u.'"> </iframe>
<div class="loadingtime"></div>
</div>';
}
Then i have this javascript that should calculate the time before each frame starts loading, and the time after its loaded:
$(document).ready(function () {
load_time();
});
function load_time(){
var beforeLoad = (new Date()).getTime();
$('.frame_container iframe').on('load', function() {
var afterLoad = (new Date()).getTime();
var result = (afterLoad - beforeLoad) / 1000;
// beforeLoad = afterLoad;
$(this).parent().find('div.loadingtime').html(result);
});
}
My problem - the beforeLoad value is the same for all iframes. This value should be different for each frame because all fames dont start loading at the exact same time. Any suggestions?

write first div using php then remaining using your javascript code
var curFrame = 1;
var totalIFrame = 2;
var url = new Array('http://www.abc.com','http://www.xyz.com');
var beforeLoad = (new Date()).getTime();
var result = 0;
function addTime() {
var afterLoad = (new Date()).getTime();
result += ((afterLoad - beforeLoad) / 1000);
if(totalIFrame==curFrame){// number of iframe you will be loading
$(this).parent().find('div.loadingtime').html(result);
} else {
$('.frame_container').append('<iframe "width="200" height="200" id="myiframe" src="'+url[curFrame]+'" onload="addTime()"> </iframe>');
}
curFrame++;
}

Related

How to change frame to div and load content into div

Is there any way to convert an iframe with all attributes it contains into a div or php.
<iframe src='left_nav.php' name='left_nav' class="daemon" scrolling="auto" frameborder='0' height='100%' width="100%"></iframe>
If I use the php include function to call the left_nav.php file:
<?php include left_nav.php; ?>
How to load content which was loading in the frame into the div.
In main.title file (other file)
function toencounter(rawdata) {
document.getElementById('EncounterHistory').selectedIndex=0;
if(rawdata=='') {
return false;
} else if (rawdata=='New Encounter') {
top.window.parent.left_nav.loadFrame2('nen1','RBot','forms/newpatient/new.php? autoloaded=1&calenc=')
return true;
} else if (rawdata=='Past Encounter List') {
top.window.parent.left_nav.loadFrame2('pel1','RBot','patient_file/history/encounters.php')
return true;
}
var parts = rawdata.split("~");
var enc = parts[0];
var datestr = parts[1];
var f = top.window.parent.left_nav.document.forms[0];
frame = 'RBot';
if (!f.cb_bot.checked) {
frame = 'RTop';
}
parent.left_nav.setEncounter(datestr, enc, frame);
top.frames[frame].location.href = '../patient_file/encounter/encounter_top.php?set_encounter=' + enc;
}
In left_nav file
setEncounter(edate, eid, frname) {
if (eid == active_encounter) return;
if (!eid) edate = '<?php xl('None','e'); ?>';
var str = '<b>' + edate + '</b>';
setDivContent('current_encounter', str);
active_encounter = eid;
encounter_locked=isEncounterLocked(active_encounter);
reloadEncounter(frname);
syncRadios();
var encounter_block = $(parent.Title.document.getElementById('current_encounter_block'));
var encounter = $(parent.Title.document.getElementById('current_encounter'));
var estr = ' <b>' + edate + ' (' + eid + ')</b>';
encounter.html( estr );
encounter_block.show();
}
function loadCurrentEncounterFromTitle() {
top.restoreSession();
top.frames[ parent.left_nav.getEncounterTargetFrame('enc') ].location='../patient_file/encounter/encounter_top.php';
}
This is a JS script to loadFrame2
function loadFrame2(fname, frame, url) {
var usage = fname.substring(3);
if (active_pid == 0 && usage > '0') {
alert('<?php xl('You must first select or add a visitor.','e') ?>');
return false;
}
if (active_encounter == 0 && usage > '1') {
alert('<?php xl('You must first select or create an encounter.','e') ?>');
return false;
}
if (encounter_locked && usage > '1') {
alert('<?php echo xls('This encounter is locked. No new forms can be added.') ?>');
return false;
}
var f = document.forms[0];
top.restoreSession();
var i = url.indexOf('{PID}');
if (i >= 0) url = url.substring(0,i) + active_pid + url.substring(i+5);
if(f.sel_frame)
{
var fi = f.sel_frame.selectedIndex;
if (fi == 1) frame = 'RTop'; else if (fi == 2) frame = 'RBot';
}
if (!f.cb_bot.checked) frame = 'RTop';
top.frames[frame].location = '<?php echo "$web_root/interface/" ?>' + url;
if (frame == 'RTop') topName = fname;
return false;
}
Since you want to load content of an other file (left_nav.php) into a div rather than into an iframe, you can use multiple ways to do that.
1) JS:
Create a div container which will hold your content:
<div id="left_nav"></div>
Now, you can use jQuery to load the content easily:
onClick="loadContent('path/to/file/left_nav.php')"
This would be your loadContent function:
function loadContent(path){
$("#left_nav").load(path);
}
2) PHP:
You could also use PHP (pass a parameter to the URL you are currently on yourfile.php?m=left_nav). Then you can include the file, with a controller (MVC principle -> if you want to learn more about it):
<?php
if($_GET["m"] == "left_nav")
include("left_nav.php");
?>
EDIT:
It seems like you need a little mix of both. Instead of your iframe you need to insert a div and load the content at the same time:
<div id="left_nav"><?php include("left_nav.php"); ?></div>
This should be equivalent to creating the iframe. Now, when you change the src of the iframe in your JS scripts, instead of using this line:
top.window.parent.left_nav.loadFrame2('pel1','RBot','patient_file/history/encounters.php');
try changing the content of the div as I stated previously at 1), but you should only need the loadContent function.

.getJSON function, append to PHP url, return data from PHP file

I found many examples of this getting data from a mysql query. What I want to pass back to jQuery function is parsed html content in JSON format. What I want to do is separate PHP code from my initial load of the page. I'm doing this in jQuery Mobile. I know, my description is bad, it's hard to phrase.
I get article names and links from my database and output listview in index.html. When the user clicks on an article, I'm passing the link in the URL, getting it in jQuery and trying to call a PHP file which Parses that URL. Here's ALL the code:
index.html:
<body>
<div data-role="page" id="mainNews">
<div data-role="content">
<ul id="fnews" data-role="listview"></ul>
</div>
</div>
<script src="js/getmainnews.js"></script>
</body>
getmainnews.js:
var serviceURL = "http://localhost/basket/services/";
var news;
$('#mainNews').bind('pageinit', function(event) {
getNews();
});
function getNews() {
$.getJSON(serviceURL + 'getmainnews.php', function(data) {
$('#fnews li').remove();
mainnews = data.items;
$.each(mainnews, function(index, mnews) {
$('#fnews').append('<li data-icon="false"><a style="white-space:normal;" href="newstext.html?url=http://www.basket-planet.com' + mnews.link + '">' + mnews.article + '</a></li>');
});
$('#fnews').listview('refresh');
});
}
getmainnews.php:
<?php
include 'connect_to_mysql.php';
mysql_query("SET NAMES UTF8");
$sql = mysql_query("SELECT * FROM basket_news");
$mainnews = array();
while ($r = mysql_fetch_assoc($sql)){
$mainnews[] = $r;
}
echo '{"items":'. json_encode($mainnews).'}';
?>
Everything loads fine but the next page comes up empty. Here's the next 3 files...Sorry that this is such a long topic.
newstext.html:
<body>
<div data-role="page" id="newstext">
<div data-role="content">
<div id="textcontent"></div>
</div>
</div>
</body>
newstext.js:
var serviceURL = "http://localhost/basket/services/";
$('#newstext').bind('pageshow', function(event) {
var url = getUrlVars()["url"];
$.getJSON(serviceURL + 'getnewstext.php?url='+url, displayNewsText);
});
function displayNewsText(data){
var newstext = data.item;
$('#textcontent').append(newstext);
}
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
And finally getnewstext.php:
<?php
include_once ('simple_html_dom.php');
$url = $_GET['url'];
$html = file_get_html(''.$url.'');
$article = $html->find('div[class=newsItem]');
$a = str_get_html(implode("\n", (array)$article));
#$a->find('div[style*=float]', 0)->outertext = '';
#$a->find('h3', 0)->outertext = '';
#$a->find('div[id=comments]', 0)->outertext = '';
#$a->find('script', 0)->outertext = '';
#$a->find('a[href*=register]', 0)->outertext = '';
#$a->find('div', 4)->outertext = '';
#$a->find('div', 6)->outertext = '';
echo '{"item":'. json_encode($a) .'}';
?>
So those are the 6 files. On the newstext.html, the URL contains the URL which I need to pass to my PHP file. I'm sure the problem is in the last three files. What am I doing wrong here? Thanks in advance!
Update: Console error fixed, but still no output on the page.
Update2: From searching around, I saw somewhere that json_encode only accepts arrays. My $a in last PHP script is content from a page containing all kinds of html tags. How can I turn this into an array? To make one key/value with the value being all that html content?
The error getUrlVars is not defined newstext.js:3 says it all. You are calling a function that is not defined anywhere. I did a quick search and you probably want this:
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}

using ajax to move javascript variable value to php variable?

I'm very new to coding and am creating an online system. Part of the system I have included Google Distance Matrix API which is JavaScript, whereas most of my other code is HTML or PHP. Unfortunately, I need the distance (which is calculated in JavaScript) to be in my PHP code so I can play about with it. I read I could use AJAX? I'm not terribly sure about what I'm doing but I had a go.
Before the page that includes the Google Map, there is a form. This means I have to use SESSION variables to move the data from the page before the Google page, to two pages after the Google page.. this is also where my Google script gets it's two locations to find the distance between. Which all works fine, I think.
PHP on Google page:
$date = $_POST['date'];
$time = $_POST['time'];
$length = $_POST['length'];
$numberofpeople = $_POST['numberofpeople'];
$useofbus = $_POST['useofbus'];
session_start();
$_SESSION['time'] = $time;
$_SESSION['date'] = $date;
$_SESSION['length'] = $length;
$_SESSION['numberofpeople'] = $numberofpeople;
$_SESSION['pickuplocation'] = $pickuplocation;
$_SESSION['destination'] = $destination;
$_SESSION['useofbus'] = $useofbus;
$pickuplocation = $_POST['pickuplocation'];
$destination = $_POST['destination'];
HTML on Google page:
</head>
<body onload="initialize()">
<div id="inputs">
<pre class="prettyprint">
</pre>
<form name="google" action="thirdform.php">
<table summary="google">
<tr>
<td> </td>
<td><input name="Continue" value="Continue" type="submit" ></td>
<td> </td>
</tr>
</table>
</form>
</div>
<div id="outputDiv"></div>
<div id="map"></div>
</body>
</html>
I won't post the JavaScript of the Google Matrix other than the AJAX:
var distance = results[j].distance.text;
$.get("thirdform.php", {miles:distance} );
I'm not sure if the code above is correct, I'm guessing I'm going wrong somewhere, probably here.
On the next page, (thirdform.php) PHP:
session_start();
$time = $_SESSION['time'];
$date = $_SESSION['date'];
$length = $_SESSION['length'];
$numberofpeople = $_SESSION['numberofpeople'];
$pickuplocation = $_SESSION['pickuplocation'];
$destination = $_SESSION['destination'];
$useofbus = $_SESSION['useofbus'];
var_dump($_SESSION);
echo "</br>";
$distance = $_GET['miles'];
echo "DISTANCE: " . $distance . "</br>";
I'm not able to get anything in the PHP variable $distance - it's empty. Am I coding incorrectly? I followed an example on-line from this website somewhere which claimed to work. I've read several articles and searched on Google and on this website but there doesn't seem to be a clear answer anywhere that isn't too complicated and relates to what I'm trying to do. I've read plenty of examples but they're all far too complicated for me to use and change to put into my code. There was some code I read where the page was sent straight to next page however I need to show the Google Map on my page and therefore need to use the button to move to the next page.
Could anyone give me a nudge in the right direction? Thanks.
JS:
<script>
var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var origin = '<?php echo $pickuplocation; ?>';
var destination = '<?php echo $destination; ?>';
var destinationIcon = 'https://chart.googleapis.com/chart? chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';
function initialize() {
var opts = {
center: new google.maps.LatLng(55.53, 9.4),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), opts);
geocoder = new google.maps.Geocoder();
calculateDistances()
}
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '';
deleteOverlays();
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
addMarker(destinations[j], true);
outputDiv.innerHTML += origins[i] + ' to ' + destinations[j]
+ ': ' + results[j].distance.text + ' in '
+ results[j].duration.text + '<br>';
}
}
}
}
function addMarker(location, isDestination) {
var icon;
if (isDestination) {
icon = destinationIcon;
} else {
icon = originIcon;
}
geocoder.geocode({'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
});
markersArray.push(marker);
} else {
alert('Geocode was not successful for the following reason: '
+ status);
}
});
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
<script type="text/javascript">
var distance = results[j].distance.text;
$('.button-class').click(function() { $.get("thirdform.php", {miles:distance}, function (data){alert(data)} ); });
</script>
Since you are overriding the form action with the $.get, try removing the form and using a <button> instead of an <input> button.
Then have your ajax request run on that <button>.
Edit:
It's also worth noting that you should probably just send data from the php file. You can then do any other manipulation("DISTANCE: ", "<br />") in the html/js.

how to solve this setTime out in javascript with an if condition?

here's my script , it's a combined php and javascript
<?php
$countdown = strtotime("22:00") - time();
$itemtime = "22:00";
$realtime = substr(date('H:i'),0,5);
?>
<script>
var itemtime = "$itemtime";
var countdown = '$countdown';
var url = "$redirectpage";
var realtime = "$realtime";
// HOW WILL I ADD AN IF STATEMENT WITH THE SETTIMEOUT FUNCTION
// WHEREBY, if(realtime == itemtime) ..that's the only time the
// redirection should occur
setTimeout(function(){
location.href='$redirectpage';
},countdown * 1000);
</script>
<?php
$countdown = strtotime("22:00") - time();
$itemtime = "22:00";
$realtime = substr(date('H:i'),0,5);
?>
<script>
var itemtime = "<?php echo $itemtime;?>";
var countdown = '<?php echo $countdown;?>';
var url = "$redirectpage";
var realtime = "<?php echo $realtime;?>";
// HOW WILL I ADD AN IF STATEMENT WITH THE SETTIMEOUT FUNCTION
// WHEREBY, if(realtime == itemtime) ..that's the only time the
// redirection should occur
setTimeout(function(){
if(realtime == itemtime) location.href='$redirectpage';
},countdown * 1000);
</script>
Assuming $redirectpage is set in JavaScript and not PHP. If it is set in PHP, you'll need to assign it as I did above.
I ended up with my own solution,i place this inside the setTimeout function
if(countdown < 0) setTimeout("location.reload(true);",1000); location.href= "$redirectpage";

Show Redirecting In.. CountDown Timer PHP

I have this code so far that redirects the user after 5 seconds to the correct URL:
<?php
$url = $_GET['url'];
header("refresh:5;url=$url");
include('ads.php');
?>
Please could you tell me how i could display a countdown timer saying Redirecting In.. with .. being the amount of seconds left. I am new to web development so all code will be helpful!
<script type="text/javascript">
(function () {
var timeLeft = 5,
cinterval;
var timeDec = function (){
timeLeft--;
document.getElementById('countdown').innerHTML = timeLeft;
if(timeLeft === 0){
clearInterval(cinterval);
}
};
cinterval = setInterval(timeDec, 1000);
})();
</script>
Redirecting in <span id="countdown">5</span>.
You can try this.
As this is a common beginner question; I just wanted to highlight that for best practise setInterval should, and can usually be avoided by using setTimeout recursively within a function.
For example:
var timer = 5,
el = document.getElementById('countdown');
(function t_minus() {
'use strict';
el.innerHTML = timer--;
if (timer >= 0) {
setTimeout(function () {
t_minus();
}, 1000);
} else {
// do stuff, countdown has finished.
}
}());
Excellent code by Kyle. I have modified the timer with a pause and resume button.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var time_left = 50;
var cinterval;
var timestatus=1;
function time_dec(){
time_left--;
document.getElementById('countdown').innerHTML = time_left;
if(time_left == 0){
clearInterval(cinterval);
}
}
function resumetime()
{
//time_left = 50;
clearInterval(cinterval);
cinterval = setInterval('time_dec()', 1000);
}
function defaultstart()
{
time_left = 50;
clearInterval(cinterval);
cinterval = setInterval('time_dec()', 1000);
}
function stopstarttime()
{
if(timestatus==1)
{
clearInterval(cinterval);
document.getElementById('stopbutton').value="Start";
timestatus=0;
}
else
{
clearInterval(cinterval);
cinterval = setInterval('time_dec()', 1000);
document.getElementById('stopbutton').value="Stop";
timestatus=1;
}
}
defaultstart();
</SCRIPT>
</HEAD>
<body>
Redirecting In <span id="countdown">50</span>.
<INPUT TYPE="button" value="stop" id="stopbutton" onclick="stopstarttime()">
</body>
</HTML>
Here is my take on it, without variables outside of the function. Depends on jQuery.
function count_down_to_action(seconds, do_action, elem_selector)
{
seconds = typeof seconds !== 'undefined' ? seconds : 10;
$(elem_selector).text(seconds)
var interval_id = setInterval(function(){
if (seconds <= 0)
{
clearInterval(interval_id);
if (typeof do_action === 'function')
do_action();
}
else
$(elem_selector).text(--seconds);
},1000)
}
​
Here is an example using it http://jsfiddle.net/VJT9d/

Categories