What Im trying to do: Display a loading gif or text... at the very least show a black screen before and during the time the php is being executed.
What I have tried.
I have tested using flush () and I get nothing until the entire php process is finished. I dont particularly like this concept either but I'll take anything.
I am considering using two pages to accomplish this though the current project is nearly complete and would take some time to consolidate the scattered html/php code.
Currently I'm doing 3-simpleXML_load_file(), 1-include(), 1-file_get_contents()
I have javascript function plotting data from one of the simpleXML_Load_file()...
Im up for moving parts of the code to a different file but it's a big task. So id like some advise or suggestions on how to proceed.
If I need to elaborate more just ask!
Thanks,
JT
<html>
<head>
<?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
?>
<script type="text/javascript">
<!--Plot function-->
$(function()
{
var d =
[
<?php
//Pulling in hourly data to plot temp vs time
$i=0;
$array=array();
while ($i<=100)
{
echo '['. (strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000) .','.$weather_hourly->data->parameters->temperature->value[$i] .'],';
$value = $weather_hourly->data->parameters->temperature->value[$i];
array_push($array,$value);
$i++;
}
foreach ($array as $key => $value)
{
$value = (string) $value;
$min_sec_array[] = $value;
}
?>
</script>
</head>
<body>
<div id=graph>
</div>
</body
The main way you can accomplish this is by using AJAX and multiple pages. To accomplish this, the first page should not do any of the processing, just put the loading image here. Next, make an AJAX request, and once the request is finished, you can show the results on the page or redirect to a different page.
Example:
File 1 (jQuery must be included also), put this in the body along with the loader animation:
<script language="javascript" type="text/javascript">
$(function(){
var mydata = {};
$.post('/myajaxfile.php', mydata, function(resp){
// process response here or redirect page
}, 'json');
});
</script>
Update: Here is a more complete example based on your code. This has not been tested and needs to have the jQuery library included, but this should give you a good idea:
File 1: file1.html
</head>
<body>
<?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
?>
<!-- Include jQuery here! Also have the loading animation here. -->
<script type="text/javascript">
$(function(){
$.get('/file2.php?Lat=<?php echo $lat; ?>&Lon=<?php echo $long; ?>', null, function(resp){
// resp will have the data from file2.php
console.log(resp);
console.log(resp['min_sec_array']);
console.log(resp['main']);
// here is where you will setup the graph
// with the data loaded
<!--Plot function-->
}, 'json');
});
</script>
<div id=graph>
</div>
</body
</html>
File 2: file2.php
I'm not sure if you needed the $min_sec_array, but I had this example return that as well as the main data you were using before.
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
//Pulling in hourly data to plot temp vs time
$i=0;
$main = array();
$array=array();
while ($i<=100)
{
$main[] = array((strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000), $weather_hourly->data->parameters->temperature->value[$i]);
$value = $weather_hourly->data->parameters->temperature->value[$i];
array_push($array,$value);
$i++;
}
foreach ($array as $key => $value)
{
$min_sec_array[] = (string) $value;
}
echo json_encode(array(
'min_sec_array' =>$min_sec_array,
'main' => $main
));
exit();
?>
I would recommend not to do this with plain html and php if u expect it modify the page after it is loaded. Because php is server side processing, so it is executed before the page is send to the user. U need Javascript. Using Javascript will enable u to dynamically add or remove html elements to or from the DOM tree after the page was send to the user. It is executed by the users browser.
For easier start I would recommend jQuery, because there are lots of tutorials on such topics.
JQuery
JQuery learning center
A small example:
HTML
<head>
<meta charset="utf-8" />
<title> </title>
<script type="text/javascript" src="js/lib/jquery-1.9.1.js"></script>
</head>
<body>
<h1>Addition</h1>
<div id="error_msg"> </div>
<div id="content">
<!-- show loading image when opening the page -->
<img src="images/loading.gif"/>
</div>
<script type="text/javascript">
// your script to load content from php goes here
</script>
</body>
this will be nothing more then the following until now:
adding the following php file
<?php
$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
$result = $num1 + $num2;
echo '<p>Calculating '.$num1.' + '.$num2.' took a lot of time, but finally we were able to evaluate it to '.$result.'.</p>'
.'<p> '.$num1.' + '.$num2.' = '.$result.'</p>';
?>
wont change anything of the html, but adding javascript/ Jquery inside the HTML will be kind of connection between static html and server side php.
$(document).ready(function(){
$.ajax({ // call php script
url: 'php/script.php?num1=258&num2=121',
type:'GET',
timeout: 500,
contentType: 'html'
}).success(function(data){
// remove loading image and add content received from php
$('div#content').html(data);
}).error(function(jqXHR, textStatus, errorThrown){
// in case something went wrong, show error
$('div#error_msg').append('Sorry, something went wrong: ' + textStatus + ' (' + errorThrown + ')');
});
});
This will change your page to show the loading animation until the php script returns its data, like:
So you can setup the whole page in plain html, add some loading gifs, call several php scripts and change the content without reloading the page itself.
It is kind of nasty solution to your problem...
But this can work:
You work with those -
ob_start();
//printing done here...
ob_end_flush();
at the beginning you will create your rotating ajax gif...
Then you do all the processing and calculating you want...
At the end of the processing, just echo a small script that does a hide to your gif...
Depends on the exact need, maybe ajax can be more elegant solution.
In response to your conversation with David Constantine below, did you try using ob_flush()?
ob_start();
echo '<img src="pics/loading.gif">';
ob_flush();
// Do your processing here
ob_end_flush();
I think you don't have a problem with flushing your PHP output to the browser, but more likely with getting the browser to start rendering the partial html output. Unfortunately, browser behavior on partial html is browser-specific, so if you want something to work the same in any browser, the AJAX solution suggested in other answers is the better way to go.
But if you don't like that added complexity of a full AJAX solution, you can try to make your html output "nice" in the sense of providing some body output that can be formatted without needing the rest of the html output. This is were your sample code fails: It spends most of its time outputting data into a script tag inside the html header. The browser never even sees the start of the body until your PHP code has practically finished executing. If you first write your complete body, then add the script tag for the data there, you give the browser something to at least try to render whilst waiting for the final script to be completed.
I've found the same issue (albeit not in PHP) discussed here: Stack Overflow question "When do browsers start to render partially transmitted HTML?" In particular, the accepted answer there provides a fairly minimal non-AJAX example to display and hide a placeholder whilst the html file hasn't completely loaded yet.
I know this is an old question, but the answer provided in this page by rpnew is extremely clear and easy to adjust to your project's requirements.
It is a combination of AJAX and PHP.
The HTML page PHPAjax.html which calls the PHP script:
<html>
<head>
<script type="text/javascript">
document.write('<div id="loading">Loading...</div>');
//Ajax Function
function getHTTPObject()
{
var xmlhttp;
if (window.ActiveXObject)
{
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E)
{
xmlhttp = false;
}
}
}
else
{
xmlhttp = false;
}
if (window.XMLHttpRequest)
{
try
{
xmlhttp = new XMLHttpRequest();
}
catch (e)
{
xmlhttp = false;
}
}
return xmlhttp;
}
//HTTP Objects..
var http = getHTTPObject();
//Function which we are calling...
function AjaxFunction()
{
url='PHPScript.php';
http.open("GET",url, true);
http.onreadystatechange = function()
{
if (http.readyState == 4)
{
//Change the text when result comes.....
document.getElementById("content").innerHTML="http. responseText";
}
}
http.send(null);
}
</script>
</head>
<body onload="AjaxFunction()">
</body>
</html>
The Background PHP Script PHPScript.php:
<?php
sleep(10);
echo "I'm from PHP Script";
?>
Save both files in the same directory. From your browser open the HTML file. It will show 'Loading...' for 10 seconds and then you will see the message changing to "I'm from PHP Script".
i give another codes for example
this is my some3.php code:(First file)
:
<head>
<script src="jquery-1.7.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('p').click(function(){
var who = $('input#who').val();
var why = $('input#why').val();
$('#geting').load('file2.php',{who:who,why:why},function(applyData){
if ( applyData == 'YEY . Ye have hi' ){
alert('OKKK data is ok ');
} else{
alert('Nooo We dont have requested output');
}
});
});
});
</script>
</head>
<body>
<p> click </p>
<input type="text" id="who">
<br>
<input type="text" id="why">
<div id="geting" align="center">
</div>
</body>
i this my file2.php:
<?php
echo "1";
echo "2";
if($_REQUEST['who'] == "hi"){
$myVariable = "YEY . Ye have hi";
echo $myVariable;
} else{
$myVariable = "The out put is not Hi";
echo $myVariable;
}
?>
its not work why? becuse we have echo "1" and echo "2"
i want jquery just check $myVariable data not whole php callback ! i think i must use json but i dont know how
Well, assuming that you want to read the value with JQuery off the page you are posting to, you could do this, since you are echo'ing the value out in that page by doing the following: echo $myVariable;
Now this is how I generally read a value off another page with JQuery which is by using JQuery's get() method.
$.get("thepagetoretrievefrom.php", function(retrievedvalue) {
alert("Here's the data you requested: " + retrievedvalue);
if (retrievedvalue == 1) {
//print out something here
alert("The retrieved value was 1.");
}
});
And that should retrieve the value from the PHP page. "thepagetoretrievefrom.php" is the page where you want to retrieve the information from. function(retrievedvalue) just indicates that whatever output you're requesting from the page via JQuery will be put into retrievedvalue. Then, using JQuery, you may decide whether you want to do a new call to another page depending on what the "retrievedvalue" was.
This, however is not the best method to achieve this, since this will print whatever may be in that page, but if you are requesting one specific value from that page, then it shouldn't be an issue.
i would like to ask how can i make a php script which echoes the id of the data stored in a database repeat itself after specific time for example after 2 minutes.i don't want to use a cron job or another scheduler.Just php or javascript implemantation.Thanks in advance..
I've done similar with this script. While the user is on the page, it runs scriptToRun.php every 2 minutes.
function changeFeedAddress() {
$.ajax({
type: 'get',
url: 'scriptToRun.php',
success: function(txt) {
// do something with the new RSS feed ID here
}
});
}
setInterval(changeFeedAddress,120000); // 2 MINUTES
Alternate to #JMC Creative (Self-contained for example's sake):
<?php
// check if the $.post below is calling this script
if (isset($_POST['ajax']))
{
// $data = /*Retrieve the id in the database*/;
// ---vvvv---remove---vvvv---
// Example Data for test purposes
$data = rand(1,9999);
// End Example Data
// ---^^^^---remove---^^^^---
// output the new ID to the page so the $.post can see it
echo $data;
exit; // and stop processing
}
?>
<html>
<head>
<title>Demo Update</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
// assign a timeout for this script
var timeout = 2 * 60000; // 2 minutes
// create a function we can call over and over to fetch the ID
function updateDBValue(){
// call this same script and retrieve an "id from the database" (see top of page)
$.post('<?php echo $_SERVER['PHP_SELF']; ?>',{ajax:true},function(data){
// 'data' now contains the new ID. For example's sake, place the value
// in to an input field (as shown below)
$('#db-value').val(data);
// set a timer to re-call this function again
setTimeout(updateDBValue,timeout);
});
}
// call the function initially
updateDBValue();
});
</script>
</head>
<body style="text-align:center;">
<div style="margin: 0 auto;border:1px solid #000;display:block;width:150px;height:50px;">
DB Value:<br />
<input type="text" id="db-value" style="text-align:center;" />
</div>
</body>
</head>
Why not just do this?
<?php
header('refresh: 600; url=http://www.yourhost.com/yourscript.php');
//script here
?>
If your generating your ID at random from within the script...this will work fine. The page will refresh itself every 10 minutes.
Is there a way to check if JavaScript is enabled with PHP? If so, how?
perhaps a more simple option...
<html>
<head>
<noscript>
This page needs JavaScript activated to work.
<style>div { display:none; }</style>
</noscript>
</head>
<body>
<div>
my content
</div>
</body>
</html>
No, that is not possible, because PHP is a server side language, it does not access the client's browser in any way or form (the client requests from the PHP server).
The client may provide some meta info through HTTP headers, but they don't necessarily tell you whether the user has JavaScript enabled or not and you can't rely on them anyway,
Technically no because as the other answers have said, PHP is strictly server-side, but you could do this...
In the PHP page on the server, output (a lot of HTML has been deleted for brevity)
<html>
<head>
<script type="text/javascript" src="jquery1.4.4.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.get("myPage.php");
});
</script>
</head>
</html>
Then in myPage.php set a session variable to indicate the client supports JS
<?php
session_start();
$_SESSION['js'] = true;
?>
But really, just use <script></script><noscript></noscript> tags, much, much less effort...
//Here is a solution:
//it works perfect
<?php
if(!isset($_SESSION['js'])||$_SESSION['js']==""){
echo "<noscript><meta http-equiv='refresh' content='0;url=/get-javascript-status.php&js=0'> </noscript>";
$js = true;
}elseif(isset($_SESSION['js'])&& $_SESSION['js']=="0"){
$js = false;
$_SESSION['js']="";
}elseif(isset($_SESSION['js'])&& $_SESSION['js']=="1"){
$js = true;
$_SESSION['js']="";
}
if ($js) {
echo 'Javascript is enabled';
} else {
echo 'Javascript is disabled';
}
?>
//And then inside get-javascript-status.php :
$_SESSION['js'] = isset($_GET['js'])&&$_GET['js']=="0" ? "0":"1";
header('location: /');
You can't tell if a browser has JS enabled, but you can tell if the browser supports JS http://php.net/manual/en/function.get-browser.php
$js_capable = get_browser(null, true)=>javascript == 1
Having said this, that's probably not of much use. You should reconsider detecting JS from PHP. There should be no need for it if you use progressive enhancement, meaning that JS only adds functionality to what's already on the page.
<noscript>
<?php if(basename($_SERVER['REQUEST_URI']) != "disable.html"){ ?>
<meta http-equiv="Refresh" content="0;disable.html">
<?php } ?>
</noscript>
Place above code in your header file after title tag and set appropriate like[disable.html] for redirection.
before try you have to disable your browsers javascript...
after then
Try This code :
<html>
<head>
<noscript><meta http-equiv="refresh"content="0; url=script-disabled.html">
</noscript>
<h1>congrats ! Your Browser Have Java Script Enabled </h1>
</head>
</html>
Write something in script-disabled.html
its work
You can try with 2 metod:
setting cookies with JS and detecting them from PHP
creating a form with a hidden field and an empty value; and then assigning some value to it with JS, if the field gets the value – JS is ON, otherwise it’s off. But the form had to be submitted first before PHP can request that hidden field’s value.
if you want detect if JS enable enable setting before the loading of the page you can try this (I don't konw if it works):
<?php
if (isset($_POST['jstest'])) {
$nojs = FALSE;
} else {
// create a hidden form and submit it with javascript
echo '<form name="jsform" id="jsform" method="post" style="display:none">';
echo '<input name="jstest" type="text" value="true" />';
echo '<script language="javascript">';
echo 'document.jsform.submit();';
echo '</script>';
echo '</form>';
// the variable below would be set only if the form wasn't submitted, hence JS is disabled
$nojs = TRUE;
}
if ($nojs){
//JS is OFF, do the PHP stuff
}
?>
there is a fine tutorial on this issue on address http://www.inspirationbit.com/php-js-detection-of-javascript-browser-settings/
Here is a small include I made up that I have on top of my pages to detect if js is enabled. Hope this helps out...
<?php
//Check if we should check for js
if ((!isset($_GET['jsEnabled']) || $_GET['jsEnabled'] == 'true') && !isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
//Check to see if we already found js enabled
if (!isset($_SESSION['javaEnabled'])){
//Check if we were redirected by javascript
if (isset($_GET['jsEnabled'])){
//Check if we have started a session
if(session_id() == '') {
session_start();
}
//Set session variable that we have js enabled
$_SESSION['javaEnabled'] = true;
}
else{
$reqUrl = $_SERVER['REQUEST_URI'];
$paramConnector = (strpos($reqUrl, "?"))? "&" : "?";
echo "
<script type='text/javascript'>
window.location = '" . $reqUrl . $paramConnector . "jsEnabled=true'
</script>
<noscript>
<!-- Redirect to page and tell us that JS is not enabled -->
<meta HTTP-EQUIV='REFRESH' content='0; " . $reqUrl . $paramConnector . "jsEnabled=false'>
</noscript>
";
//Break out and try again to check js
exit;
}
}
}
?>
<html>
<head>
<?php
if(!isset($_REQUEST['JS'])){?>
<noscript>
<meta http-equiv="refresh" content="0; url='<?php echo basename($_SERVER['PHP_SELF']);?>?JS='"/>
</noscript><?php
}
?>
</head>
<body>
<?php
if(isset($_REQUEST['JS'])) echo 'JavaScript is Disabled';
else echo 'JavaScript is Enabled';
?>
</body>
</html>
PHP can't be used to detect whether javascript is enabled or not. Instead use <noscript> to display an alternate message / do something.
To get rid of bots with JS disabled:
<?php
session_start();
#$_SESSION['pagecount']++;
?>
<html>
<head>
<?php
if (!isset($_COOKIE['JSEnabled']) || strlen($_COOKIE['JSEnabled'])!=32 ) {
$js_cookie=md5(md5(#$_SESSION['pagecount']) . $_SERVER['REMOTE_ADDR']);
echo '<script language="javascript">';
echo 'document.cookie="JSEnabled=' . $js_cookie . '"';
echo '</script>';
echo '<meta http-equiv="refresh" content="0;url=http://example.com"/>';
}
?>
<?php
$js=$_COOKIE['JSEnabled'];
if ($js!=md5(md5(#$_SESSION['pagecount']-1) . $_SERVER['REMOTE_ADDR'])) {
$js_cookie=md5(md5(#$_SESSION['pagecount']) . $_SERVER['REMOTE_ADDR']);
echo '<script language="javascript">';
echo 'document.cookie="JSEnabled=' . $js_cookie . '"';
echo '</script>';
echo "</head><body>Sorry, this website needs javascript and cookies enabled.</body></html>";
die();
} else {
$js_cookie=md5(md5(#$_SESSION['pagecount']) . $_SERVER['REMOTE_ADDR']);
echo '<script language="javascript">';
echo 'document.cookie="JSEnabled=' . $js_cookie . '"';
echo '</script>';
}
?>
No one can use for example curl -H "Cookie: JSEnabled=XXXXXXXXXXXXXXXXXX"
because they don't know your algo of computing the hash.
This is the way I check whether javascript and cookies are enabled or not http://asdlog.com/Check_if_cookies_and_javascript_are_enabled
I copy/paste it here
<?
if($_SESSION['JSexe']){ //3rd check js
if($_COOKIE['JS']) setcookie('JS','JS',time()-1);//check on every page load
else header('Location: js.html');
} //2nd so far it's been server-side scripting. Client-side scripting must be executed once to set second cookie.
//Without JSexe, user with cookies and js enabled would be sent to js.html the first page load.
elseif($_COOKIE['PHP']) $_SESSION['JSexe'] = true;
else{ //1st check cookies
if($_GET['cookie']) header('Location: cookies.html');
else{
setcookie('PHP','PHP');
header('Location: '.$_SERVER['REQUEST_URI'].'?cookie=1');
}
}
?>
<head>
<script type="text/javascript">document.cookie = 'JS=JS'</script>
</head>
Recently, I had the following dilemma:
I use a PHP function that generates a QR image related to the current URL, which is very useful for mobile devices. The function works fine, but having my site on a shared hosting, there are some limits for CPU and RAM usage. This function is to heavy and it consumes a lot of CPU time and RAM, so the hosting guys asked me to decrease the usage.
After some tries, I finally reached the idea that I can save some CPU & RAM usage from search engine bots. It is difficult to recognize a bot by browser identification, but all the bots have no JS enabled and that's the main criteria I used to detect if it is a real browser or it is a bot. To explain how significant it is to prevent executing code which will not give anything more for Search Engines (QR, in my case, does not affect search engines), I can say that just Google bot for example makes about 16000 crawls a day on my site.
So I've made this very simple thing which helped a lot:
<script language="javascript"><!--
document.write('<?php echo drawQR($_SERVER["REQUEST_URI"]);?>');
//--></script>
This code uses JS to write a line of PHP code, so this line will be written only when JS is enabled.
Of couse you can use 'noscript' tag if you want to show something when JS is disabled, but this method shows how to execute some PHP only when JS is enabled.
Hope this helps.
Create a cookie using JavaScript and read it using PHP.
With this basic ajax you can separate data that the client see based on javascript or not.
index.php
<!DOCTYPE html>
<html>
<body>
<script>
function jsCheck() {
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "jscheckCon.php", true);
xhttp.send();
}
jsCheck();
</script>
<div id="demo">
no javascript
</div>
</body>
</html>
jscheckCon.php
<?php
echo 'we have javascript!';//you can do that you like to do with js!
?>
Please despite all the people telling you cant check for a client-side scripting technology. If the target technology has http functions, you can do ALWAYS, just write out a verify step. That means literally, the way to check javascript is to run javascript. If javascript is disabled on the browser side it's not possible to check if the client is Javascript capable (like Dillo with it's default config or others)
UPDATED: I've develop this script because i test some of the examples here and seems that everybody does copypasting without any sort of tests. Code is also on the Gist https://gist.github.com/erm3nda/4af114b520c7208f8f3f (updated)
//function to check for session after|before PHP version 5.4.0
function start_session() {
if(version_compare(phpversion(), "5.4.0") != -1){
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
} else {
if(session_id() == '') {
session_start();
}
}
}
// starting the function
start_session();
// create a script to run on the AJAX GET request from :P Javascript enabled browser
echo
'<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.get(document.URL.substring(0, document.URL.length-1) + "?sessionstart=1");
console.log(document.URL.substring(0, document.URL.length-1) + "?sessionstart=1")}
</script>;
// Ajax GET request handle
if ($_REQUEST['sessionstart'] == 1){
$_SESSION['js'] = 1; // save into session variable
} else {
session_destroy(); // force reset the test. otherwise session
}
// If the session variable has not saved by the AJAX call, loads again.
if (!isset($_SESSION['js'])){
header("Refresh: 1"); // thats only for the first load
echo "Javascript is not enabled <br>"; // Return false
} else {
echo "Javascript is enabled <br>"; // Return true
}
This solution do not need more files, just a iteration if you run a Javascript capable browser. The value is passed back to PHP using a GET with a simple variable but anyone can fake the output doing cURL to url + ?sessionstart=1 unless you add more logic to it.
Make your main php page assume jscript is off, and add a <script> to redirect to the jscript-enabled app in the <head>. If the user actually uses your first page, assume jscript is off.
Other option:
If you dont' have to check if JS is enabled at the visitors first view (mainpage) you can set a cookie with js. On the next page you can check with php if the cookie is there...
You can use logic the logic (default/switch) - is this example I printed the variable in php:
PHP:
$js = 'No';
print 'Javascript Enabled: <span id="jsEnabled">'.$js.'</span>';
JS: (in my document ready)
jQuery('#jsEnabled').text('Yes'); or $('#jsEnabled').text('Yes');
You can set a cookie using Javascript and then reload the page using Javascript. Then using PHP you shall check if the cookie is setted, if it is Javascript is enabled!
Its 2013. Simply have your script render the non-js templates inside a body > noscript tag, then inside your CSS keep your main js site container div display: none; After that just put something like <script>$('#container').show();</script> immediately after you close you main #container div and before your noscript tag. (if you're using jquery of course).
Doing it this way will show the HTML for the non-js enabled browsers automatically, and then the js enabled browsers will only see the js site.
If you're worried about over-bloating the page size with too much mark up, then you could do the same but instead leave <div id="content"></div> empty, then with the js code instead of just showing the div use an ajax call to fetch the content for it.
On a side note, I would probably include additional css files for the non-js site within the noscript tag to save on bandwidth.
Since PHP is server side you can't know in PHP whether the client has Javascript enabled unless you use sessions (or some other way to store data across requests) and first send some code to which the client responds.
If you put the following at the start of your PHP file the client is redirected to the same URL with either 'js=0' or 'js=1' appended to the query string, depending on whether they have Javascript enabled or not. Upon receiving the redirected request the script records the result in a session variable and then redirects back to the original URL, i.e. without the appended 'js=0' or 'js=1'.Upon receiving this second redirect the script proceeds as normal, now with the session variable set according to the clients Javascript capability.
If you don't care about how your query string looks in the user's address bar you can skip the second redirect and just set the session variable. While these redirects are taking place the user is shown a short informative message (also something you could skip if you don't care about that).
<?php
session_start();
if (!isset($_SESSION['js']) && !isset($_GET['js'])) {
$url=$_SERVER['SCRIPT_URI'];
$qry='?'.($q=$_SERVER['QUERY_STRING']).($q?'&':'').'js';
die('<!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><title>js check</title>'.
'<script type="text/javascript">window.location.href="'.$url.$qry.'=1";</script>'.
'<noscript><meta http-equiv="refresh" content="0; url='.$url.$qry.'=0" /></noscript>'.
'</head><body>Hold on while we check whether you have Javascript enabled.</body></html>');
} elseif (isset($_GET['js'])) {
$_SESSION['js']=$_GET['js'];
$qry = preg_replace('%&?js=(0|1)$%', '', $_SERVER['QUERY_STRING']);
$url = $_SERVER['SCRIPT_URI'].($qry?'?':'').$qry;
die('<!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><title>js check</title>'.
'<meta http-equiv="refresh" content="0; url='.$url.$qry.'" />'.
'</head><body>Hold on while we check whether you have Javascript enabled.</body></html>');
}
if ($_SESSION['js']) {
//Javascript is enabled
} else {
//Javascript is disabled
}
?>
Yes.
Ensure you have the latest jQuery.js
//javascript
$(function(){
$('#jsEnabled2').html('Yes it is')
})
//php
$js - 'No';
$jscheck = 'Javascript Enabled: ';
$jscheck .= '<span id="jsEnabled">'.$js.'</span>';
print $jscheck;
Working on the same page as before,but now I'm using it as a playground for messing around with jQuery so I can learn it for my'boss.' Unfortunately, I can't get the javascript in this file to execute, let alone give me a warning. All of the PHP and HTML on the page work perfectly, it's just the script that's the issue. What am I doing wrong?
<?php
if( isset($_POST['mushu']) )
{
playAnimation();
clickInc();
}
function playAnimation()
{
echo "<img src='cocktail-kitten.jpg' id='blur'>";
}
function clickInc()
{
$count = glob("click*.txt");
$clicks = file($count[0]);
$clicks[0]+=1;
$fp = fopen($count[0], "w") or die("Can't open file");
fputs($fp, $clicks[0]);
fclose($fp);
echo $clicks[0];
}
?>
<html>
<head>
<title>Adobe Kitten</title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<form action="<?php $_SERVER['PHP_SELF']; ?>"
method="post">
<input type="submit"
value="Let's see what Mushu is up to."
name="mushu">
</form>
<script>
$(document).ready( function()
{
$('#blur').click( function()
{
$(this).blur( function()
{
alert('Handler for .blur() called.');
});
});
});
</script>
</body>
</html>
You're calling playAnimation() before your <html> tag, so your html is malformed. JQuery probably can't find the #blur element because it's not actually inside your web page, much less within the <body>.
Move the if( isset($_POST['mushu'])) ... block of code somewhere after the body tag.
Check FireBug's console, or FireFox' Error Console.
Verify that jquery.js is being included, and check your error console.
Otherwise, a few obvious errors which may or may not contribute to your javascript problems:
You're outputting HTML in playAnimation() before your opening HTML tag
Your form's action attribute is blank - you need <?= or <?php echo
Your script tags should read <script type="text/javascript">
Like Scott said you need to echo the div in the actual body of the page. Also, I think another problem you have is you're calling .blur which is the event when your mouse leaves the image. Since you have functions like animate I think you might actually be looking for .fade http://api.jquery.com/fadeOut/. Try something like:
<script>
$(document).ready( function()
{
$('#blur').click( function()
{
$(this).fadeOut('slow', function()
{
alert('All Done');
});
});
});
</script>