Call javascript function using php variable - javascript

I am using the below code to call the javascript function from php script. Its not working while am adding the php variable in javascript($msg). Please help me to do this.
if ( isset($_GET['Error'])) {
$msg =$_GET["Error"];
echo '<script type="script.php">validate("Error",$msg);</script>';
}

You have to quote the $msg or it will be syntax error in javascript.
And the type is non sense.
Since the msg is from the $_GET, don't forget the escape it.
if ( isset($_GET['Error'])) {
$msg =$_GET["Error"];
echo '<script>validate("Error", "'.htmlspecialchars($msg).'");</script>';
}

Instead of an inline script, this should work:
<html>
<head>
<script type="text/javascript">
function testMe(x){
alert(x);
}
</script>
</head>
<body>
<?php
$phpVar = 'I am a PHP variable';
echo "Click Me";
?>
</body>
<html>

Related

php call a js function that is defined on different js file

I am trying to call
this js function that is stored on a file called default.js from a php file.
function myfunction(score) {
console.log("got here");
alert(score);
}
so this is the call for the js function on my php code but it does not work.
<!-- myfunction js file ↓ -->
<script type="text/javascript" src="../js/default.js"></script>
<?php
if ($grade=="100%"){
// not able to call
echo "myfunction($grade)";
}
else{
echo "alert(\"haha\")";
}
?>
Try this you will get the accurate result
<?php
if ($grade == "100%") {
?>
<script>
myfunction('<?=$grade?>');
</script>
<?php
} else {
?>
<script>
alert('in');
</script>
<?php } ?>
you forgot about the <script> tags
change your echo like this:
echo "<script>myfunction('$grade')</script>";
you need to wrap ' around the $grade because you're passing a string
or put <script> before the opening php tag and </script> after the end of php tag
This is your Code.
Define $grade too in PHP or you get a
<b>Warning</b>: Undefined variable $grade in <b>
<script type="text/javascript" src="../js/default.js"></script>
<script>
<?php
$grade = "10%";
if ($grade=="100%"){
echo "myfunction('$grade')";
}
else{
echo 'alert("haha");';
}
?>
</script>
Dont forget the <script></script> for javascript code inside html.

How to send a normal variable's value from PHP to JavaScript?

I have the below piece of code in my test.php file. The code mainly has a variable defined in PHP, and I want to send it to a JavaScript function so it could POST it. Here's the code :
<!DOCTYPE html>
<html lang="en">
<head>
<title>Payment Receipt</title>
</head>
<body>
<?php
...
if($row) {
$myValue = 'Hi there!'; //the PHP variable (currently has a sample value, but will be string only)
//JS starts
echo <<<JS001
<script type="text/javascript">
var msg = {$myValue}; //trying to set it to a JS var, so I could send it to below function.
var ThunkableWebviewerExtension = {
postMessage: function (message) {
if (window.ReactNativeWebView) {
window.ReactNativeWebView.postMessage(message);
} else {
window.parent.postMessage(message, '*');
}
}
};
ThunkableWebviewerExtension.postMessage(msg);
console.log(msg);
alert('Message Sent');
</script>
JS001;
} else {
echo 'Incorrect Value';
}
?>
</body>
</html>
But when I run this code, I get this error on console : Uncaught SyntaxError: Unexpected identifier. What should I do if I want to send just a simple string value to the JS code? What's wrong currently?
Any help is appreciated! Thanks!
You can do:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Payment Receipt</title>
</head>
<body>
<?php
...
if($row) {
$myValue = 'Hi there!';
?>
<script>
var msg = "<?php echo $myValue; ?>"; //trying to set it to a JS var, so I could send it to below
//Your remaining js script here ...
</script>
<?php } else {
//your else condition
}
?>
</body>
</html>
Try this
<!DOCTYPE html>
<html lang="en">
<head>
<title>Payment Receipt</title>
</head>
<body>
<?php
...
if($row) {
$myValue = 'Hi there!'
?>
<script>
var msg = "<?php $myValue; ?>";
</script>
<?php } else {
echo 'Incorrect Value';
}
?>
</body>
</html>
Simplifying your code (which you should always do when debugging!) you have this:
$myValue = 'Hi there!';
echo <<<JS001
<script type="text/javascript">
var msg = {$myValue};
</script>
JS001;
If you look at the HTML that's returned to the browser, you'll see that it looks like this:
<script type="text/javascript">
var msg = Hi there!;
</script>
The browser has no idea that "Hi there!" was supposed to be a string, so it tries to execute it as code.
What you wanted the output to be was this:
<script type="text/javascript">
var msg = 'Hi there!';
</script>
So we need to add those quote marks into the PHP:
$myValue = 'Hi there!';
echo <<<JS001
<script type="text/javascript">
var msg = '{$myValue}';
</script>
JS001;
As a more general solution, you can abuse the fact that JSON strings are valid JS values, and use json_encode in the PHP:
$myValue = 'Hi there!';
$myValueJson = json_encode($myValue);
echo <<<JS001
<script type="text/javascript">
var msg = {$myValueJson};
</script>
JS001;
This makes no difference in this case, but is useful for passing other types of value - arrays, null, etc
For a better code management, you should probably separate HTML, PHP, and JS code in different files.
Imagine something like this :
controller.php
$displayName="David";
include 'vue.php';
vue.php
<html>
...
<body>
<div id="php-data" data-displayName="<?php echo $displayName ?>"></div>
</body>
</html>
script.js
<script>
var msg = document.getElementById('php-data').dataset.displayName // "David";
</script>

Passing PHP variable to Javascript Array

i want to pass PHP variable to Javascript array.
It is a test code, but in further i want to pass the printed product id's and name's to this ajax function to send it to cart
The code above is working without printing the button with echo.Any better ideas are welcome :)
<html>
<?php
$num=3;
echo "<button onclick='funkt('<?php echo $num ?>');'>cc</button>
";
?>
</html>
<script>
function funkt(x){
var c=x;
alert(c);
}
</script>
You weren't properly escaping the quotes inside the echo statement. Also, HTML attributes use double quotes (onclick="..."), not single quotes.
Try this:
<!DOCTYPE html>
<html>
<head>
<script>
function funkt(x) {
var c = x;
alert(c);
}
</script>
</head>
<body>
<?php
$num = 3;
echo "<button onclick=\"funkt('" . $num . "');\">cc</button>";
?>
</body>
</html>
Better option is to add an input field of type hidden and pass the number/name/ID to it. On submission of form or button click, you can fetch it wtih the field Id and pass the value to ajax.
<input type="hidden" id="number" value="<?php echo $num;?>" />
<script>
function funkt(x) {
var c = document.querySelector("#number").value;
alert(c);
}
</script>
You can try to declare variable inside "script" tag, and then use this variable in the javascript afterwards like this:
<?php $num = 5; ?>
<script>
var link_label = '<?php echo $num ?>';
//use your link_label value to load it in ajax here or in other files that has been loaded after this script
</script>

How to pass variables from PHP to Javascript redirect

I've put together this short little code that should randomly pick a url from "url.txt" and then redirect it through a javascript redirect. For whatever reason I can't get it to work. I'm aware of how to get it to work with other forms of redirection including meta refresh and php header, however I would like to know how to do with with javascript redirection.
<?php
$loadlist = explode("\n", file_get_contents('urls.txt'));
$rand = rand(0,count($loadlist)-1);
$picked = $loadlist[$rand];
?>
<html>
<head>
<script type='text/javascript'>
window.location.href = '<?php echo $picked ?>'
</script>
</head>
</html>
<?php
$loadlist = explode("\n", file_get_contents('urls.txt'));
$rand = rand(0,count($loadlist)-1);
$picked = $loadlist[$rand];
?>
<html>
<head>
<script type='text/javascript'>
window.location.replace("<?php echo $picked ?>");
</script>
</head>
</html>
Try this

How to echo a PHP variable in JavaScript? [duplicate]

This question already has answers here:
Pass a PHP string to a JavaScript variable (and escape newlines) [duplicate]
(14 answers)
Closed 9 years ago.
I need to echo a PHP variable into JavaScript. But I have no experience about JavaScript, I did some research but nothing worked for me.
The code
function hide() {
document.getElementById("myDiv").style.display="none";
<?php echo $myVar; ?>
}
And the $myVar looks like:
$myVar = "Hi there";
you can do like this in js :
var php_val = '<?php echo $myVar; ?>';
alert(php_val);
use this
$myVar = 'var myVar="Hi here"'
or
function hide() {
document.getElementById("myDiv").style.display="none";
var myVar='<?php echo $myVar; ?>'
}
There is 2 ways to write PHP variable in javascript:
First Way:
JavaScript written in the php page or inline:
EX:
<?php
$myVar = 'hello';
?>
....
<script>
function hide() {
document.getElementById("myDiv").style.display="none";
<?php echo $myVar; ?>
}
</script>
Second way:
Put your variables on the top of your page, like baseUrl for example, and use it in separated JavaScript file but you have to write the variables before load JavaScript files.
EX:
<head>
<script>
var baseUrl = <?php echo $thisPageUrl; ?>
</script>
</head>
....
<script src="myscriptfile.js"></script>
<?php $var="blah"; ?>
<script type="text/javascript">
alert('<?php echo $var ?>');
</script>

Categories