How to assign JavaScript variable to PHP session variable? - javascript

Here's javascript code that i have
var randomnum = 30;
and here's PHP code
<?php $_SESSION['numbertoguess'] = '<script>document.write(randomnum)</script>';?>
But this is not passing the value
But when i am trying this code below, it works. It gives session variable that the value 'a sample thing'.
<?php $_SESSION['numbertoguess'] = 'a sample thing';?>

Look at the following code. The PHP session is assigned to 30 from the Javascript value. however am not sure if this is good way for implementation.
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Html Page Title</title>
</head>
<body>
<script>
var randomnum = 30;
</script>
<?php $_SESSION['numbertoguess'] = '<script>document.write(randomnum)</script>';?>
<?php echo $_SESSION['numbertoguess']; ?>
</body>
</html>

You can't access Session directly in JavaScript.
You can make a hidden field and pass it to your page and then use JavaScript to retrieve the object via document.getElementById

Related

Cant echo PHP variable inside <script> tags? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This is my PHP code. I want error to be displayed using an alert window.
if ($projectid=="")
{
$error = 'You must choose a project.
Click ‘back’ and try again.';
include error.html.php';
exit();
}
This is error.html.php that is supposed to be parsed by the browser
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Script Error</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script>
var error = <?php echo $error ; ?>;
window.onload = function(){ alert(error); }
</script>
</body>
</html>
Wahts up with the script tags ? Do they prevent PHP from running ?
The real problem is that this is what your rendered result looks like:
var error = You must choose a project.
Click ‘back’ and try again.
Does that looks like valid JavaScript to you? I think not.
var error = <?=json_encode($error);?>;
That should result in:
var error = "You must choose a project.\r\n Click ‘back’ and try again.";
Much better.
Your problem is that javascript is run on the client and will run after the page loads and so after the php is run on the server.
However, you can do something like the following which allows php to set the value of a javascript variable when the page loads and then AFTER the page is loaded runs the javascript to display the message.
<?php
$error = "test me";
echo "<script>error = '" . $error . "'</script>";
?>
<script>
var error;
window.onload = function(){
alert(error);
}
</script>
UPDATE
Based on your edits, here's an updated answer.
The echo "<script>error = '" . $error . "'</script>" is needed to assign the $error to the javascript variable when the page is loaded.
if ($projectid=="")
{
$error = 'You must choose a project.
Click ‘back’ and try again.';
echo "<script>error = '" . json_encode($error) . "'</script>"
include error.html.php';
exit();
}
And the html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Script Error</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script>
var error;
window.onload = function(){ alert(error); }
</script>
</body>
</html>
If you have an $error within your PHP, then you can write:
<?php
echo "<html><head></head><body></body>";
$error = "whoops!"; // just for testing
echo "<script>\n";
echo "alert('{$error}')\n";
echo "</script>\n";
echo "</html>";
?>
and the alert will happen as soon as the page is loaded, tested it on my server. This is for the situation where the $error is happening on the server side. (By the way, thanks for the fun question this late in my day!)
Actually it's quite simple.
if ($projectid=="")
{
$error = 'You must choose a project.
Click ‘back’ and try again.';
include 'error.html.php';
exit();
}
$error will now contain You must choose a project. Click ‘Back’ and try again. Note, there are no quotes, so then the line
var error = <?php echo $error ; ?>;
looks like this in the client:
var error = You must choose a project.
Click ‘Back’ and try again;
Which naturally causes an error as that is not valid javascript. You need to add quotes, either inside the definition of $error serverside or outside the PHP -- something along the lines of:
$error = '"You must choose a project.
Click ‘back’ and try again."';
OR
var error = '<?php echo $error ; ?>';
as per your preference...
You certainly can use inline php to generate javascript code. They will, of course, be executed in different contexts, Server-Side vs. Client-Side, but that's mostly irrelevant.
However, you have to realize that the two languages aren't communicating as such, but part of the JS is being generated by the output of the PHP. You have to be careful about that output. One of the issues you have is that JS does not support multiline strings, so the value of $error in PHP can't have a newline.
Try this instead:
if ($projectid=="")
{
$error = 'You must choose a project. Click \"back\" and try again.';
include 'error.html.php';
exit();
}
and
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Script Error</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script>
var error = "<?php echo $error ; ?>";
window.onload = function(){ alert(error); }
</script>
</body>
</html>
List of fixes:
Fixed quotes in the include statement.
Added quotes around the inline PHP echo in the JS code.
Removed the newline in the $error var so JS gets it all in one line.
Removed html quotes and replaced them with escaped regular quotes. Alert boxes don't process those.

Find the parent filename within an embedded JavaScript file that is generated with PHP

If, within a php generated page (findmyfilename.php), I embed a JavaScript file (php_js.php) that uses php to generate its content, is there any way within php_js.php that I can find with php the name of the parent i.e. findmyfilename.php?
I have tried
$parentfile = $_SERVER['PHP_SELF'];
$parentfile = basename(__FILE__);
$parentfile = $_SERVER["SCRIPT_NAME"];
$parentfile = $_SERVER["REQUEST_URI"];
$parentfile = $_SERVER["SCRIPT_FILENAME"];
but these all return php_js.php.
I want to be able to generate the content of php_js.php depending upon the page that called it.
// findmyfilename.php
<!DOCTYPE html>
<html>
<head>
<title>Find my filename</title>
</head>
<body>
<script type="text/javascript" src="/scripts/php_js.php">
</body>
</html>

Why PHP not working with Javascript?

A very popular answer in StackOvwerflow suggested that in order to get any php variable within a javascript, simply use php withi angular brackets.
var x= <?php echo "val"; ? >
. However I see that the script given below entirely fails to run If I use this method.
Once I comment out that line script works fine.
<script>
var test=<?php echo "hi"; ?>;
alert(test);
document.title=test;
</script>
Even this simple script is not working.
The page is saved as .php
The page resides in WAMP server and is accessed as localhost/test.php
.
.
EDIT: Full code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Test</title>
<script>
var test=<?php echo "hi"; ?>;
alert(test);
document.title=test;
</script>
</head>
<body>
<div id="test-canvas" style="float:left;width:100%;height:100%;"></div>
</body>
</html>
I believe your omitted the ' ' in the script
<script>var test = '<?php echo $variable; ?>';</script>
Hope this helps, good luck.
Try this :-
var test = '<?php echo "anything"; ?>';
alert(test);
The result of your php is:
var test=hi;
And that will make a problem because javascript needs quotes too when dealing with strings.
You can do this to solve the issue:
var test=<?php echo "'hi'"; ?>;

DOMDocument stripping tags from inline scripts PHP

This is a strange one but looks like $dom->saveHTML() is stripping tags from inline javascript
$domStr = '
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>my page</title>
<script>
var elem = "<div>some content</div>";
</script>
</head>
<body>
<div>
MY PAGE
</div>
</body>
</html>
';
$doc = new DOMDocument();
libxml_use_internal_errors(true);//prevents tags in js from throwing errors; see php.net manual
$doc->formatOutput = true;
$doc->strictErrorChecking = false;
$doc->preserveWhiteSpace = true;
$doc->loadHTML($domStr);
echo $doc->saveHTML();
exit;
http://sandbox.onlinephpfunctions.com/code/ad59a2a1016b2128e437ef61dbe00f1c511bff8d
if you use libxml_use_internal_errors(true); you will not see what is wrong but if removed you get
<b>Warning</b>: DOMDocument::loadHTML(): Unexpected end tag : div
Same thing happens with
$doc->formatOutput = false;
Any help is appreciated.
I've avoided this by not including any HTML in my inline JavaScript. Instead, I've added <template> elements containing the HTML string I want to manipulate in JS, and then I read that dynamically at runtime. For example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>my page</title>
</head>
<body>
<div>
MY PAGE
</div>
<template id="content-template">
<div>some content</div>
</template>
<script>
var elem = document.getElementById('content-template').innerHTML;
...
</script>
</body>
</html>
It is probably a bug of DomDocument.
You have to escape the closing tag of HTML in JS or it gets misinterpreted.
This should work
var elem = "<div>some content<\/div>";
Alternatively, if you pass option 1 to the loadHtml the parser will ignore it.
In a bit of an oddity 1 can mean both LIBXML_SCHEMA_CREATE and LIBXML_ERR_WARNING as these two predefined constants have the same value. Presumably it is meant to be LIBXML_SCHEMA_CREATE which does the following "Create default/fixed value nodes during XSD schema validation".
You're missing the opening <html> tag right after the DOCTYPE declaration.

Sending a JSON encoded PHP variable to JS

I am trying to send a PHP variable to my javascript. In order to do this, I encode the php variable with json, send it to my view with my controller, use it as a value in a hidden html form, and then pull the value with js, using parseJSON to get the final product.
HTML (I'm using laravel, the brackets are equivalent to php tags):
<input type="hidden" id="js-helper-artist-likes" name="js-helper-artist-likes" value="{{$artist_likes}}">
JS
var artist_likes = $('#js-helper-artist-likes').val();
console.log(artist_likes);
In the page source, I see that the value is populating with the json string, but when I print it to the console from my js like the above, all that is showing is: [{
I am not sure why this is.
I want to perform:
var artist_likes_decoded = $.parseJSON(artist_likes);
to get the decoded variable in JS, but this is impossible without the encoded string coming up correctly in the artist_likes variable in js.
Any ideas what I'm doing wrong? Thank you.
<input type="hidden" id="js-helper-artist-likes" name="js-helper-artist-likes" value="{{ echo $artist_likes}}">
You could use:
<input type="hidden" id="js-helper-artist-likes" name="js-helper-artist-likes" value="<?= json_encode($artist_likes) ?>">
<?php
$yourVariable ="something";
$arr = json_encode(array("name"=>$yourVariable));
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<input type="hidden" id="js-helper-artist-likes" name="js-helper-artist-likes" value='<?php echo $arr; ?>'>
<script>
$(document).ready(function(){
var artist_likes = $('#js-helper-artist-likes').val();
console.log($.parseJSON(artist_likes));
});
</script>
</body>
</html>

Categories

Resources