On page ready, get Javascript array created during dom creation - javascript

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>

Related

How to set js variable in php and save it into data base

I create new variable and next code is add value to this variable. This code have Load (working) and dont working save i try to fix search google and i dont know
<?php
session_start();
?>
<script type="text/javascript">
var drzewo = 0;
var ustdrzewo = 1;
/* L O A D */
function wczytaj() {
drzewo = <?php echo $_SESSION['drewno']; ?>;
ustdrzewo = <?php echo $_SESSION['ustdrzewo']; ?>;
document.getElementById("drzewo").innerHTML = drzewo;
document.getElementById("ustdrzewo").innerHTML = ustdrzewo;
}
/* S A V E */
function zapisz() {
<?php
$_SESSION['drewno'] = "<script type='text/javascript'> document.getElementById('drzewo').innerHTML = drzewo; </script>"
?>
window.location.href = "zapis.php"
}
function addwood() {
drzewo +=ustdrzewo
document.getElementById("drzewo").innerHTML = drzewo;
}
<script type="text/javascript">
//include jquery
$.post( "other.php", { drewno: drzewo } );
</script>
other.php
<?php
$_SESSION['drewno'] = $_POST["drewno"];
?>

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
}

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>

Output do_shortcode in JavaScript variable

The do_shortcode is not replying me anything.
It should reply me the shortcode value, but when I use this same( only the PHP script) in PHP file it's replying me the value.
But while I'm pushing it in JavaScript variable then it is not replying me anything.
<script>
function append2(){
var video2;
video2='<?php
$custom_fields = get_post_custom();
$mykey_values = $custom_fields['wpcf-picture-movie-link'];
foreach ( $mykey_values as $key => $value ) {
if($value!=''){
do_shortcode($value) ;
}
}
?> ';
$("#hide_video2").append(video2);
}
</script>
Try this code:-
<script>
function append2(){
var video2;
video2='<?php
$custom_fields = get_post_custom();
$mykey_values = $custom_fields['wpcf-picture-movie-link'];
foreach ( $mykey_values as $key => $value ) {
if($value!=''){
echo do_shortcode($value) ; // echo the shortcode
}
}
?> ';
$("#hide_video2").append(video2);
}
</script>

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 :)

Categories