Check if JavaScript is enabled with PHP - php

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;

Related

Javascript Variable to PHP Session Variable and then call it via Ajax for multiple use

I am trying to server device specific layout and also content based on the browser viewport. I have a heavey site and I am not using Media Queries for some specific reasons primarily page load speeds. I need to accomplish this task in this manner only.
OK the situation is like this.....
I have 2 files index.php and viewport.php both residing in a folder http://localhost/test/
To get the browser viewport and convert the values to PHP variable, I am using the following script:
<?php
if (isset($_GET['width'])) {
$layoutType = $_GET['width'];
if ( $layoutType >= 240 && $layoutType <= 600 ) {
$layoutType = 'mobile';
} else if ($layoutType >= 601 && $layoutType <= 900 ) {
$layoutType = 'tablet';
} else {
$layoutType = 'desktop';
}
} else {
echo "<script language='javascript'>\n";
echo " location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
. "&width=\" + document.documentElement.clientWidth;\n";
echo "</script>\n";
exit();
}
?>
My questions:
Q1. How can I store $layoutType as a Session Variable so that I can use it multiple times? What would be the correct syntax for it?
Q2. How can I run the file viewport.php from index.php and get only the $layoutType and no other data. This is because by using the <?php require_once ?> method I am getting my URL like this:http://localhost/test/index.php?&width=1600. I want the URL to display like http://localhost/test/ only. What will be the correct syntax I need to use in my index.php file?
Q3. Skipping the Ajax part is there a way to get rid of index.php?&width=1600 from the URL? I tried via .htaccess but it gives me the error saying "The page is not redirecting properly"
Please note: I do not intend to use and JavaScript Libraries like jQuery and MooTools as this is the only JavaScript function in my entire website and it wont make sense to load an entire library for it.
Firstly, PHP happens server side, so once the page loads the only way to use PHP again (without loading a page) is to make an ajax call, presumably to another php page that performs a certain function and returns a value.
If you want to store a value as a session variable so that it can be used continuously, you can do the following:
when they first land on your site have php check for the existence of a session and if it does not exist, call a Javascript function to get the layoutWidth and make an ajax call to a php page that will store it as a session variable and then reload the page and include the correct layout file.
I would probably not use this method and actually look at ways to do this with JavaScript/JQuery instead. But this is how you have asked to do it.
For your example, I have not used JQuery at all, but I would as the include is only about 19kb or so and it makes life SO much easier.
Example:
index.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<?php
if (empty($_SESSION['layoutWidth'])) {
echo '<script type="text/javascript"> var session=false; var layoutWidth;</script>';
} else {
echo '<script type="text/javascript"> var session=true; var layoutWidth=' . $_SESSION['layoutWidth'] . ';</script>';
}
?>
<script type="text/javascript" src="js/viewport.js"></script>
</head>
<body>
<?php
if (!empty($_SESSION['layoutWidth'])) {
$layoutWidth = $_SESSION['layoutWidth'];
if ( $layoutWidth >= 240 && $layoutWidth <= 900 ) {
include('layout1.php');
} else if ($layoutWidth > 900 && $layoutWidth <= 1200 ) {
include('layout2.php');
} else {
include('layout3.php');
}
}
?>
</body>
</html>
js/viewport.js
// JavaScript Document
window.onload = function() {
// if there is no session (session = false)
if (!session) {
// call function to get the screen size
getScreenWidth();
// make ajax call to php page to set the session variable
setSession();
}
}
function getScreenWidth() {
layoutWidth = screen.width;
}
function setSession() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// Reload the page
window.location.reload();
}
}
xmlhttp.open("POST","set_session.php?layoutWidth=" + layoutWidth,true);
xmlhttp.send();
}
your php file to set the session the parameter is passed from your ajax call:
set_session.php
<?php
session_start();
// you can check if it is already set if you like otherwise:
$_SESSION['layoutWidth'] = $_REQUEST['layoutWidth'];
?>
layout1.php
<?php
echo '<div>This is layout1.php</div>';
echo '<div>Your screen width is: ' . $_SESSION['layoutWidth'] . '</div>';
?>
layout2.php
<?php
echo '<div>This is layout2.php</div>';
echo '<div>Your screen width is: ' . $_SESSION['layoutWidth'] . '</div>';
?>
layout3.php
<?php
echo '<div>This is layout3.php</div>';
echo '<div>Your screen width is: ' . $_SESSION['layoutWidth'] . '</div>';
?>
This method means you dont have to pass parameters around in your URL. it will all be hidden.
Q1) $_SESSION['layoutType']=$layoutType;
Q2&Q3 ) I think you're making it too complex for yourself. Best way to achive what you want with restrictions that you have is to combine the power of cookie and session, you'll have a faster and neater code. So what you can do is check if the session layoutType is set, if not, inject a javascript code that'll get the layoutType for you and puts it in a cookie, and next time you include viewport.php in a a page, it'll check to see if the cookie is set and will transfer it to session for future use, so you can change viewport.php to this :
<?php
if(isset($_SESSION['layoutType'])){
//write the code for when session is set here
}elseif(isset($_COOKIE["layoutType "])){
$_SESSION['layoutType']=$_COOKIE["layoutType "];
}else{
$script = "<script language='javascript'>function SetCookie(cookieName,cookieValue) { var today = new Date(), expire = new Date(), nDays=1;expire.setTime(today.getTime() + 3600000*24*nDays);document.cookie = cookieName+'='+escape(cookieValue)+ ';expires='+expire.toGMTString();SetCookie('layoutType',document.documentElement.clientWidth}";
echo $script;
}
?>

PHP output value of JS function

<html>
<script type="text/javascript">
function show_alert()
{
alert("I am an alert box!");
}
</script>
<body>
<?php
$x = 8;
if($x ==10){
echo "Hi";
}
else{
echo 'show_alert()';
}
?>
</body>
</html>
How do I get the echo to output the value of show_alert() ?
Change
echo 'show_alert()';
to
echo '<script>show_alert()</script>';
so that the browser knows to treat show_alert() as a function call and not regular HTML text.
You need to wrap it in a script tag:
if($x ==10){
echo "Hi";
}
else{
echo '<script type="text/javascript">show_alert();</script>';
}
Note, this will not wait until the page has finished loading to call show_alert(). The alert will be displayed as soon as the browser reaches this point in the page rendering, which may be otherwise incomplete behind the alert box. If you want it to wait until the whole page is loaded, place the condition to be called in <body onload>
<body <?php if ($x != 10) {echo 'onload="show_alert();"';} ?>>
<?php
if ($x == 10)
{
echo "Hi!";
}
?>
</body>
If you mean call showAlert() when the browser renders/evaluates that line:
echo '<script type="text/javascript">show_alert();</script>';
If you mean get the value of showAlert() in PHP, you can't - PHP is a server-side language.
This:
echo 'show_alert()';
will simply print "showAlert()" on the page, unless you have already opened a <script> tag.
I think you may be confused about the difference between client side and server side code.
HOWEVER, if you are using the two correctly, and you want to make it appear:
echo '<script type="text/javascript">show_alert();</script>';
It depends largely upon when you want the show_alert() javascript function to be called. Guessing by the PHP code that you're using, I am going to assume that you want the javascript function to be called as soon as the page loads, in which case you might want to use PHP before the body loads, and add an "onload" attribute event handler to your body tag:
if($x ==10){
echo '<body>';
}
else{
echo '<body onload="show_alert();">';
}

PHP Beginner: How to pass PHP variable from one PHP code segment to another?

I have index.php which uploads a file to server and sets several PHP variables (like $target_folder_and_file_name).
index.php also has the following line (it was originally index.html):
<script language="JavaScript" src="main.js.php"></script>
After index.php returned to the browser, the browsers asks for main.js.php from the server (right?).
Can I access somehow $target_folder_and_file_name from the PHP code in main.js.php ?
#TheJacobTaylor is right, sessions are the best, but if you dont want to keep "$target_folder_and_file_name" secret, you can also use: (index.php)
<script type="text/javascript" src="main.js.php<?php echo '?target='.urlencode($target_folder_and_file_name); ?>"></script>
and in your main.js.php
<?php
$target_folder_and_file_name = htmlspecialchars(urldecode($_GET['target']));
...
?>
with SESSIONS this would look something like this:
in your index.php
<?php
session_start();
$_SESSION['target'] = $target_folder_and_file_name;
...
echo '<script type="text/javascript" src="main.js.php"></script>';
...
?>
and in your main.js.php:
<?php
session_start();
if( isset( $_SESSION['target'] ) )
{
$target_folder_and_file_name = $_SESSION['target'];
}
else
{
$target_folder_and_file_name = FALSE;
}
...
?>
The easiest way to accomplish this is to put the information in the PHP session. Sessions last beyond one round trip. You can also add your information to a database, cache, external store, or to the URL of the javascript. As I mentioned, sessions are the easiest.
http://www.php.net/manual/en/session.examples.basic.php
<?php
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
?>
If you don't want everything to be session dependent, you could pass a parameter to the script when fetching it.
index.php
<?
//get filename in whatever manner you currently do
?>
<script language="JavaScript" src="main.js.php?t=<?= urlencode($filename); ?>"></script>
main.js.php
<?php
$filename = urldecode($_GET['t']);
//do whatever you need to with the filename
?>

Run a JavaScript function from a php if statement

I am using PHP conditions and want to know if I can run a JavaScript function without some one have to click on it using JavaScript:
if($value == 1)
{
JavaScript to run the function
}
How would I do that?
First of all keep in mind that your PHP code is evaluated on the server, while JavaScript runs in the browser on the client-side. These evaluations happen in different places, at different times. Therefore you cannot call a JavaScript function from PHP.
However with PHP you can render HTML and JavaScript code such that it is only rendered when your PHP condition is true. Maybe you may want to try something like this:
if($value == 1) {
echo "<script>";
echo "alert('This is an alert from JavaScript!');";
echo "</script>";
}
Javascript is client-side code, PHP is server-side, so you cannot execute javascript while building the page in PHP.
To execute javascript on the client-side as soon as the page has loaded, one way is to use the body onload handler to call your function:
<?php
echo '<script type="text/javascript">';
echo 'function myFunction(){ /* do_something_in_javascript */ };';
echo '</script>';
if ($value == 1) {
echo '<BODY onLoad="myFunction()">';
}
?>
Better yet, if you can afford the bandwidth, use jQuery and use $(document).ready():
<?php
if ($value == 1) {
echo '<script type="text/javascript">';
echo '$(document).ready(function(){ /* do_something_in_javascript */ });';
echo '</script>';
}
?>
I've found that you cannot do something like this in IE and other browsers. It does work in Firefox though. You have to echo out each line as posted in the other method.
<?php
if(somecondition)
{
?>
<script>
Some javascript code
</script>
<?php
}
?>
I know this thread is old but I just came across it and wanted to add my technique.
You can also echo the php variable into JavaScript and do something based on its value. I use it to place database values into js so the user can do math on the page with them
<script>
var jsvar = <?php echo $phpvar ;?>
if (jsvar = x){ do something...}
</script>
After some tinkering, I was able to get the following to work within a .php file.
This doesn't work in a .html file though.
<?php
if (isset($_SESSION['loggedin'])) {$login='t';}else{$login='f';}
?>
<script>
var login = "<?php echo $login ?>";
console.log(login);
if (login == 'f'){ .. do something..}

PHP publishing JavaScript

I have a PHP script that publishes customised JavaScript based on the parameter, with header type as text/javascript. This PHP URL is included in the src of a <script> tag. However, there seem to be an issue, because the script seems to be nonfunctional. As in, I have an alert inside the script, which should be executed immediately after inclusion, but it's not happening. Where am I going wrong?
Server Side PHP
<?php
//Exploding the path after the file widget to get user details
$expl = explode("/",$_SERVER['PATH_INFO']);
$c=count($expl);
//Handling the cases as widget/a widget//a etc
switch($c) {
case 2:
if(empty($expl[0]) && !(empty($expl[1]))) pumpValid();
else pumpInvalid();
break;
case 3:
if(empty($expl[2]) && !(empty($expl[1])) && empty($expl[0])) pumpValid();
else pumpInvalid();
break;
default:
pumpInvalid();
break;
}
function pumpValid() {
global $expl;
//Checking for a matching account in the urllist
include('embedUrl/urllist.php');
if(isset($customerList[$expl[1]])) {
header("Content-Type: text/javascript");
//Setting the host path for fetching the JS files later. As in stage or vidteq.com
echo "alert('h');";
echo 'var _serverHostUrl="http://'.$_SERVER["SERVER_NAME"].eregi_replace('widget.*','',$_SERVER["REQUEST_URI"]).'";';
}
else
pumpInvalid();
}
function pumpInvalid() {
//Should redirect to error/home page
echo "Are You Nuts";
}
?>
function init() {
alert('hi');
addJSinHead('jquery-1.3.2.min.js');
addJSinHead('OpenLayers.js');
addJSinHead('json2.js');
addJSinHead('dom-drag.js');
addJSinHead('globals.js');
}
function addJSinHead(fileName) {
var head=document.getElementsByTagName('head');
var new=document.createElement('scrpit');
new.src=_serverHostUrl+'/js'+fileName;
new.type='text/javascript';
head.appendChild(new);
}
init();
Inclusion in client side HTML
<script src='http://rak/cvs/widget/cis/' type='text/javascript'></script>
Is the alert that should be executed inside of a function block? If so then you first need to execute the actual function.
Also try copying and pasting the javascript src url directly into the browser's url bar.
If the above didn't help, some code to analyze would be useful.
You can check with Firebug to see if the output of the script is what you expect and that the headers are being sent as you expect.
You'll need to provide some code for further help.
EDIT:
I don't see anywhere that you output a header in php:
header('Content-Type: text/javascript');
EDIT2:
It looks like you're calling the pumpValid function before it's defined.

Categories