finding screen resolution on resizing - php

I've been scratching my head about this for a few days now, hope you guys can help.
I need to find out the size of the browser when a page is loaded.
I am writing a PHP page with PHP and javascript. The page starts with this code:
if ( empty($_GET['w']) ) {
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<script type="text/javascript">
var winW = 630, winH = 460;
if (document.body && document.body.offsetWidth) {
winW = document.body.offsetWidth;
winH = document.body.offsetHeight;
}
if (document.compatMode=="CSS1Compat" &&
document.documentElement &&
document.documentElement.offsetWidth ) {
winW = document.documentElement.offsetWidth;
winH = document.documentElement.offsetHeight;
}
if (window.innerWidth && window.innerHeight) {
winW = window.innerWidth;
winH = window.innerHeight;
}
location.replace("'.$_SERVER['PHP_SELF'].'?w=" + winW + "&h=" + winH );
</script>
</body>
</html>';
} else {
$w = $_GET['w'];
$h = $_GET['h'];
// my main page goes here
}
This code basically gets the resolution and then reloads the page with the width and height sent in the url's query so that PHP can then use those values.
The problem is: when the user resizes his/her window and then reloads the page, the values sent are the old values (because they are still in the URL query).
How can I find new values of width and height every time a page is loaded or reloaded?
Thanks

I am not 100% sure, but you can't stop page from begin reloaded by user interaction. But you can listen to page unload events so that you can do what you need to do.

The problem with this code of yours is that it does absolutely nothing if w and h exist as url parameters. If you look at the source, it'll be blank.
What you should do is to check if the url parameters match with the actual values that the window currently has and then proceed to do whatever it is you plan on doing.
<?php
$w = 0;
$h = 0;
if (isset($_GET['w'])) {
$w = $_GET['w'];
}
if (isset($_GET['h'])) {
$h = $_GET['h'];
}
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<script type="text/javascript">
window.onload = function(event) {
var winW = 630, winH = 460;
if (document.body && document.body.offsetWidth) {
winW = document.body.offsetWidth;
winH = document.body.offsetHeight;
}
if (document.compatMode=="CSS1Compat" &&
document.documentElement &&
document.documentElement.offsetWidth ) {
winW = document.documentElement.offsetWidth;
winH = document.documentElement.offsetHeight;
}
if (window.innerWidth && window.innerHeight) {
winW = window.innerWidth;
winH = window.innerHeight;
}
if (winW=='.$w.' && winH=='.$h.') {
document.write("Yay, victory!");
} else {
location.replace("'.$_SERVER['PHP_SELF'].'?w=" + winW + "&h=" + winH );
}
}
</script>
</body>
</html>';
// my main page goes here
?>

How about using jQuery, with polling to a script that will return the value received via GET as json. It will update to any value as the screen is resized with no user interaction!
In my example it just updates the paragraph but you could also do something with the values. (Write less do more ;p)
<?php
if(isset($_GET['width']) && $_GET['height']){
$size = array('width'=>intval($_GET['width']),'height'=>intval($_GET['height']));
echo json_encode($size);
die;
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function poll(){
setTimeout(function(){
$.ajax({ url: "http://localhost/screensize.php?width="+ $(window).width() +"&height="+ $(window).height() +"",cache: false,
success: function(data){
//Do something with returned json
$("#screensize").replaceWith("<p id=\"screensize\">Width:"+ data.width +"px Height:"+ data.height +"px</p>");
//Next poll
poll();
}, dataType: "json"});
// 1/2 a sec
}, 500);
}
$(document).ready(function(){
poll();
});
</script>
<p id="screensize">Updating...</p>

Use Jquery. Roughly something like this should work. Attach a .resize handler to the window.
$(document).ready(function(){
echoWindowDimensions();
$(window).resize(function(){
echoWindowDimensions();
});
});
function echoWindowDimensions {
var h = $(window).height();
var w = $(window).width();
alert('height'+h+' width'+w);
}

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.

unable to pass variable to other page using ajax

I would need some advice/assistance here. I'm trying to pass 2 variable to other page from a link using ajax but when i click the link, there is no response. Seem like my ajax is not working, would appreciate if anyone can assist here. Thanks.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="productshow.js"></script>
</head>
<body>
<?php
$sql = mysql_query ("SELECT * FROM espaceproduct WHERE email = 'jaychou#hotmail.com' ");
?>
<?php
$result1 = array();
$result2 = array();
$loopCount1 = 0;
$loopCount2 = 0;
while($row = mysql_fetch_array($sql))
{
$result1[] = $row['thumbnail'];
$result2[] = $row['id'];
$_SESSION['thumbnail'] = $result1;
//$url = "profileview.php?email=".$result1[$loopCount1].'&'. "id=".$result2[$loopCount2];
$loopproduct = $result1[$loopCount1];
$loopid = $result2[$loopCount2];
echo"<br/>"."<br/>";
echo '<a href="#" onClick="ajax_post($loopproduct,$loopid)" >'. $_SESSION['thumbnail'][$loopCount1] .'</a>'."<br/>" ;
$loopCount1++;
$loopCount2++;
}
?>
</body>
</html>
This my ajax page
function list_chats(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
document.getElementById("showbox").innerHTML = hr.responseText;
}
}
hr.open("GET", "productshow.php?t=" + Math.random(),true);
hr.send();
}
setInterval(list_chats, 500);
function ajax_post(la,ka){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "espaceproductinsert.php";
var kn = "add="+la+"&csg="+ka;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status1").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(kn); // Actually execute the request
document.getElementById("csg").value = "";
}
This is the page where the variables should be insert
<?php
$add = $_POST['add'];
$csg = $_POST['csg'];
$sql2 = mysql_query ("INSERT INTO espaceproduct ( storename,productname ) VALUES ('$add','$csg') ");
?>
Smiply Try this
function ajax_post(la,ka){
$.post("espaceproductinsert.php", { add:la, csg:ka},
function(data) {
alert(data);
});
}
In page 1 add this script appropriately
<script language="javascript" type="text/javascript">
var httpObject=false;
if(window.XMLHttpRequest){
httpObject = new XMLHttpRequest();
}else if(window.ActiveXObject){
httpObject = new ActiveXObject("Microsoft.XMLHttp");
}
function tranferData(){
var data1= document.getElementById('div1').value;
var data2= document.getElementById('div2').value;
var queryString = "?data1=" + data1;
queryString += "&data2=" + data2;
httpObject.onreadystatechange = function(){
if(httpObject.readyState == 4 && httpObject.status == 200){
var error = document.getElementById('error');
var response = httpObject.responseText;
alert(response);
}
}
httpObject.open("GET", "page2.php"+queryString ,true);
httpObject.send(null);
}
</script>
You send the data using above script and recieve from another page
page 2
<?php
echo $_GET['data1'];
echo $_GET['data2'];
?>
and on the serverside do this
<?php
header('Content-Type: application/json');
echo json_encode($_GET); //for testing replace with array('key'=>$value);
?>

JavaScript loses image movement function when using a DOCTYPE

I have got a JavaScript here that is suppose to make an image (ghost) appear on screen, fly around for a bit, and then fade out before repeating again later on. The script works just fine without a DOCTYPE in my document, however if I add any DOCTYPEs, only the appear/disappear works. For some reason it doesn't move around on screen. The DOCTYPE I need to use is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
This has been driving me crazy and I can't seem to figure out how to make it compatible. I just need to get the movement portion working with a DOCTYPE. Any help with this would really be appreciated. Below is the script:
if(!window.JSFX) JSFX=new Object();
JSFX.ghostImages = new Array(
"<img src='/ghost.png'>",
"<img src='/ghost2.png'>"
);
var ns4 = document.layers;
var ie4 = document.all;
JSFX.makeLayer = function(id)
{
var el = document.getElementById ? document.getElementById(id) :
document.all ? document.all[id] :
document.layers[id];
if(ns4) el.style=el;
el.sP=function(x,y){this.style.right = x;this.style.top=y;};
el.show=function(){ this.style.visibility = "visible"; }
el.hide=function(){ this.style.visibility = "hidden"; }
if(ns4 || window.opera)
el.sO = function(pc){return 0;};
else if(ie4)
el.sO = function(pc)
{
if(this.style.filter=="")
this.style.filter="alpha(opacity=100);";
this.filters.alpha.opacity=pc;
}
else
el.sO = function(pc)
{
this.style.opacity=pc/100;
}
return el;
}
if(window.innerWidth)
{
gX=function(){return innerWidth;};
gY=function(){return innerHeight;};
}
else
{
gX=function(){return document.body.width-50;};
gY=function(){return document.body.height-50;};
}
JSFX.ghostOutput=function()
{
for(var i=0 ; i<JSFX.ghostImages.length ; i++)
document.write(ns4 ? "<LAYER NAME='gh"+i+"'>"+JSFX.ghostImages[i]+"<\/LAYER>" :
"<DIV id='gh"+i+"' style='position:absolute'>"+JSFX.ghostImages[i]+"<\/DIV>" );
}
JSFX.ghostSprites = new Array();
JSFX.ghostStartAni = function()
{
for(var i=0 ;i<JSFX.ghostImages.length;i++)
{
var el=JSFX.makeLayer("gh"+i);
el.x=Math.random()*gX();
el.y=Math.random()*gY();
el.tx=Math.random()*gX();
el.ty=Math.random()*gY();
el.dx=-5+Math.random()*10;
el.dy=-5+Math.random()*10;
el.state="off";
el.op=0;
el.sO(el.op);
el.hide();
JSFX.ghostSprites[i] = el;
}
setInterval("JSFX.ghostAni()", 40);
}
JSFX.ghostAni = function()
{
for(var i=0 ;i<JSFX.ghostSprites.length;i++)
{
el=JSFX.ghostSprites[i];
if(el.state == "off")
{
if(Math.random() > .99)
{
el.state="up";
el.show();
}
}
else if(el.state == "on")
{
if(Math.random() > .98)
el.state="down";
}
else if(el.state == "up")
{
el.op += 2;
el.sO(el.op);
if(el.op==100)
el.state = "on";
}
else if(el.state == "down")
{
el.op -= 2;
if(el.op==0)
{
el.hide();
el.state = "off";
}
else
el.sO(el.op);
}
var X = (el.tx - el.x);
var Y = (el.ty - el.y);
var len = Math.sqrt(X*X+Y*Y);
if(len < 1) len = 1;
var dx = 20 * (X/len);
var dy = 20 * (Y/len);
var ddx = (dx - el.dx)/10;
var ddy = (dy - el.dy)/10;
el.dx += ddx;
el.dy += ddy;
el.sP(el.x+=el.dx,el.y+=el.dy);
if(Math.random() >.95 )
{
el.tx = Math.random()*gX();
el.ty = Math.random()*gY();
}
}
}
JSFX.ghostStart = function()
{
if(JSFX.ghostLoad)JSFX.ghostLoad();
JSFX.ghostStartAni();
}
JSFX.ghostOutput();
JSFX.ghostLoad=window.onload;
window.onload=JSFX.ghostStart;
Here is an example of the script on a page without a DOCTYPE:
http://boomansion.net/test.php
...and an exmaple on a page with a DOCTYPE (look at the very bottom):
http://boomansion.net/test2.php
Thanks in advance!
You set setting top and left to Numbers, but they take lengths (and non-zero lengths must have a unit).
When you add a Doctype, browsers:
Assume you know what you are doing
Follow the specification more closely
(Consequently) are more consistent with each other
(Consequently) will treat more errors are "values to ignore" instead of "values to fix up automatically".
You probably want to + "px".

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/

php slideshow sample

I try to do a simple image slideshow in php (just cycle images, no links, no other effects).
after some googling I found the following in net:
<HTML>
<HEAD>
<TITLE>Php Slideshow</TITLE>
<script language="javascript">
var speed = 4000; // time picture is displayed
var delay = 3; // time it takes to blend to the next picture
x = new Array;
var y = 0;
<?php
$tel=0;
$tst='.jpg';
$p= "./images";
$d = dir($p);
$first = NULL;
while (false !== ($entry = $d->read())) {
if (stristr ($entry, $tst)) {
$entry = $d->path."/".$entry;
print ("x[$tel]='$entry';\n");
if ($first == NULL) {
$first = $entry;
}
$tel++;
}
}
$d->close();
?>
function show() {
document.all.pic.filters.blendTrans.Apply();
document.all.pic.src = x[y++];
document.all.pic.filters.blendTrans.Play(delay);
if (y > x.length - 1)
y = 0;
}
function timeF() {
setTimeout(show, speed);
}
</script>
</HEAD>
<BODY >
<!-- add html code here -->
<?php
print ("<IMG src='$first' id='pic' onload='timeF()' style='filter:blendTrans()' >");
?>
<!-- add html code here -->
</BODY>
</HTML>
but it displays only the first image from the cycle. Do I something wrong?
the resulting HTML page is:
<HTML>
<HEAD>
<TITLE>Php Slideshow</TITLE>
<script language="javascript">
var speed = 4000; // time picture is displayed
var delay = 3; // time it takes to blend to the next picture
x = new Array;
var y = 0;
x[0]='./images/under_construction.jpg';
x[1]='./images/BuildingBanner.jpg';
x[2]='./images/littleLift.jpg';
x[3]='./images/msfp_smbus1_01.jpg';
x[4]='./images/escalator.jpg';
function show() {
document.all.pic.filters.blendTrans.Apply();
document.all.pic.src = x[y++];
document.all.pic.filters.blendTrans.Play(delay);
if (y > x.length - 1)
y = 0;
}
function timeF() {
setTimeout(show, speed);
}
</script>
</HEAD>
<BODY >
<!-- add html code here -->
<IMG src='./images/under_construction.jpg' id='pic' onload='timeF()' style='filter:blendTrans()' ><!-- add html code here -->
</BODY>
</HTML>
I recommend you to use a ready made javascript framework, such as jQuery
As I remember, I used this: jQuery Cycle Plugin
I'm working on a jquery based slideshow plugin. You can add more images to the slideshow as the slideshow progresses.. it is in beta version.
http://smg-solutions.com

Categories