How would I check if certain text was outputted to the screen using PHP? For example, I have this code:
<html>
<body>
<noscript>
error: no js
<noscript>
<?php
//detect if the HTML printed out "error: no js"
?>
</body>
</html>
I want to detect if HTML printed out the specified <noscript> message. Is this possible to do with PHP, or on a PHP page? Is there a better way to stop any scripts if JavaScript is disabled, or if certain output was outputted?
I would especially like to do this because then I can pass certain output if certain conditions were met, and have the PHP act according to the output.Thanks!
The only thing I can think of is setting a cookie:
<script type="text/javascript">
document.cookie = "jsEnabled=true";
</script>
Then, you can do a simple check in PHP:
<?php
if (isset($_COOKIE['jsEnabled'])) {
// Javascript is enabled!
} else {
// Javascript is not enabled!
}
Related
I have a page with php and other stuff in the code. What I need to do is a way to check with php if there is javascript enabled in the browser.
This way, the whole page source will be prevented to be loaded, instead of using that only prevents the page from loading, but allows the source code.
PHP is a server-side language. There is no way to do this with PHP since it is run on the server, and then the result is sent to the client. The server has no knowledge of whether the client has JavaScript enabled or not.
If you don't want to show the code in your .html file when JS is disabled, then you don't have to use PHP. You could put the essential stuff in the .html file and load the rest in with JavaScript. If JavaScript is disabled, the rest of the stuff never gets loaded in the first place. (This is called progressive enhancement.)
This example will use the <noscript></noscript> tag inside an echo directive.
<?php
echo "<noscript>You need JS enabled to view the text on this page.</noscript>";
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
document.write("<h1>Heading Text</h1>");
document.write("<p>This message appeared because you have JS enabled.</p>");
</script>
</body>
</html>
You could make JavaScript fire a request to a page, setting a session variable enabling access to the website, then reload the page. This is by no means secure.
In all files except enable.php (could be done via an include/etc) before anything is echoed.
...
if (!isset($_SESSION['enabled']) { ?>
<!doctype html>
<html>
<head>
...
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', '/enable.php', false);
xhr.send();
window.location.reload();
</script>
</head>
<body></body>
</html>
<?php die();
}
....
In enable.php, you would then do
$_SESSION['enabled'] = 1;
enable.php would only need to be hit once-per-session and if JavaScript was disabled afterwards, or it was hit manually by pointing the browser there, your server will not know the difference. The assumption is the client must have JavaScript enabled for this session if the page was reached this session.
I am loading some jquery within a Wordpress page, the jquery works as I want it to but now I need to have that jquery only fire if a php variable exists.
In php I would just do:
if( $foo ) {
do this;
}
In Wordpress I am enqueuing the a file bla.js that contains this:
jQuery(document).ready(function($){
$('#someID.some-class > a').append('<div class="caption"></div>');
$(".caption").text("Add this text");
});
I am confused as how to add the php check if $foo exits. There seems to be several approaches but all I end up doing is producing an unexpected token error.
Javascript exists only on the clients computer in their browser; PHP only exists on the server, far away from their browser, so your JS can't just use the PHP variable. You can do it two ways:
Only include the JS if the variable is true:
<?php if ($foo) : ?>
jQuery(document).ready(function($){
$('#someID.some-class > a').append('<div class="caption"></div>');
$(".caption").text("Add this text");
});
<?php endif; ?>
Or set a JS variable from the PHP variable:
jQuery(document).ready(function($){
var foo = <?php echo $foo; ?>;
if (foo) {
$('#someID.some-class > a').append('<div class="caption"></div>');
$(".caption").text("Add this text");
}
});
Note that in either case, the page is "created" on the server with PHP. Once it's displayed in the browser, you can't use PHP variables. If you need to call another PHP page to check some additional stuff, look at Ajax.
So php is a server side language, javascript is a front end language. So basically php runs then javascript runs...so basically if $foo exists output the jquery you want to run and it will display on the front end. If it doesn't exists output different jquery that you want to run....here is as simple example...
<!-- JS -->
var foo = <?php echo $foo; ?>
if (foo == 'test'){
} else {
}
// More PHP based
if ($foo == "test"){ ?>
javascript function() <!-- Note how I closed php -->
<? } else { ?>
javascript function2()
<? } ?>
PHP and jQuery (which is a framework written in Javascript) run in entirely different scopes.
PHP is executed on the server and the generated result is the HTML page (which will likely include some Javascript code).
That resulting page is then delivered from the server to the browser and when the browser renders it, the jQuery/Javascript will execute.
The key part is that the PHP code is actually generating the HTML and Javascript code.
So, if you'd like to run some jQuery code only if a PHP variable exists:
<?php
if( $foo ) {
?>
<script type="text/javascript"> /* Some jQuery stuff here */ </script>
<?php
} else {
?>
As an example, I generate this text in the "else" condition.
<?php
}
?>
If $foo is true then PHP will generate this HTML:
<script type="text/javascript"> /* Some jQuery stuff here */ </script>
otherwise, PHP will generate this:
As an example, I generate this text in the "else" condition.
Keep in mind that once PHP has delivered the page to the browser, it is no longer running, and the generated result will be "permanent". At that point, the page is loaded into the browser DOM (document object model) and the DOM can only be changed through Javascript.
Put the Javascript inside the PHP conditional.
<script type="text/javascript>
...
<?php
if ($foo) : ?>
jQuery(document).ready(function($){
$('#someID.some-class > a').append('<div class="caption"></div>');
$(".caption").text("Add this text");
});
<?php endif ?>
...
</script>
Usually i just create a hidden input like so:
<input type='hidden' id='some_id' value='the_value'>
Note that I don't add the name attribute so it doesn't get posted (if it happens to be in a form).
Then you can access it with jQuery by its id.
if($('#some_id').val() == what_you_want)
{
do_something();
}
I have a PHP variable thePHPvar in a file DoStuff.php in my website.
thePHPvar gets set to a string.
Then after that the code in DoStuff.php does
header("Location: http://localhost/theWebite/index.php");
I need 2 things in my onLoad handler inside the body tag of index.php:
<body onload="doLoad()">
My doLoad() function must be able to do 2 things:
1) get access to 'thePHPvar' variable, which again is a string (a path name) that was set in PHP code in DoStuff.php just prior to the header() redirect.
2) also, doLoad() must be able to detect when 'thePHPvar' is empty so it can avoid trying to use
'thePHPvar' and skip the logic that uses that string.
I'm new to php and javascript and have impressed myself with getting working what I have now,
but I've spent 1/2 day on this, read lots of similar issues on SO.
I have to be able to redirect back to index.php, grab this string variable and if it's been set (not null), execute some javascript code.
Right now this is all my onLoad() does, and hey -- it works. But not the right way, yet.
<head>
<script type="text/javascript">
function doLoad()
{
alert("Page is loaded");
}
</script>
</head>
Without introducing a bunch of new stuff I'd have to learn like Ajax etc., how can I get this done in javascript, html, php and what I have here?
You can use a session variable as Jorge said, if this myPHPVar is specific to a user. Otherwise, pass the variable in your header redirect:
header("Location: http://localhost/theWebite/index.php?myVar=" . $myPHPVar);
As you're a beginner, you probably won't want to use JSON to get the variable from PHP to Javascript, but do look it up if you ever have to pass a lot of data to Javascript code.
<script>
var myPHPVar="<?php echo $_GET['myVar']; ?>";
</script>
If the user has any influence over that PHP variable, be sure to sanitise the variable against XSS attacks.
To check if myPHPVar is empty in your doLoad method, just use if (!myPHPVar) { .... }
Would it be acceptable to include $thePHPvar in the querystring of the page you're redirecting to?
header("Location: http://localhost/theWebite/index.php?$thePHPvar");
and then in javascript you can just look for document.location.search, eg
<head>
<script type="text/javascript">
function doLoad()
{
alert('thePHPvar is ' + document.location.search.substring(1));
}
</script>
</head>
I suggest you set a session with the variable you want and then use the session to fetch the variable on the next page.
After initializing the session on the page you redirected to, you'd use it on the javascript like this:
var variableFromPhp = "<?php echo $the_variable ;?>";
alert(variableFromPhp);
You could pass it as a GET param, but that's generally less secure since it's tamperable.
Previous page:
Then on the page you redirect to:
<head>
<?php
session_start();
$the_var=(isset($_SESSION['a_var']) && $_SESSION['a_var'])) ?
$_SESSION['a_var']
: false;
?>
<script type="text/javascript">
function doLoad(the_var)
{
if(the_var){ alert("Page is loaded"); }
}
window.onload=function(){ doLoad(<?php echo var_export($the_var,true);?>); }
</script>
</head>
I want to trigger javascript alert using PHP.
Is it possible
I want to use it in head section, for displaying it at load time.
<head>
<?php
$valid="valid";
if(!isset($valid))
echo "<script type=\"text/javascript\"> alert('Hi');</script>";
?>
</head>
EDIT
i want to display javascript alert() at load time after checking existance of session
Of course this is possible.
All you are doing is outputting JavaScript, it's all the same thing.
The only issue is that you are nesting <script> tags, which is an HTML error, so get rid of the tags in the echo string.
<script type="text/javascript">
<?php
$valid="valid";
if(!isset($valid))
echo "alert('Hi');";
?>
</script>
By the way, as i'm sure you already know, this specific code will ALWAYS echo the "alert('Hi');"
i need to have some php code inside javascript
<script ...>
<?php
echo " ... ";
?>
</script>
but this doesnt work. how can u implement php inside javascript that is in a own file javascript.php?
That doesn't do what you probably think it does. It'll work, but the PHP gets run once, when the page is loaded, not every time the JavaScript function is called.
Just for clarification, this is what will happen
index.php
<script type="text/javascript">
<?php echo "alert('hello!');"; ?>
</script>
output html in browser
<script type="text/javascript">
alert('hello!');
</script>
If that is what you want to do, then you can output all the javascript you like. What you cannot do is execute PHP code in the user's browser.
your can use php to dynamically generate javascript code, but you cannot execute php client side. If you need to execute php you will need to postback or use AJAX
There seems to be a good bit of misunderstanding of the question... Here is what you want to do to generate JS from PHP on the server:
file javascript.js.php
<?php
header('Content-Type: text/javascript');
?>
// javascript code here
function PrintTime()
{
alert("The time is " + <?php echo json_encode(time()); ?>);
}
Now, include it on the HTML page using normal script tags:
<script type="text/javascript" src="/url/to/javascript.js.php"></script>
The server will process the PHP file, and return javascript from it.
You can't run PHP inside a javascript file. Primarily because PHP runs server side and is processed before the client is sent any actual http info. JavaScript is processed by the browser on the client side and is sent as text.
It looks like you want to pass some kind of dynamic info to the JavaScript. You can do this by passing a variable like this:
<?php $variable="its me"; ?>
<script>
alert('<?php print($variable)?>')
</script>
The output passed to the client is:
<script>
alert('its me')
</script>
What are you trying to accomplish and maybe we can help you come up with a better solution?