Javascript isn't parsing PHP [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Parse a JavaScript file through PHP
PHP no longer working inside javascript
I am running .php files on my localhost and yesterday they worked and today they have errors, but I haven't changed the code. Here is a test file that has the same error as my longer actual code:
<html>
<script type="text/javascript">
<? $message = "Hello"; ?>
</script>
<? echo $message; ?>
</html>
I know this is a silly way to write Hello, but it demonstrates what error I am getting when I try to use php inside javascript. It was working perfectly fine yesterday and none of the code has changed. When I run this, it says "unexpected token <" on line 3. I think it is a problem with apache/php/mysql but I'm lost trying to fix it. Any suggestions would be great. Thanks.

I guess, you have short tags disabled. You need to enable PHP short tags in order for this to work. Check if this works:
<html>
<script type="text/javascript">
<?php $message = "Hello"; ?>
</script>
<?php echo $message; ?>
</html>
And in my opinion, I have no clue, why you open a <script> tag and declare a PHP Server Side statement there. You know what? It doesn't output anything. Anyways, the output of the above code would be this:
<html>
<script type="text/javascript">
</script>
Hello
</html>
So there's no need of having the <script> tag as it is client side and PHP doesn't care about that. You can just give it anywhere you want, and as long as they are inside <?php ?> tags, they won't be parsed by the browser. :)
If you are doing this in your own system, to enable short tags in PHP, do the following:
Locate the php.ini file.
Find this:
short_open_tag = Off
Change it to:
short_open_tag = On
From the manual:
short_open_tag: Tells PHP whether the short form (<? ?>) of PHP's open tag should be allowed. If you want to use PHP in combination with XML, you can disable this option in order to use <?xml ?> inline. Otherwise, you can print it with PHP, for example: <?php echo '<?xml version="1.0"?>'; ?>. Also, if disabled, you must use the long form of the PHP open tag (<?php ?>).

its not valid javascript.
after the php is run you end up with a dom looking like <script type="text/javascript"></script> because you're not writing anything.
try:
<script>
var hello = "<?php echo 'hello' ?>"
</script>
<script type="text/javascript">
document.writeln(hello)
</script>

The script as it is works fine for me. Is the code posted in your question complete?
The only way I was able to reproduce the problem was with the following code:
<?php
<html>
<script type="text/javascript">
<? $message = "Hello"; ?>
</script>
<? echo $message; ?>
</html>
?>
Correct me if I'm wrong, but I'm assuming the code you posted is in a *.php file and in between php tags.. If this is the case, remove said tags and it should work.

Related

Is there a way to overwrite a page's <title> tag by using PHP within the body?

I'm pretty new to PHP and was wondering if there was a way to overwrite what is displayed in a title tag by using PHP inside the body.
Let me explain why I'm trying to do this. I'm using a forum/cms software that allows me to create PHP pages, but won't let me change anything about the header (including the title tag). I was hoping there was a script that I could place into the body using PHP that would overwrite whatever was displayed into the default title tag.
This is probably a crazy question, and if so I apologize.
Just running out of ideas how to get what I need in the title.
Thanks!
You can't.
if you want to change it add some Java Script code that will execute on the client side and do this for you:
<script>
document.title = "This is the new page title.";
</script>
And with some PHP:
<head><title>some title</title></head>
<body>
<?php if (some condition, etc) { ?>
<script>
document.title = "This is the new page title.";
</script>
<?php } ?>
</body>
<html>
<head>
<title>Hello</title>
</head>
<body>
<?
echo "<script>document.title='Hello, World!';</script>";
?>
</body>
</html>

php syntax for big block of echo <?php if(1): ?> html<?php endif; ?> correct way

Well most is in the title. I wonder if it's supposed to be that way or i can do the same without an if(1) condition I'm doing this because my website pages are all as php includes.
Thank you all
Answer retained:
Okay basically the way to do it is simply to include('file.php') as it will be considered out of the current <?php ?> environment.
Putting
<?php if(1): ?>
...
<?php endif; ?>
around your HTML code in a PHP file will have no effect on the result. You will still be able to include the file without it.
You can think of it like the "default mode" for a PHP file is that it contains HTML content. You only need to add <?php ?> tags if you want to add PHP code. If you're just putting HTML code in a PHP file, they're unnecessary.
The beauty of PHP is that you can move "in" and "out" of PHP very easily. You can do the following without issues:
<?PHP
if(whatever) {
?>
your HTML
<?php
include('whatever.php');
?>
more HTML
<?PHP
}
?>
To build on Zak's answer:
You can also use PHP to echo out things that aren't PHP... as long as you quote it appropriately.
<?php
//HTML
while ($x < 5) {
echo "<p> this is html that you can wrap with html tags! </p>";
$x++;
}
//Javascript
echo "<script type='text/javascript'>
some javascript code
</script>"
?>
Although, it's less confusing to just end the php tag to keep things separate.
And you can even use php as you want within html or javascript as long as you put the tags, and as long as the file is saved as a .php file (so PHP can be processed on the server).
Ex:
<script type="text/javascript">
//set a javascript image array to a php value
var imgArray = [<?php echo implode(',', getImages()) ?>];
</script>
But if you want to do this the other way around (IE, assign a browser-compiled value, such as a javascript value to a php value), you'll need to use AJAX.

echo php variable on external javascript possible?

I (absolute php beginner) was given a script with different variables that are based on date and time on the top of xhtml strict page:
<?php
$var1="2011,9,31,18,0,0";
[...]
?>
Inside the html body I have a javascript that currently starts like this:
<script type="text"/javascript">
dateFuture = new Date(<?php echo $var1; ?>);
[...]
</script>
Is it possible to make the javascript external, but still pull the variable $var1 from the top of the index page and then have it show the same output on the index page as it currently does?
I have found one example where the beginning of the external .js is supposed to look like this:
dateFuture = new Date(<?php include("/index.html");echo $var1;?>);
Unfortunately that doesn't seem to work.
Is there any possible solution for this?
Any help is greatly appreciated.
Thank you in advance.
Yes. Make the javascript variable global and you can access it inside you external js file.
Something like this
<script type="text/javascript">
var dateFuture = new Date(<?php echo $var1; ?>);
</script>
<script src="your-external-js-file.js" type="text/javascript"></script>
In your-external-js-file.js, you can access the dateFuture.
Or you can encapsulate the code in external js file in a class and pass on the date from php as a parameter to the constructor of that class.
The external JavaScript file itself can point to a PHP file — provided that the PHP file outputs valid JavaScript. That way, you can do something like the following:
myJS.php:
<?php
// Initialize your PHP variable(s) here, or include the PHP script(s) to do so.
$var1="2011,9,31,18,0,0";
...
?>
dateFuture = new Date(<?php echo $var1; ?>);
In your HTML file:
<script type="text/javascript" src="myJS.php"></script>
Since the output of myJS.php is purely JavaScript code, the file extension will not matter to the browser. Same way as your PHP code currently outputs purely HTML code, and your browser understands how to parse that as well.
If your purpose is to move the javascript code to an external script for better modularization, you can move it to a php file and then reference php file as javascript.
<script type="text/javascript" src="myscript.php"></script>
Inside myscript.php -
<?
Header("content-type: text/javascript");
dateFuture = new Date(<?php echo $var1; ?>);
?>
Whilst the answers given by Jonathan Newmuis and RonakG are perfectly acceptable and will work, the purpose of this answer is to answer your question as close to the setup you've got now as possible. However I'd personally agree with RonakG's answer.
If you're using Apache on your server then add the following line to your .htaccess file: AddType application/x-httpd-php .js. Alternatively you could add that code into the Apache configuration if performance is an concern for you.
The goal of that code is, essentially, to say that PHP should parse all files ending in ".js" as if they were ".php"
Yes. It is possible. However, you are going to have to make the javascript file into a php file, or force Apache, or whatever web server you use, to run javascript as php (perfectly harmless, because all code outside of <?php ... ?> is just written to output).
In my-external-js.php or my-external-js.js (whichever you choose, though I would recommend the former, because it requires less configuration):
<?php require_once 'file-which-defines-var1.php'; ?>
dateFuture = new Date("<?php print $var1; ?>");
Note: you should always use require_once instead of include or require, so that the same file is never included twice, which leads to messed-up variables and colliding functions/classes. Also, require and require_once case Fatal errors if the script could not be loaded, while include and include_once do not.

Learning php. Hello world won't display using easyphp and writing in notepad++

<html>
<!--HTML-->
<head><title>a quick test</title></head>
<body>a quick test</body>
<p>javascript</p>
<!--javascript-->
<p><script>
document.write("hello world")
</script></p>
<p>php</p>
<!--php-->
<?php
Echo "hello world";
?>
</html>
The Hello world works for javascript but not in php, what gives? Any suggestions or obvious errors?
thanks
Are you saving this file with a .php file extension? PHP code will not execute within a normal .html file.
If you view source, can you read your PHP?
Perhaps your environment is set up wrong.
What does <?php phpinfo(); ?> yield?
To be w3 valid by the way, your body tag should end before the ending html-tag -> as such:
<body>a quick test
<p>javascript</p>
<!--javascript-->
<p><script>
document.write("hello world")
</script></p>
<p>php</p>
<!--php-->
<?php
Echo "hello world";
?>
</body>
</html>
First of all, before saving any file related to PHP, You have to clear see in which format it is going to Save. Save the file in .php extension, for example : filename.php then execute it at WAMP server. You will find HELLO World.

Organising code that includes php and javascript files

I have a website where I am including a php library file and a javascript library file. I have condensed the problem to the following files:
index.php
<?php
include('constants.php');
?>
<html>
<head>
<script type="text/javascript" src="lib.js"></script>
</head>
<body onload="javascript:show_const_1('<?php echo(CONST_TEXT); ?>');
show_const_2();">
Some text here
</body>
</html>
constants.php
<?php
define('CONST_TEXT', 'Hello World');
?>
lib.js
function show_const_1(string)
{
alert(string);
}
function show_const_2()
{
alert('<?php echo(CONST_TEXT); ?>');
}
The result is that when the page loads I get two message boxes. The first says "Hello World" and the second says "<?php echo(CONST_TEXT); ?>". The first javascript method does what I want it to, but I will be using the function in many places across the site and so ideally I don't want to have to pass the constant as a parameter every time.
Is there a good way to rearrange the code to make the second javascript method work?
The simple answer is rename "lib.js" to "lib.php".
You should also add
header('Content-type: text/javascript');
to the top of the file.
Incidentally, you should us json_encode() to output text to javascript:
alert(<?php echo json_encode(CONST_TEXT); ?>);
And "javascript:" doesn't belong in event attributes (which are kindof outdated anyway):
<body onload="doSomething();">
The method body inside alert() is not interpreted by PHP (it's interpreted by Javascript), so you can't put PHP tag in it

Categories