how to display output from PHP into HTML - javascript

basically what I've been trying to do is with PHP get a integer from MySQL after that is done, using JavaScript get the integer that PHP has and display it on HTML
<?php include('ConnectionCode.php');
$conn = mysqli_connect($svr, $usr, $pwd, $db) or die("Could not connect " . mysql_error());
$sql = "SELECT RetailPrice FROM WebHosting_PricingCOP WHERE id='32402' LIMIT 1";
$result = mysqli_query($conn, $sql);
$price = mysqli_fetch_array($result);
echo json_encode(number_format($price['RetailPrice'],0,".",","));
mysqli_close($conn)
?>
the code above will connect to the Database and get the value 59,347
now I'm trying to move this single value from PHP to Javascript in order to display it on HTML
<script type="text/javascript">
var PriceValue = "<?php echo json_encode($price) ?>";
document.write('<h3>'+PriceValue+'</h3>');
</script>
I have gone through many discussions and options here and there and still cant figure out to make it work, when i try to run the html it doesn't display anything
I would greatly appreciate your input

Update:
You may also have a problem with using json_encode inside of "" quotes.
var PriceValue = "<?php echo json_encode($price) ?>";
Instead, use:
var PriceValue = <?php echo json_encode($price) ?>;
or
var PriceValue = <?php echo $price ?>; // if $price is not an object
Note:
To debug this, check the generated HTML source to see what JavaScript you are actually generating.
$price needs to be in the same scope when you try to generate JS.
http://phpfiddle.org/main/code/aeav-gb1w
<?php
$price = 2523525;
?>
<script type="text/javascript">
var PriceValue = "<?php echo $price; ?>";
document.write('<h3>'+PriceValue+'</h3>');
</script>
However, it is going to be preferable for you to use your PHP file as an API endpoint instead of mixing your PHP and JavaScript together.

Related

'unexpected token: identifier error' - assigning php json array type variable value to a javascript function from php code

I am trying to call JavaScript function in php and pass it value of a php json array type variable as an argument. I found from search on SO forum one way to do this is to echo/print_r the variable value to a js var inside a js script within php code. I am trying do it this way but I am not able to recover from 'unexpected token: identifier error ' while doing so.
I am trying to figure out the reason of syntax error but couldn't. I tried different ways what I found; by putting quotes single/double around php part within the script, without quotes as some places I found solution with quotes some places without but no one seems working.
Here is my code. It will be very helpful if someone sees it and point what is causing this error.
<script>
dspChrt(WData);
.......
</script>
<HTML>
<?php
$WData;
require("Connection.php");
try {
$stmt = $conn->prepare("Select humidity, temperature FROM weatherdata");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll() as $k=>$v) {
$WData = json_encode($v);
//print_r($WData);
}?>
<script>
var Wdata = <?php print_r($WData);?>
dspChrt(WData);
consol.log(WData);
</script>
<?php
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
</HTML>
First of all you need to parse the JSON using JSON.parse.
Also you need to change the sequence of php and javascript code.
If you want to assign php data to Javascript variable, please retrieve data using php first and write javascript code below it.
For example :
<?php
$v = array(1,2,3);
$data = json_encode($v);
?>
<script>
var WData = JSON.parse('<?php echo $data; ?>');
dspChrt(WData);
</script>
You should encode your PHP into JSON to pass it to JavaScript.
And you should prepare your data first.
<?php
$data = array('xxx'=>'yyy');
?>
<script>
var data = <?php echo json_encode($data); ?>;
//then in js, use the data
</script>
for your code, there are too many errors to be fixed:
<HTML>
<?php
require("Connection.php");
$stmt = $conn->prepare("Select humidity, temperature FROM weatherdata");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$WData = array();
foreach($stmt->fetchAll() as $k=>$v) {
$WData[] = $v;
}
?>
<script>
var WData = <?php echo json_encode($WData);?>;
console.log(WData);
dspChrt(WData);
</script>
</HTML>

Array of Javascript in PHP

I was trying to get datas from the database and put them into the array in Javascript but Javascript is not working in PHP command area.
Here is the whole PHP codes;
<?php
mysql_connect("mysql.metropolia.fi","localhost","") or die("ERROR!!");
mysql_select_db("localhost") or die("COULDN'T FIND IT!!") or die("COULDN'T FIND DB");
$sql = mysql_query("SELECT * FROM METEKSAN_HABER_CUBUGU");
$haber = 'haber';
$list = array();
$i=0;
while($rows = mysql_fetch_assoc($sql)){
$list[] = $rows[$haber];
$i++;
}
echo $i;
echo '<script type="text/javascript">
var yazi=new Array();';
echo $i;
for ($k = 0 ; $k < $i ; $k++){
echo 'yazi['.$k.']="'.$list[$k].'';
}
echo '</script>';
?>
But when it comes to;
echo '<script type="text/javascript">
var yazi=new Array();';
this command line, the problem begins. Though I write 'echo $i;' after that command, I get nothing on the screen but I get the result if I write before that command. So, it means that everything works well before that command. What you think about the problem ? Why can't I starting the Javascript command ? Am I writing something wrong ?
Please give me a hand.
Thanks.
UPDATE;
I opened the web source and yeah it exactly seems there is a problem. So, I think it's better to ask that how can I write
<script type="text/javascript">
/*Example message arrays for the two demo scrollers*/
var yazi=new Array()
yazi[0]='METEKSAN Savunma, Yeni Dönemin Örnek Oyuncusu Olmaya Hazır'
yazi[1]='METEKSAN Savunma Bloomberg TVde'
</script>
this Javascript code in PHP ??
You can see my output at http://users.metropolia.fi/~buraku/Meteksan/index.php
try something like this
while($rows = mysql_fetch_assoc($sql)){
$list[] = ''.$rows[$haber].'';
}
$js_array = json_encode($list);
echo "<script>var yazi = ". $js_array . ";</script>";
It seems you are executing it currently in your browser? Then you should find your second output when opening page source, because your browser tries to executes the output as JS code. If you execute it on cli, everything should work as expected.
EDIT based on your comment:
Bullshit i wrote before, obviously. Viewing line 122 of your current html shows me a problem with your quotation marks. try the following:
for ($k = 0 ; $k < $i ; $k++){
echo 'yazi['.$k.']=\''.$list[$k].'\';';
}
In the end you should try to avoid using this kind of js rendering at all. The json_encode proposal of jeremy is the correct way to go.
You may have much more compact code:
....
$list = array()
while($rows = mysql_fetch_assoc($sql)) {
$list[] = $rows[$haber];
}
echo '<script type="text/javascript">' . "\n";
echo 'var yazi=';
echo json_encode($list,JSON_HEX_APOS | JSON_HEX_QUOT);
echo ";\n";
echo '</script>' . "\n";
What is this doing:
There's no need to count the added elements in $i, count($array) will give you the cutrrent number.. But it's not needed anyway.
Put some newlines behind the echo, better readable source
json_encode will format an JSON array from your php array, which can be directly used as source code.

passing PHP var to JS var [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I have a small issue. I can't seam to pass a variable from PHP to JS.
Here is my JS:
var eName = '<?php echo $eName; ?>';
I know that $eName has a value. However in the JS section, I get nothing. no data seams to be present in the variable. when I echo in the PHP section, I get data.
Can anyone help?
Also tried:
var eName = '<?php echo json_encode($eName); ?>';
This give me a null result
Thanks for your help
Here is how I get my PHP Variable populated:
$sql="SELECT * FROM league WHERE id='". $lID ."' LIMIT 1";
$result = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($result);
if($numrows < 1){
echo "league does not exist";
exit();
}
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$eName = $row["name"];
According to your edited code, I guess your variable $eName would be empty for the last record of the while loop.
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$eName = $row["name"];
// if the last record has the empty value for the field `name`,
// it will overwrite the previous value and
// you will get `$eName` of no value out of the loop later
}
And moreover, make sure you are not using <?php ?> in the .js file which is not parsed by Javascript.

Using php with database in a javascript

This code is when i hardcore the sentence "Have a nice day!", it will echo out the exact same line. My question is what if i want to retrieve sentence from the database, instead of hard-coding it.
<?php
$php_var = "Have a nice day!";
?>
<html>
<head>
<title>Hello</title>
</head>
<body>
<script>
var js_var = "<?php echo $php_var; ?>";
//var js_var = "Try123";
document.writeln(js_var);
//document.writeln(js_var);
</script>
</body>
</html>
I am suppose to do something like this is it? but it cant work. It printed out "SELECT * FROM sen WHERE id=1 ;" on the page.
<?php
$con = mysql_connect(localhost,root,password,database_name);
$php_var = "SELECT * FROM sen WHERE id=1 ;";
?>
<script>
var js_var = "<?php echo $php_var ; ?>";
//var js_var = "Try123";
document.writeln(js_var);
//document.writeln(js_var);
</script>
You're not executing the query and fetching the result. Something like this should work:
<?php
$con = mysqli_connect(localhost,root,password,database_name);
$php_var = mysqli_fetch_assoc(mysqli_query($con, "SELECT * FROM sen WHERE id=1 LIMIT 1"));
?>
<script>
var js_var = "<?php echo $php_var['id']; ?>";
//var js_var = "Try123";
document.writeln(js_var);
//document.writeln(js_var);
</script>
Please be aware of some things:
Don't forgot error handling on the right way. (Not or die)
Check if the MySQL connecton was successfully made.
Possibility of MySQL injection
I've updated mysql_* to mysqli_*, this because mysql_* is deprecated and will being removed in the future.
My suggestion is that you create a Rest api with json response backend in PHP and then have a javascript frontend using like JQuery $get or something.
Remove ; from the query.
Use $php_var = "SELECT * FROM sen WHERE id=1";

Run PHP echoed Javascript

I am just getting into the world of PHP, Javascript and HTML and would like some help from the community regarding the following code. Basically I want to pass variables plucked from a ODBC_connection by PHP into textboxes. Lines 1-3 were for me to test to get the box to update which it does but anything echoed by PHP does not run. I am completely new to this so I realize I must be missing something trivial.
I welcome any suggestions or comments about what I can do to fix this or what I can do better in general.
Thank you.
<script type='text/javascript'>
document.getElementById('modeltxt').value = "test2";
</script>
<?php
echo "<script type='text/javascript'>";
echo "document.getElementById('modeltxt').value =\"TEST3\";";
echo "document.getElementById('customertxt').value = $customer;";
echo "document.getElementById('endusertxt').value = $enduser;";
echo "document.getElementById(dongletxt').value = $dongle;";
echo "document.getElementById('shipdatetxt').value = $shipdate;";
echo "document.getElementById('chasistypetxt').value = $chasistype;";
echo "document.getElementById('chasisnumbertxt').value = $chasisnumber;";
echo "document.getElementById('opsystxt').value = $opsys;";
echo "document.getElementById('dvd1txt').value = $dvd1;";
echo "document.getElementById('dvd2txt').value = $dvd2;";
echo "document.getElementById('storagetxt').value = $storage;";
echo "document.getElementById('nodrivetxt').value = $nodrive;";
echo "document.getElementById('drivesizetxt').value = $drivesize;";
echo "document.getElementById('interface1txt').value = $interface1;";
echo "document.getElementById('interface2txt').value = $interface2;";
echo "document.getElementById('interface3txt').value = $interface3;";
echo "document.getElementById('interface4txt').value = $interface4;";
echo "document.getElementById('interface5txt').value = $interface5;";
echo "document.getElementById('interface6txt').value = $interface6;";
echo "document.getElementById('commentstxt').value = $comments;";
echo "document.getElementById('warrantyexptxt').value = $warrantyexp;";
echo "document.getElementById('extendedwarrantytxt').value = $extwarexp;";
echo "document.getElementById('onsitetxt').value = $onsite;";
echo "document.getElementById('sqlversiontxt').value = $sqlversion;";
echo "<\script>";
You can create dynamics JS using the below
Define Content-Type on the top of your .js.php file:
<?
header('Content-Type: application/javascript');
// Write your php code
?>
and call the js file like this ..
<script type="application/javascript" src="JS_PATH/name-of-file.js.php"></script>
and if you want to use inline php values, you can write like this
<script type="application/javascript">
document.getElementById('modeltxt').value = "<?php echo $dummy_value ?>";
</script>
No need to do this. You can simply use javascript inside php as below :-
As you mention in your question
Basically I want to pass variables plucked from a ODBC_connection by PHP into textboxes.
<?php
// Php block of code
?>
<script type="text/javscript">
document.getElementById('modeltxt').value = "TEST3";
document.getElementById('customertxt').value = "<?php echo $customer;?>";
......
....
...
</script>
<?php
// Another block of code
?>

Categories