JavaScript get php array and post key + vaule to body - javascript

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>

Related

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>

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

Using values from PHP in JavaScript

I would like to use a value from PHP in JavaScript, but it's not working. I fetch data from a database and store it in a PHP variable and for conditional formatting. I need to also use the data in JavaScript for validation.
The value required by me is $date = date('Y-m-d'); If I pass the value by json Encode the alert function is not working...
$(document).ready(function()
{
alert("Hi");
var array = php print(json_encode($date));
});
Whereas if I just alert the function without...
var array = php print(json_encode($date)); ;
...it works fine.
<script type="text/javascript" src="assests/js/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
alert("Hi");
var array = '<?php print(json_encode($date)); ?>';
});
</script>
</head>
<body>
<form action="majorprocess.php">
<?php
$dbconn = mysql_connect('localhost', 'root','' );
if(!$dbconn)
{
die(mysql_error());
}
else
{
$date = date('Y-m-d');
<script type="text/javascript" src="assests/js/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
alert("<?php echo json_encode(date('Y-m-d')); ?>");
});
</script>
What is the resulting HTML?
There could be a PHP error outputting instead of valid javascript.
Try putting the PHP section at the top maybe?
When asking a question it is always best to post any outputs you are getting so people can help.
try this one
</head>
<body>
<form action="majorprocess.php">
<?php
$dbconn = mysql_connect('localhost', 'root','' );
if(!$dbconn)
{
die(mysql_error());
}
else
{
$date = date('Y-m-d');
}
?>
<script type="text/javascript" src="assests/js/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var array = '<?php print(json_encode($date)); ?>';
alert(array);
});
</script>
You are using the PHP $date variable before setting its value. Make sure to move the php block before you try to output the date:
<?php
$dbconn = mysql_connect('localhost', 'root','' );
if(!$dbconn)
{
die(mysql_error());
}
else
{
$date = date('Y-m-d');
}
?>
<script type="text/javascript" src="assests/js/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
alert("<?php echo json_encode($date) ?>");
});
</script>

How do I pass a variable from one php file to a javascript file?

I am currently trying to make a site where I put in info in on my html side, it send the info to the php file and grabs info from another site depending on what you put in on the html side.
To make this more clear this is how it works:
You put in your username in the html site(where the javascript code
is).
Then it sends your username to the php file.
The php file gets the information, puts it in a link and request it.
It grabs information from this request (highscores page).
This is where it stops.
I don't know how to return the information to my javascript file.
This is my code:
html/javascript page:
<html>
<head>
<script type="text/javascript" src="./aloticcalc_files/jquery.min.js"></script>
</head>
<body>
<script>
function test() {
var username = "Exzib";
window.location.href = "grabinfo.php?username=" + username;
}
</script>
</body>
</html>
This is my php file: (grabinfo.php)
<html>
<head>
</head>
<?php
$username = $_GET['username'];
include_once('simple_html_dom.php');
if(isset($_GET['name'])) {
$html = file_get_html('https://alotic.com/hs/?name='.$username);
$xp = $html->find('td', 10);
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
echo $formatxp;
}
?>
<body>
</body>
</html>
So how do I proceed to send the $formatxp to my javascript?
Thanks
So what you do is execute:
window.location.href = "grabinfo.php?username=" + username;
This causes the browser to navigate to grabinfo.php and display the information that you want. Except that you don't want the information to be displayed, you want to retrieve it into a JavaScript variable, right?
To do so, don't set window.location.href. Instead call your script using AJAX. You'll find plenty of tutorials on AJAX out there. This will allow you to capture the output of your PHP script.
Change the following line
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
to
$formatxp = str_replace(array('$',',','.',' '),'',$xp);
And to pass the variable to Javascript you can do something like this.
<script type="text/javascript">
var $formatxp = '<?php echo $formatxp; ?>';
</script>
Write a script tag and set the variable equal to your PHP variable.
<script>
var thing = '<? echo $formatxp; ?>';
</script>
This is going to be easy as you already include jQuery. (Using ajax)
Look
<html>
<head>
<script type="text/javascript" src="./aloticcalc_files/jquery.min.js"></script>
</head>
<body>
<label>Type your username:<input id="username" type="text"></label>
<input id="submit-button" type="button" value="Get my highscores!">
<p id="response"></p>
<script>
//When user clicks "submit-button" button
$("#submit-button").on('click', function() {
var username = $("#username").val();
//We request our php with the username
$.get("grabinfo.php?username=" + username, function(xpValue) {
//When we receive the response from php then we add it to a "p" tag
$("#response").text("LOL your xp is: "+xpValue+". NOOOOOOOB!!");
});
});
</script>
</body>
</html>
And that's it!
More info at http://api.jquery.com/on/
And http://api.jquery.com/get/
http://api.jquery.com/text/
http://api.jquery.com/val
And well the whole jQuery API documentation http://api.jquery.com
EDIT:
OH. You have to change grabinfo.php. It should only have this:
<?php
$username = $_GET['username'];
include_once('simple_html_dom.php');
if(isset($_GET['name'])) {
$html = file_get_html('https://alotic.com/hs/?name='.$username);
$xp = $html->find('td', 10);
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
if(empty($formatxp)) {
echo "ERROR: Invalid could not find xp with username {$username}";
}
else {
echo $formatxp;
}
}
else {
echo "ERROR: Invalid arguments";
}

PHP variable in JavaScript doesn't print

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!

Categories