Why wont this code detect if javascript is blocked? - php

Okay, I have created a new question to clarify my old one, which is available here: Check if certain text was outputted to the screen PHP
Currently I have this code:
<?php
echo "
<noscript><h2>! JavaScript is not enabled!!! Features will not work !</h2></noscript>
<script type=\"text/javascript\">
document.cookie= \"jsEnabled=true\";
</script>
";
if (isset($_COOKIE['jsEnabled'])) {
// Javascript is enabled!
}
else {
die("JavaScript is not enabled!");
}
?>
I am not sure why this wont work! It should kill the PHP if JS is disabled! Thanks!

JavaScript processes after PHP has fully given out the page, not before, and not in symbiosis. As such, your PHP call will only work for the second call to the page, not the first.
That is, if you accept cookies in the first place.
If you want to prevent users without JS from using the interface on a page, consider generating the interface in pure JS instead. More reliable.

Related

What is the proper way to execute JS?

Is it possible to use JS/JQuery from an external file? If so, what is the best practice?
What is the best practice to call a JQuery function inside a PHP or HTML page?
Here is file.php
echo "<table..";
echo "some code...";
echo "</table>":
<script type="javascript">
$('table').hide().fadeIn(700);
</script>
or:
echo '<script type="javascript">';
echo '$('#foo').toggle("slow");';
echo '</script>';
So, besides a best practice. is any of this possible? I can't seem to make it work from external file or directly.
also from external.js
$(document).ready(function(){ $('table').css({ // code here ... }); });
You can certainly echo jquery (or any html code) directly from PHP
echo '<script type="javascript">
$(\'#foo\').toggle("slow");
</script>';
Your issue in that one was the un-escaped quotes around #foo
I'm not really sure what you meant in the first part of your question, but since you have php I would use this option rather than trying to add jquery into an html file from another javascript file (if that's what you were trying to do)
Both internal and external javascript/jquery code should work.
Make sure you jquery script tag was include in you header/body
If external, make sure to include the external.js script tag after the jquery script tag
Make sure the document was ready first ( $(document).ready() ), and check again the selector either they are exist or not.
For more clean code, no need to echo every single line html code. Just close the php ( ?> ) and write the html as usual.
Please provide as much information as you can so that we know exactly what's the problem was.

Use of PHP code inside Javascript code

Since I know many consider the use of PHP code inside Javascript code bad practice, I wonder how to execute a javascript function provided that a certain PHP variable has a certain value.
This is the way I currently write the code:
<script type="text/javascript">
function execute_this() {
some code;
}
<?php
if(!empty($_SESSION['authorized'])) :
?>
execute_this();
<?php
endif;
?>
</script>
Any ideas how to avoid using PHP inside Javascript in this particular example?
If you don't want to include any PHP code inside the javascript code but want to know the value of a php variable, you have to integrate a communication between the server side (PHP) and the client (JS)
For example you could use a ajax request to call a small php snippet that provides the value in its reply. With that value you can go on in you java script code.
In my opinion you should decide if its worth the effort.
Edit:
In regard to the edited question: If it is important that the JS function is never ever called if the PHP session value isn't present I would stay with the PHP code but would do it that way:
<?php
if(!empty($_SESSION['authorized'])) :
?>
<script type="text/javascript">
function execute_this() {
some code;
}
execute_this();
</script>
<?php
endif;
?>
If you evaluate the value of the session variable in javascript, you have to make sure that nothing bad happens to your code if the provided value was manipulated.
It's a matter of code style. The time your project grows, you will find it increasingly difficult to maintain it or to extend its functionality. A better solution would be to initialize all needed variables in the beginning of the file and to externalize the main JavaScript functionality.
Example PHP:
<script type="text/javascript">
MYCONFIG = {
authorized: '<?php echo $_SESSION['authorized']; ?>',
foo: 'something else'
}
$(document).trigger('init'); // fire init event, you can call it as you like
</script>
Example JS with jQuery (note that i use the custom trigger 'init', you can call it however you like):
$(document).on('init', function() {
function execute_this() {
document.write(MYCONFIG.foo);
}
if(MYCONFIG.authorized) {
execute_this();
}
})
This should be in an external JS file and does not need any PHP tags.
You have to store the php variables somewhere in the html code and then access it.
For example:
<input type="hidden" id="hidval" value=<?php echo $_SESSION['authorized'] ?>/>
then in your js:
var somevar=document.getElementById(hidval).value;
if(somevar==what you want){
execute_this();
}
I think you have some basic design issues, and we are only seeing the tip of the iceberg and can't fully help you.
There is nothing inherently wrong with calling a php function this way, but you have several issues:
1) you cannot separate your js file & allow for caching or cdn
2) while MVC is certainly not "mandatory", it is definitely a good idea to try to separate this type of logic from your "view" - your rendered output
3) I suspect elsewhere you have a massive security hole - if you are setting certain parameters based on whether or not they are "authorized" in their session, this means you are most likely sending back info on which to base a permissions decision in your php code somewhere. Never do that from the page - all data should be "neutral" on the page itself, because you have no control over it.
Give this a read if you are not clear why I say that: http://www.codebyjeff.com/blog/2012/12/web-form-security-avoiding-common-mistakes
There are three possible ways to do it.
Use hidden field and add necessary variable value inside each fields and get those using jQuery.
User jQuery Session plugin and access php session variable.
make a ajax call to php and get response in json format and access response.

Using PHP in Javascript

I just found out that PHP can be used in Javascript like this:
<script>
function seeTime() {
alert("<?php echo time(); ?>");
}
</script>
<button onclick="seeTime();">Click Me</button>
The above code will popup an alert message with the Unix timestamp every time the button "Click Me" is clicked. But the problem is, the time remains the same everytime you click the button until the page is reloaded.
I know AJAX is the solution but is there any other way I can update the data inside the javascript code/file without using any external php file to fetch data from it with AJAX ?
I know AJAX is the solution but is there any other way I can update the data inside the javascript code/file without using any external php file to fetch data from it with AJAX ?
Yes, just don't use PHP at all:
function seeTime() {
alert(Math.floor(new Date().getTime()/1000));
}
You are getting confused between PHP and JavaScript. PHP is not being "used" in JavaScript. PHP runs on the server and generates the page, which is then sent to the browser.
<?php echo time(); ?> is replaced with the current timestamp, then sent to the browser which runs the JavaScript.
As far as I know it's impossible, PHP code is compiled server-side, so all you return from a php compilation are static value, you must use AJAX to refresh the time value.
You could set the time with JS if you wish.

Calling a JavaScript function from PHP

I have a php script that is a bit of a mess and after a form entry, I need to get an address, and display it on a google map. The html and php is crammed into the same script so I essentially need to call the JavaScript as the PHP is happening. Is there a way to do this?
Thanks,
Alex
You can POST your from to a different frame (or iframe), so your page would not reload. The response of your PHP file which comes back to that frame can contain JavaScript code, which will be executed. Something like:
echo('<script type="text/javascript"> alert("Executed on client side"); </script>');
No, PHP executed by the server and returns the full response to the browser. JavaScript in the page is then executed by the client.
You can't call Javascript functions from PHP. You can set the Javascript to run when the page loads instead.
What you want is something like this:
<script type="text/javascript"></script>
var userAddress = "<?php echo $_POST['address']; ?>";
doSomethingWithAddress(userAddress);
</script>
If that code is on the page which you are POSTing the address to, it would take the address from the user, and write it into a javascript tag. The PHP will get executed first on the server, before building the HTML document. This new document has the variable available to the javascript.
I don't know how you would go about doing that, but this seems like a good place to start looking:
http://code.google.com/intl/en/

Javascript window.open Calling Twice

I'm using this code in a php conditional if/else statement to open a new window.
echo("<script type=\"text/javascript\">
<!--
window.open(\"http://www.example.com/index.php?$var\");
//-->
</script>
");
It's opening 2 windows instead of one, but only on my live site (on a dedicated server) and not on the test site (shared server).
EDIT: From zebediah49's suggestion, I appended a random int variable after the new window url. It changes the variable with each new window instance, so I assume that means that it runs the conditional twice. I probably should mention that it's using Joomla and a 3rd-party community app, JomSocial.
Alright, as I was editing this and after ~5min of the same window being open, it opened a brand new instance of the window.open window. So obviously it automatically refreshes once as soon as it lands. I'll have to pry into that. Still any suggestions are welcome.
Thank you for your tips regarding language and best practices.
Since it's performing differently, there is either something different in the code between the two, or something different in the environment.
To test to be very, very, very sure that it is opening that specific url twice, have it append a random variable to the end of the URL:
$rando = rand();
window.open(\"http://www.example.com/index.php?$var&r=$rando\");
Also, if you want to avoid having quote issues, I would advise using HEREDOCs:
echo(<<<EOF<script type="text/javascript">
<!--
window.open("http://www.example.com/index.php?$var");
//-->
</script>
EOF
);
or with a variable
$content = <<<EOF<script type="text/javascript">
<!--
window.open("http://www.example.com/index.php?$var");
//-->
</script>
EOF;
echo($content);
I can't think of a good reason why that single line of JS would happen twice though, which is why I would want to see with the random var, such that there is no possible way other than that it could get opened twice. (If it was somewhere else in the file, it would not have the &r=...; if it was the same thing getting executed twice, &r=... will be different between the two)
First of all.
Why those in your Javascript ?
Those are XML Comment.
You need to use /* ... */ or //
Did you mean
//<![CDATA[
...code...
//]]>
If this is the only call to window.open() your http://www.example.com/index.php might also make another window.open() call
Could it be that the PHP echo is being triggered twice?

Categories