Php foreach and echo inside javascript - 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>

Related

Javascript - How to pull a WooCommerce variable in PHP?

I'm trying to execute some PHP code that is using the WooCommerce variable to get the order ID.
add_action('add_meta_boxes', 'gen_order_meta_boxes');
function gen_order_meta_boxes()
{
add_meta_box(
'woocommerce-order-gen',
__( 'TESTNG' ),
'order_meta_box_gen',
'shop_order',
'side',
'default'
);
}
function order_meta_box_gen()
{
echo '<button class="button save_order button-primary alert-mass">Generate</button>';
}
add_action('admin_footer', 'lolcats');
function lolcats()
{
$order = new WC_Order($post_id);
?>
<script type="text/javascript" >
jQuery(document).ready(function($)
{
$(".alert-mass").click(function(e)
{
e.preventDefault();
alert('<?php echo $order->get_order_number; ?>');
});
});
</script>
<?php
}
I can't seem to get it to return anything besides either null or 0.
Using something like this obviously works perfectly: window.location="dhlgen.php?order=1234"; because I'm trying to pass it through the URL to a PHP function which uses it later.
This also seems to fail, but it returns 'false':
function lolcats($post_id)
{
$order = new WC_Order($post_id);
?>
<script type="text/javascript" >
jQuery(document).ready(function($)
{
$(".alert-mass").click(function(e)
{
e.preventDefault();
var data = <?php echo json_encode($order->shipping_first_name); ?>;
alert(data);
});
});
</script>
<?php
}
Thank you.
Okay, I solved it.
function lolcats()
{
global $post;
$order_id = $post->ID;
?>
<script type="text/javascript" >
jQuery(document).ready(function($)
{
$(".alert-mass").click(function(e)
{
e.preventDefault();
alert('<?php echo $order_id; ?>');
});
});
</script>
<?php
}

On page ready, get Javascript array created during dom creation

I am creating a Javascript array during dom creation using arr.push.
However, on page ready function, it returns an empty array.
<script type="text/javascript">
var short_urls = [];
</script>
$(document).ready(function() {
console.log(short_urls);
});
<?
foreach ($d_json['result'] as $key => $value) {
?>
<script>
short_urls.push("<? echo $shorten_url ?>");
</script>
<?
}
?>
<script type="text/javascript">
var short_urls = [];
$(document).ready(function() {
console.log(short_urls);
});
</script>
<?
foreach ($d_json['result'] as $key => $value) {
?>
<script>
short_urls.push("<? echo $shorten_url ?>");
</script>
<?
}
?>
As PHP will be executed before any javascript you can write the javascript variables out without needing to use the array.push method. However, the question used a php variable $shorten_url - where is that defined? I assume it is the value from the foreach loop
Approach #1
-----------
<script type="text/javascript">
var short_urls = [];
<?php
foreach( $d_json['result'] as $key => $value ) {
$shorten_url='???';
echo "short_urls.push('{$shorten_url}');";
}
?>
$( document).ready( function() { console.log( short_urls ); } );
</script>
Approach #2
-----------
<script type="text/javascript">
<?php
$tmp=array();
foreach( $d_json['result'] as $key => $value ) {
$shorten_url='???';
$tmp[]=$shorten_url;
}
echo "var short_urls = ['".implode("','",$tmp)."'];";
?>
$( document).ready( function() { console.log( short_urls ); } );
</script>

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>

Change value of html div using javascript in php foreach

I am running a foreach loop and I want to be able to change the content and class of the affected div elements.
foreach ($fields as $key => $value) { ?>
<script type="text/javascript">
document.getElementById('<?php echo $key ?>').innerHTML = '<?php echo $value ?>';
</script>
<?php } ?>
foreach ($fields as $key => $value) { ?>
<script type="text/javascript">
document.getElementById('<?php echo $key ?>').innerHTML = '<?php echo $value ?>';
</script>
you better use it like this .
<script>
<?php foreach ($fields as $key=>$value){ ?>
document.getElementById("<?php echo $key; ?>").innerHTML = "<?php echo $value; ?>";
<?php } ?>
</script>
and make sure you have all correspoinding elements with the same id as $key in this script for example.
<?php foreach($fields as $key=>$value){ ?>
<div id="<?php echo $key; ?>" ></div>
<?php } ?>
Regards
You may use only one part...
server-side with PHP and more tempting
client-side with Javascript
For the last approach, it could be okay to store / request the array as an JavaScript array, or json object and iterate it / update the existing elements during a loop after the site has been loaded.
A mixture of both may lead to a non-maintainable source and more render and execution time as expected.
I have not got what you actually want, But lets with this code. It may help you...
<script type="text/javascript">
$( document ).ready(function() {
<?php
foreach ($fields as $key => $value) {
?>
document.getElementById('<?php echo $key ?>').innerHTML = '<?php echo $value ?>';
<?php
}
?>
});
</script>

Pass JS value in php

How can I send JavaScript variable value in php?
Like :
for(var j=0;j<count_array_item;j++){
get_item = <?php echo json_encode($cld[???]['title']); ?>; //want to get 'j' value.
}
Try this code. foreach loop store the value in js get_item array.
<script type="text/javascript" language="javascript">
var get_item = new Array();
<?php foreach($cld as $val){ ?>
get_item.push('<?php echo json_encode($val["title"]); ?>');
<?php } ?>
</script>

Categories