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'"; ?>;
Related
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
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.
I want to echo the javascript from php in a heredoc. But its not working because of dollar sign. Escaped the dollar sign but it's still not working . Could anyone help out regarding this. Thanks. It gives an error
Uncaught ReferenceError: $ is not defined
<?php
echo '<!DOCTYPE html> <html> <head><title> hello world </title> </head> <body>' ;
$testscript=<<<EOT
<script>
\$('input[type=radio][name=gender]').change(function() {
alert(this.value);
});
</script>
EOT;
echo $testscript;
echo '</body></html>' ;
?>
jquery library was not loaded in the script
I was passing an array in php to Javascript using json_encode and ajax. It seems that the only way is to use
echo json_encode($var)
which also prints out the information of $var on the page because of echo. Is there an easy way to hide the output? My code was like the follows,
main.php
<?php
include_once('testing.php');
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="testing.js"></script>
</body>
<html>
testing.php
<?php
$var=array('1','2','3','4','5');
echo json_encode($var);
?>
testing.js
$.ajax({
url : './testing.php',
type : "GET",
dataType : 'json',
success : function (result) {
showstaff(result);
}
});
function showstaff(x){
console.log(x);
}
Running main.php print out the array('1','2','3','4','5') on the page and show the array in the console, but what I need is to just show the array in the console (i.e. hide the results from the page).
You don't need include_once('testing.php') in main.php. When main.php is sent to the browser, it will load testing.js, which will then execute testing.php via the AJAX call.
You can try this:
<script type="text/javascript">
var object = <?php echo json_encode($var); ?>;
</script>
Hope it helps, thanks!
I got no output when I use variable in val() function instead of fixed value. How can I fix this error.
Example: In the below example, when I use variable ($data="Glenn Quagmire"), I get no output.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
<?php $data="Glenn Quagmire"; ?>
$("input:text").val($data);
});
});
</script>
</head>
<body>
<p>Name: <input type="text" name="user"></p>
<button>Set the value of the input field</button>
</body>
</html>
Regards
Just use like this:
$("input:text").val("<?php echo $data; ?>");
Full code
<script>
$(document).ready(function(){
$("button").click(function(){
<?php $data="Glenn Quagmire"; ?>
$("input:text").val("<?php echo $data; ?>");
});
});
</script>
Don't use "$" for variables (that's PHP) in jQuery.
<?php echo 'data="Glenn Quagmire";'; ?>
$("input:text").val(data);
JavaScript running in the browser cannot access variables from a PHP program (which has finished running on another computer before delivering the page to the browser so the variable does't even exist any more).
You have to make PHP output the data to the JavaScript.
You can encode it using json_encode (because JSON is (more or less) a subset of JavaScript literal syntax). This will add quotes as needed and escape any special characters in your data (you don't have any in your example, but this is a safe, general approach that protects you from XSS).
$("input:text").val(<?php echo json_encode($data); ?>);
Use <?= $variable ?> to embed variable values in HTML, e.g.:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
<?php $data="Glenn Quagmire"; ?>
$("input:text").val("<?= $data ?>");
});
});
</script>
</head>
<body>
<p>Name: <input type="text" name="user"></p>
<button>Set the value of the input field</button>
</body>
</html>