Why isn't Javascript retrieving values of PHP variables? - javascript

When I run this code, the alerts fail to display the values and instead an empty alert box pops up.
<?php
$x = 20;
$y = "Hello World!";
$list = array();
$list[0] = "January";
$list[1] = "February";
$list[2] = "March";
$list[3] = "April";
$list[4] = "May";
?>
<script type="text/javascript">
alert("JS code executed");
alert(<?php $x ;?>);
alert(<?php echo $list[3];?>);
</script>

First, you aren't echoing $x.
Second, you need to quote the string for JavaScript, so:
alert("<?php echo $list[3]; ?>");
would work.

You should use your Browser's Development tools to see what is happening with you javascript.
If you look at Console, you will see something like:
Uncaught ReferenceError: April is not defined
This is because you forgot putting Quotes on your script, also you forgot to echo the $x. The right code is:
<script type="text/javascript">
alert("JS code executed");
alert("<?php echo $x ;?>");
alert("<?php echo $list[3];?>");
</script>
#Slaks said that this code have an XSS vulnerability, but this depends on if the origin of your $x and $list variable is safe or not.

Related

PHP variable in javascript "Invalid or unexpected token"

I'm having a problem trying to use a PHP variable within JavaScript. I keep getting the following message.
"Invalid or unexpected token. Message: Undefined variable: example."
I'm unsure why example is being undefined, as it is defined within the php code. Here is my code:
<?php
$example = '2';
?>
<script type="text/javascript">
var php_var = "<?php echo json_encode($example); ?>";
</script>
Does anyone have any suggestions? I have also tried the following javascript that results in the same problem:
<script type="text/javascript">
var php_var = "<?php echo $example; ?>";
</script>
Firstly, your original code has a syntax error: $example = '2' needs a semicolon.
Secondly, the next piece of code is just assigning the string <?php echo $example; ?> to the JavaScript variable php_var where the $example PHP variable is first substituted. The $example variable should be initiated properly first, however, for this to work.
As a separate note: JS cannot execute PHP directly -- only a PHP server can do so. What you're most likely trying to do is this:
<?php
$example = '2';
?>
<script type="text/javascript">
var php_var = '<?php echo $example ;?>';
</script>
This should work, use single quotes
<?php
$example = '2';
?>
<script type="text/javascript">
var php_var = '<?php echo $example; ?>';
</script>
Tried and working both variant:
<?php
$example = '2';
?>
<script type="text/javascript">
var php_var = <?php echo json_encode($example); ?>;
console.log(php_var);
</script>
<script type="text/javascript">
var php_va = "<?php echo $example; ?>";
console.log(php_va);
</script>

Javascript not able to print large string

I am entirely new to JavaScript and the only reason I need it now is to update a picture on a PHP page. The picture is in Base64. This is the code I currently have:
if($data != null){
$data = "data:image/jpeg;base64, " . $data;
?>
<script type="text/javascript">
var myvar = "<?php echo ($data); ?>";
document.write("test" + myvar);
</script>
This simply does not output anything.
However, if I try something like this:
if($data != null){
$data = "data:image/jpeg;base64, " . $data;
?>
<script type="text/javascript">
document.write("test" + "<?php echo strlen($data); ?>");
</script>
it does work and outputs a number somewhere between 10.000 and 20.000. I read on the internet that there is not really a max variable size in JavaScript, atleast not one I am able to reach with this size.
What am I doing wrong?

Why javascript code with a php var isn't working?

I want to change the content in javascript of a textbox while using PHP.
If I change it with plain Text as:
echo "<script> var test = 0; simplemde.value('test');
test+= 5; alert(test);</script>";
it works. But with a php-Variable it isn't working any longer:
echo "<script> var test = 0; simplemde.value('$markdown');
test+= 5; alert(test);</script>";
Not sure what I'm doing wrong. If I open the site and watching the source-text it stands in the correct form there but It isn't in the box.
Here is my full code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="./css/markdown.css">
<script src="./js/markdown.js"></script>
</head>
<body>
<textarea id="myID">
</textarea>
<script>
var simplemde = new SimpleMDE({
element: document.getElementById("myID"),
spellChecker: false,
});
</script>
<?php
require_once './Michelf/Markdown.inc.php';
use \Michelf\Markdown;
require_once 'loader.php';
$json_a = load();
if(count($json_a) > 0)
{
$text = $json_a[0]['blog'];
echo "found";
}
else
echo "not found";
$markdown = Markdown::defaultTransform($text);
echo $markdown;
echo "<script> var test = 0; simplemde.value('test'); test+= 5;
alert(test);</script>";
echo "<script> var test = 0; simplemde.value('$markdown');
test+= 5; alert(test);</script>";
?>
</body>
</html>
Things your question is missing:
The value of $markdown
The resulting JS you get for running the PHP
The error messages displayed on your browser's Developer Tools console.
That said, we can make some assumptions.
Markdown is a text markup language designed to write documents in something that looks a lot like plain text. One of its key features are new lines (used to delimit paragraphs).
Literal new line characters are not allowed in JavaScript string literals.
(Even without those assumptions, it is reasonable to say (for any answer to a question about replacing a string literal with some unspecified text):)
You need to escape or otherwise encode characters in $markdown that have special meaning.
The easiest way to do this is to take advantage of JSON being more-or-less the same as JS literal syntax.
$js_string = json_encode($markdown);
echo "<script> var test = 0; simplemde.value($js_string);
test+= 5; alert(test);</script>";
Note that $js_string gets quotes of its own, so you don't need to manually include them when outputting the variable.

php variable to javascript with json_encode

I know this topic was already discussed a few times but I can't seem to find what I'm doing wrong.
What I'm trying to do:
The user types in a number and by clicking on the button creates a table with that number of columns.
Heres the php:
<?php
$twig = require_once('bootstrap.php');
$hostname = 'localhost';
$username = 'root';
$password = '';
$conn = new PDO("mysql:host=$hostname;dbname=mydb", $username, $password);
echo $twig->render('index.html', array());
$numOfRows = 1;
if(isset($_POST['button'])){
$numOfRows = $_POST['num_input'];
}
html/javascript:
<html>
<head>
<script>
function insertRows(){
var numOfRows = <?php echo json_encode($numOfRows) ?>;
var out = "<table><tr><th>test</th>";
for (i = 0; i < numOfRows; i++){
out += "<th>test</th>";
}
out += "</tr></table>";
document.getElementById("table").innerHTML = out;
}
</script>
</head>
<body>
<form action="index.php" method="post">
<textarea id="num_input" name ="num_input"></textarea>
<button type="button" name="button" onclick="insertRows()"> Go </button>
</form>
<p id="table"></p>
</body>
</html>
Theres no error or anything since I'm not using a IDE, just doing it in vim but the error is that is just doesn't happen. If i change "numOfRows" in the for loop to a number it works, so I'm pretty sure the json_encode is the problem.
Thanks!
EDIT:
Just to test it, I used a string variable $str = "test"; the php file, and instead of using the for loop, I just edited javascript to
var str = <?php echo json_encode($str); ?>;
alert(str);
and I also tried
var str = <?php echo $str; ?>;
alert(str);
but nothing works.
json_encode is not necessary in this case.
Simply replace
var numOfRows = <?php echo json_encode($numOfRows); ?>;
with
var numOfRows = <?php echo (int)$numOfRows; ?>;
Edit: You are missing a ; on the
<?php echo json_encode($numOfRows) ?>
Should be
<?php echo json_encode($numOfRows);?>
And in these cases, if would be good to check the server log, this will automaticly make you better at finding these mistakes yourself.
You are mixing up ints and strings. The database will in PHP always return strings and the way you are using the variable as an int in a for loop.
The following change i believe would achieve the right result.
$numOfRows = intval($_POST['num_input']);
Where you use PHP's conversion to integer function there is at a global level.
You did not forget any $. JS does not need $ for variables.
As far as your json_encode is concerned, if you are just passing an integer from PHP to JS, there is no need to json_encode. Just pass the variable to JS as <?=$numOfRows?> in the JS source.

Redirect to a page/URL after alert button is pressed

i have referred to this two questions call php page under Javascript function and Go to URL after OK button in alert is pressed. i want to redirect to my index.php after an alert box is called. my alert box is in my else statement. below is my code:
processor.php
if (!empty($name) && !empty($email) && !empty($office_id) && !empty($title) && !empty($var_title) && !empty($var_story) && !empty($var_task) && !empty($var_power) && !empty($var_solve) && !empty($var_result)) {
(some imagecreatefromjpeg code here)
else{
echo '<script type="text/javascript">';
echo 'alert("review your answer")';
echo 'window.location= "index.php"';
echo '</script>';
}
it's not displ ying anything(no alert box and not redirecting). when i delet this part echo 'window.location= "index.php"'; it's showing the alert. but still not redirecting to index.php. hope you can help me with this. please dont mark as duplicate as i have made tose posts as reference. thank you so much for your help.
You're missing semi-colons after your javascript lines. Also, window.location should have .href or .replace etc to redirect - See this post for more information.
echo '<script type="text/javascript">';
echo 'alert("review your answer");';
echo 'window.location.href = "index.php";';
echo '</script>';
For clarity, try leaving PHP tags for this:
?>
<script type="text/javascript">
alert("review your answer");
window.location.href = "index.php";
</script>
<?php
NOTE: semi colons on seperate lines are optional, but encouraged - however as in the comments below, PHP won't break lines in the first example here but will in the second, so semi-colons are required in the first example.
if (window.confirm('Really go to another page?'))
{
alert('message');
window.location = '/some/url';
}
else
{
die();
}
window.location = mypage.href is a direct command for the browser to dump it's contents and start loading up some more. So for better clarification, here's what's happening in your PHP script:
echo '<script type="text/javascript">';
echo 'alert("review your answer");';
echo 'window.location = "index.php";';
echo '</script>';
1) prepare to accept a modification or addition to the current Javascript cache.
2) show the alert
3) dump everything in browser memory and get ready for some more (albeit an older method of loading a new URL
(AND NOTICE that there are no "\n" (new line) indicators between the lines and is therefore causing some havoc in the JS decoder.
Let me suggest that you do this another way..
echo '<script type="text/javascript">\n';
echo 'alert("review your answer");\n';
echo 'document.location.href = "index.php";\n';
echo '</script>\n';
1) prepare to accept a modification or addition to the current Javascript cache.
2) show the alert
3) dump everything in browser memory and get ready for some more (in a better fashion than before) And WOW - it all works because the JS decoder can see that each command is anow a new line.
Best of luck!
Like that, both of the sentences will be executed even before the page has finished loading.
Here is your error, you are missing a ';'
Change:
echo 'alert("review your answer")';
echo 'window.location= "index.php"';
To:
echo 'alert("review your answer");';
echo 'window.location= "index.php";';
Then a suggestion:
You really should trigger that logic after some event. So, for instance:
document.getElementById("myBtn").onclick=function(){
alert("review your answer");
window.location= "index.php";
};
Another suggestion, use jQuery
Working example in php.
First Alert then Redirect works.... Enjoy...
echo "<script>";
echo " alert('Import has successfully Done.');
window.location.href='".site_url('home')."';
</script>";
<head>
<script>
function myFunction() {
var x;
var r = confirm("Do you want to clear data?");
if (r == true) {
x = "Your Data is Cleared";
window.location.href = "firstpage.php";
}
else {
x = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = x;
}
</script>
</head>
<body>
<button onclick="myFunction()">Retest</button>
<p id="demo"></p>
</body>
</html>
This will redirect to new php page.

Categories

Resources