how to assign php variable to JS variable - javascript

<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

Related

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>

Javascript cant get value from PHP variable?

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!');
}
});

How to echo PHP MySQL query into Javascript variable without outputting closing PHP tag "?>"?

<script>
$(function() {
var name = [
<?php
$Database = "database name";
$DatabaseUserName = "db_user";
$DatabasePass = "db_pass";
$connect = mysql_connect("~", $DatabaseUserName, $DatabasePass);
#mysql_select_db($Database) or ("Database not found");
$query = "SELECT ~ FROM ~";
$result = mysql_query($query) or die ( $result."<br/><br/>".mysql_error());
while ($row = mysql_fetch_array($result)) {
echo "\"". $row['~']."\", ";
}
// $result = mysql_query($query) or die ( $result."<br/><br/>".mysql_error());
mysql_close($connect);
?>
];
$( "#~" ).autocomplete({
source: name
});
});
</script>
Basically, I'm getting correct output except the closing PHP tag "?>" is included in the output when I don't want it to be. Is there a better way to do this?
Use json_encode() to output JavaScript safe data. For example...
<script>
<?php
// connect, query, etc
$data = [];
while ($row = ...) {
$data[] = $row['~'];
}
?>
var name = <?= json_encode($data) ?>;
</script>
Here's a simplified demo ~ eval.in
And of course, here's the obligatory "don't use the deprecated mysql extension, etc" addendum.
Run this code and check if it is still coming. I could not reproduce the error.
<html>
<head>
<script>
var name = [
<?php
$row=array("Volvo", "BMW", "Toyota");
for($i=0;$i<count($row);$i++) {
echo "\"". $row[$i]."\", ";
}
?>
];
</script>
</head>
<body>
</body>
</html>

How to pass PHP (index.php file ) Variable value to external JAVASCRIPT .js File?

Actually this code is wrote in index.php file but now i want to pass this javascript array value to external js file.
<?PHP
$qry2 = mysql_query("SELECT table_no FROM table_info");
while($res2 = mysql_fetch_array($qry2))
{
static $i = 0;
$i++;
$reg_table[$i] = $res2['table_no'];
}
?>
<script>
var bookedSeats = new Array();
<?php foreach($reg_table as $key => $val)
{ ?>
bookedSeats.push('<?php echo $val; ?>');
<?php }?>
</script>
I want the bookedSeats variable to be in the external table.js file.
You have jQuery tag in there, so I am going to give you this... use Ajax:
test.php
<?php
// Handle Ajax Request
if (isset($_GET['loadData']))
{
// Query your db here, im building dummy data
$results = array();
for ($i = 0; $i < 10; $i++) {
$results[] = 'Data '. $i;
}
// Return Data
exit(json_encode($results));
}
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
// Load Data Via Ajax
$.getJSON("test.php?loadData", function(bookedSeats)
{
console.log(bookedSeats);
});
</script>
When the page loads, we get the result like this:
<script>
var bookedSeats = new Array();
<?php foreach($reg_table as $key => $val)
{ ?>
bookedSeats.push('<?php echo $val; ?>');
<?php }?>
</script>
This can be greatly simplified and made immune to XSS:
<script>
var bookedSeats = <?php echo json_encode(array_values($reg_table)); ?>;
</script>
You can now refer to bookedSeats in your external .js file, but only if that file is being run after this inline script has been placed. In other words, putting:
<script src="external.js"></script>
after the <script>...<?php ... ?>...</script> is okay, but putting it before is only okay if you are deferring its execution - it's just safer to put it after ;)
I have an alternative solution for you eventually even if Latheesan Kanes's one is right.
Mine is just given as a trivial exemple if you have access to a constructor in your Javascript object in the table.js file.
<script>
var bookedSeats = new Array();
person=new Object();
<?php foreach($reg_table as $key => $val)
{
// here a javascript object
?>
person.firstname="John"; // of course replace firstname and John by your informations
<?php }?>
// then call table.js constructor
var objectInTableDotJS = new YourConstructor(person); // now in table.js you need to make modification :)

Javascript updating variable

I have used some javascript with some php. The jquery changes a php variable like it should... i echoed the new php variable and it shows, however my javascript variables don't change
<?php
$image ='<div id="myid"></div>';
?>
<script type="text/javascript" src="storescripts/jquery-1.10.2.min.js"></script>
<script>
var my_pic = new Image();
my_pic.src = '<?php echo $image; ?>';
</script>
<script language="JavaScript" type="text/javascript">
function swapContent(cv){
$("#myDiv").html("animated gif").show();
var url ="myphpscript2.php";
var id = <?php echo $id; ?>;
$.post(url,{contentVar: cv, id: id,},function(data){
$("#myDiv").html(data).show();
});
}
</script>
These are the scripts used. I have no idea why just before the php variable will change but the other will just stay as ''

Categories