Unable to show php variable in javascript? - javascript

I am unable to show php variable in javascript;
this is my code here:
<script type="text/javascript">
$(document).ready(function (){
var n=<?php echo json_encode($count)?>;
for(var i=0;i<n;i++){
var div = document.createElement('div');
div.className = "d5";
div.id=i+1;
document.getElementById('wrapper').appendChild(div);
<?php
$query="select * from shop_product where shop_uniqueid='$unq'";
$result=mysql_query($query);
while($row=mysql_fetch_array($result))
{
$product=$row["in_product"];
?>
var product=<?php echo $product?>;
$('#'+div.id).html(product);
<?php
}
?>
}//for loop ends
});//ready ends
</script>
here i am trying to pass var product in html() of which value is coming from php like: var product=<?php echo $product?>;
but when doing so php value is not coming in Javascript's var product.
when I pass $('#'+div.id).html("abcd"); abcd value is showing in divs.
please help me.

Compare the first place you take data from PHP and put it in JavaScript:
var n=<?php echo json_encode($count)?>;
with your attempt to assign the product value:
var product=<?php echo $product?>;
You haven't converted the data from plain text to JavaScript in the second line. Use json_encode there too.

Related

PHP, HTML, JS conflicting execution order

I have having big issues with the execution order of my code.
HTML sample:
<div id="toast-container" class="toast-top-right"><div id="toast-type" class="toast" aria-live="assertive" style=""><div id="snackbar">message</div></div></div>
.
.<!--Somewhere more down the line-->
.
.
<div class="col_half col_last">
<label for="job-ctc-frm-heard-about">How did you find out about us?</label>
<input type="text" id="job-ctc-frm-heard-about" name="job-ctc-frm-heard-about" value="<?php echo $discovered;?>" class="sm-form-control" />
</div>
Javascript function:
<script>
function Toast(message, messagetype)
{
var cont = document.getElementById("toast-container");
cont.classList.add("show");
var type = document.getElementById("toast-type");
type.className += " " + messagetype;
var x = document.getElementById("snackbar");
x.innerHTML = message;
setTimeout(function(){ cont.classList.remove("show")}, 3000);
}
</script>
PHP sample:
<?php
$discovered ="";
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$message = 'Let the games begin';
echo "<script type='text/javascript'>Toast('$message', '$Success');</script>";
$discovered = test_input( $_POST["job-ctc-frm-heard-about"] );
......
?>
Now heres my problem. My php uses a function Toast. My function Toast accesses the HTML div toast-container to set a message. The other div uses the php variable $discovered to remember the entered value on a failed form submit. If i position the JS anywhere before the DOM then var cont will be null so it has to be below.
However if I position the code order as PHP -> HTML -> JS then the function is undefined in PHP so it has to be after JS. But if i position it as HTML -> JS -> PHP then the variable $discovered won't be displayed in the HTML. The orders are conflicting with one another. Is there any work around for this?
The simplest would be to just move the relevant parts to where you need them. You need $discovered to be available throughout your file (when PHP is executed server-side) and you need it to echo the script specifically after your Toast-declaration:
<?php
$discovered ="";
if($_SERVER["REQUEST_METHOD"]=="POST") {
$message = 'Let the games begin';
$discovered = test_input( $_POST["job-ctc-frm-heard-about"] );
// ...
}
?>
<!-- HTML referencing $discovered here -->
<script>
function Toast(message, messagetype)
{
var cont = document.getElementById("toast-container");
cont.classList.add("show");
var type = document.getElementById("toast-type");
type.className += " " + messagetype;
var x = document.getElementById("snackbar");
x.innerHTML = message;
setTimeout(function(){ cont.classList.remove("show")}, 3000);
}
</script>
<?php
if($_SERVER["REQUEST_METHOD"]=="POST") {
echo "<script type='text/javascript'>Toast('$message', '$Success');</script>";
}
?>
If you want to control these things from client-side, you can json_encode your PHP objects, meaning they will be sent in plain-text as if you had hard-coded them into the file. As #FZs mentions, PHP runs on the server and "prepares" the file by executing all <?php ... ?> blocks. When the result reaches the browser, it contains the resulting text and not PHP (browsers don't understand PHP).

Change Jquery variables to PHP

I need to put a Javascript variable into php variable, I dont know how to do that. Possible answers are appreciatable.
<script type="text/javascript">
$(document).ready(function(){
$('#number_of_inwards,#number_of_outwards').each(function(){
var product_name,total_stock;
$('#product_name').change(function(){
product_id = $('#product_name').val();
});
var hello = "13";
<?php $d = '<script>hello</script>' ?>
total_stock = <?php echo $st[$d]; ?>;
console.log(total_stock);
$(this).focusout(function(){
var inward = parseInt($('#number_of_inwards').val());
var outward = parseInt($('#number_of_outwards').val());
$('#overall_stock').val(parseInt(inward+outward));
console.log("Inside the Loop"+ inward + outward);
})
})
});
</script>
Here from the code.I added dummy variable
hello="13"
And tried to get it into php variable but It won't work, It returns empty value.
Thanks in advance

How to parse a PHP variable using a dynamic JS variable?

I have 5 PHP variables, $menu1 to $menu5, that each evaluate to a keyword. I'm trying to populate these 5 PHP variables in JavaScript, and display them. The below code doesn't work. What is wrong with my processing of the PHP variables?
var menu_populator = "";
for (var x = 1; x <= count; x++) {
menu_populator += '<li><a class="myclass" href="#link">' + '<?php echo $menu' + x + '?>' + '</a></li>';
}
$('#nav_menu').html(menu_populator);
Depending on how you are getting the menu data server-side you can try both methods below. One is for set $menu variables but if you are getting data from a database or the $menu variable are created within a loop you might find the second method better.
Method one- PasteBin
Echo your php variables into a javascript array.
var myarray=["<?php echo $menu1;?>","<?php echo $menu2;?>","<?php echo $menu3;?>","<?php echo $menu4;?>","<?php echo $menu5;?>"];
Method Two- PasteBin
Create this array server-side, this will be better if you are creating the current $menu variable in a loop, with this you can just use array_push() to push the values into the array.
<?php
// PHP Array
$menu = array('Home', 'Gallery', 'About');
// How to push new item into array
array_push($menu, 'Contact');
?>
Then just simply echo this array into your javascript myarray variable.
var myarray=<?php echo json_encode($menu);?>;
I have used the following javascript to test both methods and both seem to function just fine. I prefer the second method but I have decided to offer both as I don't know what your PHP looks like or how your $menu variables are being defined so this should cover both.
window.onload=function(){
for(var i=0; i<myarray.length; i++){
var link= document.createElement('a');
link.href="#";
link.innerHTML=myarray[i];
document.body.appendChild(link);
document.body.appendChild(document.createElement('br'));
}
}
If you have any questions about the source code above please leave a comment below and I will get back to you as soon as possible.
I hope this help. Happy coding!
Something like this would do the trick
<?php
$menu = "menu";
echo '
<script>
var count = 10;
var menu_populator="";
for(var x=1;x<=count;x++)
{
menu_populator += \'<li><a class="myclass" href="#link">'.$menu.' \'+x+\'</a></li>\';
}
$(\'#nav_menu\').html(menu_populator);
</script>
';
?>

Getting my dynamic php array to js

Here's what I got
$x=$ris;
while ($x<$rie){
array_push($array, pg_fetch_result($result,$x,0));
$x=$x+1;
}
So I'm just pushing lot's of values from a column to $array. I want to transmit the data in this array to a js array. So here's what's happening:
<script>
var temp = <?php echo json_encode($rie-$ris); ?>;
var temp2=0;
var jarray = [];
while (temp2<temp)
{
jarray.push(<?php echo json_encode($array[temp2]); ?>);
temp2++;
}
console.log(jarray)
</script>
Whenever I try to print anything out, jarray has nothing in it, which leads me to think that this
jarray.push(<?php echo json_encode($array[temp2]); ?>);
line is messed up. It's probably because I'm trying to reference a js variable in a php echo. The problem is I'm trying to make a while loop to just copy the array over, but in js, I'm incrementing a js var, so how can I possibly do this?
Try my code. First json_encode your php array and then JSON.parse in js after that while loop.
<script>
var temp = <?php echo json_encode($rie-$ris); ?>;
var temp2=0;
var jarray = [];
var arr = '<?php echo json_encode($array); ?>';
var arr_p = JSON.parse(arr);
while (temp2<temp)
{
jarray.push(arr_p[temp2]);
temp2++;
}
console.log(jarray)
</script>

How to pass a variable from php to javascript

If I pass an hard coded numeric value from php to javascript, all works perfectly. But if i pass the numeric value from a variable, i get an error:
javascript file (gallery.js)
function goto_anchor(id)
{
var anchor = $("#anchor_" + id);
$('html,body').animate({
scrollTop: anchor.offset().top - 20
}, 1200);
}
php file
....
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script src="js/gallery.js" type="text/javascript"></script><?php
$get_cat = 4;
if (isset($get_cat)) { ?>
<script>
$(document).ready(function() {
goto_anchor(4); // this will work PERFECTLY!!!
goto_anchor(<?php echo $get_cat; ?>); // this will NOT work !!!
});
</script><?php
} ?>
I need to pass the $get_cat variable in my php, not the harcoded numeric value. How ??
Thanks
I have such kind of problems before, can not fill
javascriptfunction(<?php echo $phpvirable ?>)
inside javascript function that causes error; Instead , according to your code, can echo it to javascript virable first before using it;
echo '<script> var get_cat = '.$get_cat.'</script>';
into your php
<?php $get_cat = 4; ?>
surely, Your php $get_cat can be captured from such as $_REQUEST['cat'] dynamic value from form submit event towards this page. then u convert it to javascript virable to use in function.
<?php
if(isset($getcat)):
echo '<script> var get_cat = '.$getcat.'</script>';
endif;
?>
// javascript function read predefined javascript virable that confirm work.
// u also avoid using mixed php and javascript statements which looks messy
<script>
$(document).ready(function() {
goto_anchor(get_cat); // this will work then.
});
</script>

Categories

Resources