Echo PHP variable from JavaScript? - php

I have a PHP page with some JavaScript code also, but this JavaScript code below doesn't seem to work, or maybe I'm way off!
I am trying something like this:
var areaOption=document.getElementById("<?php echo #$_POST['annonsera_name']?>");
areaOption.selected=true;
Also I have tried this, but it only alerts a BLANK alert-box:
alert (<?php echo $test;?>); // I have tried this with quotes, double-quotes, etc... no luck
Am I thinking completely wrong here?
UPDATE
Some PHP code:
<?php
$test = "Hello World!";
?>

In your second example, you are missing quotes around the string (so H is interpreted as a variable - which you didn't set).
Test this:
alert (<?php echo "'H'";?>);
OR
alert ('<?php echo "H";?>');

PHP runs on the server side and Javascript is running on the client side.
The process is that PHP generates the Javascript that will be executed on the client side.
You should be able to check the JS that is generated just looking at the code. Of course, if the JS relies on some PHP variables, they need to be instanciated before the JS is output.
<?php
$test = 'Hello world';
?>
<html>
<body>
<script>
alert('<?php echo $test; ?>');
</script>
</body>
</html>
will work but
<html>
<body>
<script>
alert('<?php echo $test; ?>');
</script>
</body>
</html>
<?php
$test = 'Hello world';
?>
will not

Use json_encode to convert some text (or any other datatype) to a JavaScript literal. Don't just put quotes around the echoed string — what if the string has a quote in it, or a newline, or backslash? Best case your code fails, worst case you've got a big old cross-site-scripting security hole.
So,
<?php
function js($o) {
echo json_encode($o, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP);
}
?>
<script type="text/javascript">
var areaOption= document.getElementById(<?php js($_POST['annonsera_name']); ?>);
areaOption.selected= true;
alert (<?php js('Hello World'); ?>);
</script>

Your using #$_POST indicates that you have received (or are expecting) errors - check your generated source to see if the value was output correctly. Otherwise document.getElementById will fail and you'd get no output.

alert("Delete entry <? echo $row['id']; ?> ")

If your extension is js, php will not work in that file.
The reason being, php parses on files that it is supposed to. The file types that php will parse are configured in httpd.conf using AddType commands (or directives, whatever they are called).
So you have 3 options:
add filetype js to the list of files php will parse (BAD, VERY BAD)
make the script inline to some php file
rename the file to script.js.php, and at the beginning of the file, specify the content type, like so:
<?php header( 'content-type: text/javascript' ); ?>
Cheers!

Related

Chance.js and PHP game scripting

I'm scripting a small RP game Text base. I found a site with chance.js script free to use but I am trying to find out how to use it within PHP.
This is the code they tell you to use:
<script src="chance.js"></script>
<script>
console.log(chance.bool());
</script>
But every time I put it in my PHP it blacks out everything and does not work. I have tried to search everywhere to try and find out why but found nothing. A lot of sites say I can't use JavaScript in PHP, but I know that can't be true.
Please, someone point me in the right direction... :)
P.S. the replay with be true or false http://chancejs.com/ <<< is the site it's from.
PHP != JavaScript. JavaScript is client-side and PHP is server-side.
You might want to use rand() to generate random numbers.
If you want to output this into browser do it either as:
<?php
...
?>
<script src="chance.js"></script>
<script>
console.log(chance.bool());
</script>
<?php
...
?>
or use the echo php function:
echo '<script src="chance.js"></script>
<script>
console.log(chance.bool());
</script>';
To echo JavaScript inside of PHP, you should do this:
<?php
echo"
<script src='chance.js'></script>
<script>
console.log(chance.bool());
</script>
";
?>
Also, notice that I echoed it inside of double quotes, this means that now if you use double quotes inside of your JS you should escape them like this: \".
As stated in a previous answer, you should be very careful about mixing PHP with JavaScript, as PHP is always executed before JS.

Assigning output of external Javascript src to avoid script hang out

I have two websites: domain1.com and domain2.com.
The script on domain1.com/external.php is:
<?php
echo <<<ots
<!--
document.write('Hello World!');
//-->
ots;
?>
I want to execute this external.php script on domain2.com, so I use:
<script src="http://domain1.com/external.php"></script>
The problem is - the Javascript often hangs out, so I wanted to include the < script.. right below the < /body>. However, I must print the Hello World! text in a specific place on the page (ie. right after the </head>).
Question - can I include the < script.. right below the < /body> to assign the output somehow and then put this variable on the page after the script executes?
Or any other similar solution? I cannot use JQuery.
You can use innerHTML to replace the content of one element on the page:
document.getElementById('idOfTarget').innerHTML='Hello World!';
Please note that you can modify the element only after it's created, so put the script before </body> if possible or use window.onload event:
window.onload=function(){
document.getElementById('idOfTarget').innerHTML='Hello World!';
};
See also this mine earlier answer to see how to replace an element by the classname or the tagname.
If you need to use PHP in your script, then you still can do that:
window.onload=function(){
document.getElementById('idOfTarget').innerHTML='<?php
echo "Hello World!";
?>';
};
Please note that if you want to update a lot of elements, you may want to use AJAX/JSON.
You can but you have to use in your external.php file
header('Content-type: text/javascript');
So it's possible to use it like
<script src="http://domain1.com/external.php"></script>

php shortcode into jquery

I have a Wordpress based website, and some of the content is loaded through javascript.
For example:
jQuery(".portfolio-fs-slides").css({"display":"none"}).prepend('<div class="portfolio-fs- slide current-slide portfolio-ppreview"><div class="project-coverslide"></div><div id="content" class="content-projectc contenttextwhite"></div></div>');
What I want to do is append this shortcode: <?php echo do_shortcode('[daisy]'); ?>
But as far as I know is not really possible to append php code in javascript.
Is there any workaround to accomplish this ?
Thanks!
As #Bergi mentioned, the PHP will run serverside, and the JS will run client side. You can output JS (or parts of your JS) via PHP and have it run client side, e.g.
<script>
// extra code here
jQuery(".portfolio-fs-slides").css({"display":"none"}).prepend('<div class="portfolio-fs- slide current-slide portfolio-ppreview"><div class="project-coverslide"></div><div id="content" class="content-projectc contenttextwhite"></div></div>');
<?php echo 'we can output valid js here' ?>
// more code here
</script>
One way to think of this is that since PHP runs server side, it will always run before the JS is parsed.
Put another way, you could have a javascript line like this:
console.log(<?php echo $someVariable ?>);

Extracting information from PHP to JavaScript

I've been stuck for hours now trying to pass a few pieces of information from a PHP script to JavaScript. The PHP script echoes out HTML and I've figured there might be a problem with this if I'm to try and send the JavaScript a JSON object through AJAX. The thing is, all the arrays and such are made within the PHP file which echoes out the results, so what I have done is to try and json_encode those arrays/and or echo them out somehow.
Is it even possible for me to send the information this way? The only thing I can think of would be to write those arrays into a new file and then explode it up into new ones and similar. Not a very fun thought.
To give you an idea of what my PHP looks like:
echo "<html here>";
echo "<html here>";
echo "<html here>";
echo json_encode($array);
Just build your HTML/JavaScript code from PHP...
Simple example (PHP)
<?php
$phpvariable = 'test variable from php';
echo "<html>\n<head>\n</head>\n<body>\n";
echo "<script type=\"text/javascript\">\n";
echo " myPHPvar = '$phpvariable';\n";
echo " alert(myPHPvar);\n";
echo "</script>\n";
echo "</body>\n</html>";
?>
Output (HTML)
<html>
<head>
</head>
<body>
<script type="text/javascript">
myPHPvar = 'test variable set in php';
alert(myPHPvar);
</script>
</body>
</html>
Output (Browser)
JavaScript variable myPHPvar gets value from PHP variable $phpvariable. That is the simplest way to pass variable from PHP to JavaScript.
What's your question? What are you trying to achieve in javascript with your data from PHP? Does the ajax call work at all?
In general I'd recommend separating HTML construction from providing array data as json.
You'd like to handle both in one single PHP call, don't you?
You could attach html parts to you array and send json only, or have array data in a fake html element, that you might exclude from display later. Depends on how complex both parts are. Give some more example code and information, please.

disabling javascript codes using php?

is there a way to disable javascript codes in a particular page using certain php codes? I need to ensure that all the javascripts used in a page should not give any result (even errors) when run.
Why don't you just not send the javascript down for those particular pages?
You could throw PHP conditionals around the Javascript so they won't display on your page:
<script type="text/javascript">
<?php if($showJavascript): ?>
// executes the following function
myJavascriptFunc();
<?php endif; ?>
function myJavascriptFunc() {
}
</script>
And to resolve any issues from my comments:
<?php var showJavascript = <?php echo ($showJavascript) ? 'true' : 'false'; ?>;
<script type="text/javascript" src="myFile.js"></script>
In the last case you should check the boolean value of showJavascript in myFile.js.
The easiest way (and the dirtiest, slowest, etc) is to turn on the output buffer at the start of the page, and, before echoing the buffer's content at the end, remove all traces of javascript, either through regular expressions, a html parser, or a combination of both.
<?php
ob_start();
// your code here
$output = ob_get_contents();
ob_end_clean();
// Purge your $output here, remove all <script> tags, onclick events, etc.
echo $output;
?>
How to purge the output has already been answered on SO many, many times.
There is no such way because PHP run on your server and JavaScript runs client-side once your server has done it's part and it's done by browser.
What you can do is make sure that your JS doesn't have errors or remove all the JavaScript.

Categories