I've been reading all the questions about how to print a PHP variable in JavaScript but all the answers I read until now don't work for me and I'm going crazy.
This is my code:
<?php
$MyPHPStringVar = '321321';
$MyPHPNumVar = 32;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>o maior</title>
</head>
<body>
<script type="text/javascript">
var MyJSStringVar = "<?php Print($MyPHPStringVar); ?>";
var MyJSNumVar = <?php Print($MyPHPNumVar); ?>;
alert(MyJSStringVar);
alert(MyJSNumVar);
</script>
</body>
</html>
When I run this the alert() shows "" for my phpstring variable and doesn't show nothing for my php number variable.
Why is this?? I'm going nuts because it seems to work for everybody but not me!!
Thanks for your time
use this instead :
<script type="text/javascript">
<?php echo " var MyJSStringVar = "\".$MyPHPStringVar.""\";
var MyJSNumVar = <?php echo $MyPHPNumVar; ?>;
alert(MyJSStringVar);
alert(MyJSNumVar);
</script>
#ToBe, here is the code:
<?php
$MyPHPStringVar = '321321';
$MyPHPNumVar = 32;
?><!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>o maior</title>
</head>
<body>
<script type="text/javascript">
var MyJSStringVar = "<?php print($MyPHPStringVar); ?>";
var MyJSNumVar = <?php print($MyPHPNumVar); ?>;
alert(MyJSStringVar);
alert(MyJSNumVar);
</script>
</body>
</html>
It's the same!
Use echo instead of Print. Something like -
var MyJSNumVar = <?php echo $MyPHPNumVar; ?>;
Also if your php.ini has short tags turned on you can use -
var MyJSNumVar = <?=$MyPHPNumVar?>;
It was an error on the PHP engine.
I reinstalled it with Microsoft Web Plataform Installer along with the new ISS8.0 and it's working great!
Related
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>
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
I'm new to coding and i have no idea why this is not working
please explain so i can learn, Thank You.
EDIT: Moving PHP to top is still not printing any thing.
<?php
//create array
$someArray = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
//encode array
$someJSON = json_encode($someArray);
//pritn array
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var array = "<?PHP echo $someJSON?>";
var arrayDecode = jQuery.parseJSON(array);
$.each(arrayDecode, function(key, value){
$('body').append(key + value + "<br><br>");
});
});
</script>
</head>
<body>
</body>
</html>
Try This.
You Need to Declare PHP Variable Before use in JS Script.
Otherwise the variable doesn't have any value and it will return error.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?php
//create array
$someArray = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
//encode array
$someJSON = json_encode($someArray);
?>
<script>
$(document).ready(function(){
var array = '<?php echo $someJSON; ?>';
arrayDecode = jQuery.parseJSON(array);
$.each(arrayDecode, function(key, value){
$('body').append(key + value + "<br><br>");
});
});
</script>
</head>
<body>
</body>
</html>
I had a variable in my php page which is an URL printed on that page, I had another html page where I needs this URL value from that php page and it should be assigned to the button in html page.
How can it be performed?
php page content:
if ($output== true) {
//Output results as URL
print_r($resulta);
}
html page content:
<p align="center">
<input type="button" name="res1" value="result">
You should use Ajax.
When you need information to be filled in HTML page the only easy way is Ajax.
I suggest you to use jQuery for simpler requests.
More info about making get request with jQuery: https://api.jquery.com/jquery.get/
Example:
$(function() {
$.get('request.php', {}, function(response) {
if (response.url) {
alert('No information from server!');
return;
}
$('button.mybutton').onclick(function() {
window.location.href = response.url;
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="mybutton">Click</button>
And in your PHP something like this:
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
$response = json_encode(array( 'url' => $url ));
die($response);
Header "Access-Control-Allow-Origin" is important when you do an Ajax request from different domains. you can see more usages of it in google: Access-Control-Allow-Origin
Use $_GET method to pass variables between PHP pages.
In your PHP page,
<?php
$value = "Some value";
header("location:nextPage.php?variable=$value");
exit();
?>
In the nextPage.php
<?php
$received = $_GET['variable'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<<button type="button"><?php echo $received; ?></button>
</body>
</html>
If the next page is not a PHP file, here is a solution,
// THIS WORKS FOR MULTIPLE VALUES, BUT IF YOU DO NOT SEND ANY VALUES, IT WILL SHOW ERROR OF "UNDEFINED". BUT THAT CAN ALSO BE FIXED.
// EXAMPLE : http://yourdomain.com?tag1=100&tag2=200&tag3=300
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<script>
var url,url_contents,received_values,passed_values;
url = document.URL;
url_contents = url.split("?");
received_values = url_contents[1];
received_values = received_values.split("&");
for(var i=0;i<received_values.length;i++)
{
var value_array = received_values[i].split("=");
alert(value_array[0]+"="+value_array[1]);
}
</script>
</head>
<body>
</body>
</html>
How to detect the current language of a multilanguage *joomla* website using javascript?
Try such way
<script>
window.addEvent('domready',function(){
var lang = document.getElement('html').getProperty('lang');
console.log(lang)
})
</script>
Try this
<?php
$lang = JFactory::getLanguage();
$lang_code = $lang->getTag();
$lang_name = $lang->getName();
?>
In Js
<script type="text/javascript">
var language_code = "<?php echo $lang_code;?>";
var language_name = "<?php echo $lang_name ;?>";
console.log("Lang Code"+language_code+"Lang Name"+language_name);
</script>
Hope this may help you..
var lang = document.getElement('html').getProperty('lang');
this code won't work on ie depending on your template, you may have some
<!--[if IE 9 ]> <html prefix="og: http://ogp.me/ns#" lang="en" class="ie9"> <![endif]-->
tags specifying the lang to en.