Using values from PHP in JavaScript - 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>

Related

Echoing a mulitple line message in alert function

I need to echo multiple line error in JS alert and I am using below code
Working code
$str = "This is a error1\\n";
$alert = $str."This is error2";
if(!empty($alert)){
?>
<script type="text/javascript">
alert('<?php echo $alert;?>');
</script>
<?php
}
but I need to work on an old written code so this has addslashes function before echo alert like below:
$str = "This is a error1\\n";
$alert = $str."This is error2";
$alert = addslashes($alert);
if(!empty($alert)){
?>
<script type="text/javascript">
alert('<?php echo $alert;?>');
</script>
<?php
}
Output : This is a error1\nThis is error2
I need this to print in two lines I have also tried with only \n but it is not working then.
I'd make javascript do the hard work.
<script type="text/javascript">
var alertArr = ["<?php echo $string1; ?>", "<?php echo $string2; ?>"];
alert(alertArr.join("\n"));
</script>
https://jsfiddle.net/0uwmmm3n/
(Magnificent random url by the way)
EDIT: less messy version, maybe more legitimate
<?php $alertArr = [$string1, $string2]; ?>
<script type="text/javascript">
var alertArr = <?php echo json_encode($alertArr); ?>;
alert(alertArr.join("\n"));
</script>
RE-EDIT: nah, too much work for a job so simple, two conversions is way too much
$str = "This is a error1\\n";
$alert = $str."This is error2";
$alert = addslashes($alert);
if(!empty($alert)){
?>
<script type="text/javascript">
alert('<?php echo $alert;?>');
</script>
<?php
}
I have used this code and it working fine according to your need
if still issue continues then clear your cache

Php foreach and echo inside javascript

Good day to everyone:). I just want to ask how can I do php foreach and echo values inside the javascript, because I want the javascript to be a dynamic.
Here is the static js
<script type="text/javascript">
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if($(this).attr("value")=="1"){
$(".1").toggle();
}
if($(this).attr("value")=="2"){
$(".2").toggle();
}
if($(this).attr("value")=="3"){
$(".3").toggle();
}
if($(this).attr("value")=="4"){
$(".4").toggle();
}
});
});
</script>
and this what I want to happen
<script type="text/javascript">
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
<?php foreach($data as $field): ?>
if($(this).attr("value")=="<?php echo $field->ID);?>" ){
$(".<?php echo $field->ID);?>").toggle();
}
<?php endforeach; ?>
});
});
</script>
the ID values form the database are 1,2,3,4. That would be all. Thank You!
you can push all the values to a js array and than do a loop on js array.
<script type="text/javascript">
$(document).ready(function(){
my_values = Array;
<?php foreach($data as $field): ?>
my_values.push ("<?php echo $field; ?>");
<?php endforeach; ?>
$('input[type="checkbox"]').click(function(){
// java script loop here
for ( var i in my_values)
{
if($(this).attr("value")== i )
{
$("."+this.value).toggle();
}
}
});
});
</script>

javascript onload in while

I'm trying to initialize inputs with maps api autocomplete -the number of inputs comes from database- , but I'm not able to execute a simple javascript function in a while loop.
The initialazing is working fine with window.onload, but I can't execute the function in this while loop...
No errors appearing in Console, 1 result is coming from database.
$limit = $bdd->prepare('MySQL query');
$limit->execute();
while ($city = $limit->fetch()) {
echo 'result'; ?>
<script type="text/javascript">
function initializeLimitCity() {
alert("Hello World");
};
initializeLimitCity();
</script>
<?php
}
You cant declare same function more times... Change your code to this:
<script type="text/javascript">
function initializeLimitCity() {
alert("Hello World");
};
</script>
<?
$limit = $bdd->prepare('MySQL query');
$limit->execute();
while ($city = $limit->fetch()) {
echo 'result'; ?>
<script type="text/javascript">
initializeLimitCity();
</script>
<?php
}
?>
<script type="text/javascript">
function initializeLimitCity() {
alert("Hello World");
};
</script>
<?php
$limit = $bdd->prepare('MySQL query');
$limit->execute();
while ($city = $limit->fetch()) {
echo 'result'; ?>
<script type="text/javascript">
initializeLimitCity();
</script>
<?php
}
You are generating the function with the same name several times, it won't work.
I'd not generate it this way. Let the client (Javascript) do the work, resulting in less bytes to transfer (HTML):
<?php
$cities = $limit->fetch_all();
?>
<script type="text/javascript">
function initializeLimitCity(cities) {
alert(cities);
};
initializeLimitCity(<?php echo json_encode($cities); ?>);
</script>

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 ''

how to assign php variable to JS variable

<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

Categories