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";
Related
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>
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.
I want make data exist checker.
data.check.php:
<?php
$nick = mysql_real_escape_string($_POST['nick']);
$query = mysql_query("select * from tb_user WHERE nick='$nick'");
$nick_exist = mysql_num_rows($query);
?>
<script language="javascript" type="text/javascript">
var nick_exist = "<?php echo $nick_exist; ?>";
</script>
and this for $POST data
input.data.js
var v_nick = $('input:text[name=nick]').val();
$.post('data.check.php', {nick: v_nick} ,function() {
if(nick_exist){
window.alert('Choose another nick please!');
}
});
I dont know where is the problem and my windows.alert is not running :(
thanks u
try like this get the count in php then return it to js:
NOTE: Please do not use mysql it is deprecated now start using mysqli or pdo.
data.check.php:
<?php
$nick = mysql_real_escape_string($_POST['nick']);
$query = mysql_query("select * from tb_user WHERE nick='$nick'");
$nick_exist = mysql_num_rows($query);
echo json_encode(array('count'=> $nick_exist));//send result to javascript
?>
input.data.js
var v_nick = $('input:text[name=nick]').val();
$.post('data.check.php', {nick: v_nick} ,function(resp) {
var resp=JSON.parse(resp);
if(resp.count){
window.alert('Choose another nick please!');
}
});
<html>
<head>
<script type="text/javascript">
var t;
alert(t);
</script>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'pass';
$t_id = 6;
$con = new PDO("mysql:host=$dbhost;dbname=testing",$dbuser,$dbpass);
$q = $con-> prepare("query");
$q -> bindParam(1,$t_id);
$q -> execute();
$res = $q->fetchAll();
foreach($res as $r)
{
$ab = $r[0];
$abc = $r[1];
}
echo $ab;
echo $abc;
?>
<script type="text/javascript">
t = <?php echo $abc;?>;
</script>
</body>
</html>
When i alert "t" variable just after assigning php variable, it works fine.
But i want to use "t" in the head section of the page.
actually i just want to set JS variable from DB.
how to do it?
hope it helps you,
<script type="text/javascript">
var t = "<?php echo $abc;?>"; //if not initialised variable t before use var
</script>
Try like
<script type="text/javascript">
t = '<?php echo $abc;?>';
</script>
I'd suggest that you put the php-code before any html output as the first part of your file. As soon as one html character is transferred, the complete header of the document is sent and you will not be able to change header-information any more.
To output a php-variable to javascript, use the following code if $abc is a string:
<script type="text/javascript">
"use strict";
var t = '<?php echo $abc; ?>';
alert(t);
</script>
and the following if $abc is a numeric value:
<script type="text/javascript">
"use strict";
var t = <?php echo $abc; ?>;
alert(t);
</script>
I strongly recommend using the
"use strict";
line. It will give you better debug output during development. For example it will tell you if you are assigning a value to a variable that has not been initiated. Helps a lot, trust me ;-).
<html>
<head>
//move your php code to head of the page
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'pass';
$t_id = 6;
$con = new PDO("mysql:host=$dbhost;dbname=testing",$dbuser,$dbpass);
$q = $con-> prepare("query");
$q -> bindParam(1,$t_id);
$q -> execute();
$res = $q->fetchAll();
foreach($res as $r)
{
$ab = $r[0];
$abc = $r[1];
}
echo $ab;
echo $abc;
?>
<script type="text/javascript">
var t;
t = <?php echo $abc;?>; //add the database variable here you want to use
alert(t);
</script>
</head>
<body>
</body>
</html>
Let us know if its still confusing
I'm basically working on a site in which a user repeatedly clicks a button, increasing his score each time he clicks. I don't want the page to refresh between each click, so I'm using AJAX.
The problems I'm having currently are as follows:
When I try to set my javascript var to = <? echo $result['count']; ?>, it doesn't seem to work.
I don't understand how to correctly use PDO to UPDATE a MySQL table with a calculation in the query, such as $update = $dbh->execute("UPDATE count SET count='$count'+1 WHERE username='$username'");. Is this the correct syntax for the calculation and is this the right way to do it in PDO?
Here is the code for my testing page which I am using for the clicking system:
<html>
<?php
$hostname = 'localhost';
$username2 = 'refrigerator';
$password = 'xxx';
$dbh = new PDO("mysql:host=$hostname;dbname=refrigerator", $username2, $password);
$username = $_COOKIE["user"];
$rows = $dbh->prepare("SELECT count FROM count WHERE username = '$username'");
$rows->execute();
$result = $rows->fetchALL();
$result['count'] = $count;
if(isset($_POST['action'])){
if ($_POST['action'] == 'increase'){
$update = $dbh->execute("UPDATE count SET count='$count'+1 WHERE username='$username'");
}
}
?>
<body>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var count = <? echo $result['count']; ?>;
$("#update").click(function() {
$.ajax({
type: "POST",
url: "button.php",
data: {"action":"increase"},
success: function(update) {
count++;
$("#counter").html(+count);
}
});
});
});
</script>
<button id="update" type="button">Button</button>
<div id="counter"><? echo $result['count']; ?></div>
</body>
</html>
Thanks a lot, any help would be greatly appreciated. Even if you can point me in the right direction which will help me answer my questions, that would be awesome.
Thank you
You should have:
$count = $result['count'];
Instead of:
$result['count'] = $count;
The variable to the left of the = sign is what is receiving the assignment from whatever value is on the right of the = sign.
In your update statement you could, instead of using your count variable, could do:
$update = $dbh->execute("UPDATE count SET count=count+1 WHERE username='$username'");