issue : i am able to set and get run time variable value ?
steps: onlick button random number,
expected output :alert pop in broswer and number should be shows inside alert .
<html>
<head>
<title>Pass variable from PHP to JavaScript - Cyberster's Blog'</title>
</head>
<body>
<input type="button" value="random number " onclick="location='php2js2.php'" />
<script>
// var js_var = "<?php echo $php_var; echo $randomString ?>";
//alert(js_var);
var js_var_key = "<?php echo $RandomString(6); ?>";
alert(js_var_key);
</script>
</body>
</html>
<?php
function RandomString($length) {
$keys = array_merge(range(0,9), range('a', 'z'));
for($i=0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}
return $key;
}
#$php_var = "Hello world from PHP";
#$length = 10;
#$randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
?>
==
You should not keep $ infront of RandomString..Please remove that and check and add this .. you will find the alert with a random number
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document ).ready(function() {
var js_var_key = "<?php echo RandomString(6); ?>";
alert(js_var_key);
});
</script>
var js_var_key = "<?php echo $RandomString(6); ?>";
change this line to (remove $)
var js_var_key = "<?php echo RandomString(6); ?>";
and add
$key="" before
for($i=0; $i < $length; $i++) {
Related
<span class="cid"></span>
In the above span, i am getting id from .js file. eg., 45 and i want that id in php variable. eg., $cid='45';
I have already tried below code, but i am unable to get id.
<?php echo $cid='<span class="cid"></span>'; ?>
<?php
$str = $cid;
$DOM = new DOMDocument;
$DOM->loadHTML($str);
$items = $DOM->getElementsByTagName('span');
$span_list = array();
for($i = 0; $i < $items->length; $i++) {
$item = $items->item($i);
$span_list[$item->getAttribute('class')] = $item->nodeValue;
}
extract($span_list);
echo $cid;
?>
try this one add span text in php code to get the span value in variable
<?php
$value = '<span class="cid"></span>';
?>
echo $value
Please try the below code and check at your end you can get class value in the array.
Second time Update code
<?php
echo $cid='<span class="cid">45</span>';
?>
<?php
$str = $cid;
$DOM = new DOMDocument;
$DOM->loadHTML($str);
$items = $DOM->getElementsByTagName('span');
$span_list = '';
for($i = 0; $i < $items->length; $i++) {
$item = $items->item($i);
if($item->getAttribute('class') == 'cid'){
$span_list = $item->nodeValue;
}
}
echo $span_list;
?>
Code for multiple span tags and get single value from that span list array.
<?php
$cid='<span class="cid">45</span> <span class="cid">48</span>';
?>
<?php
$str = $cid;
$DOM = new DOMDocument;
$DOM->loadHTML($str);
$items = $DOM->getElementsByTagName('span');
$span_list = array();
for($i = 0; $i < $items->length; $i++) {
$item = $items->item($i);
if($item->getAttribute('class') == 'cid'){
$span_list[] = $item->nodeValue;
}
}
//get the each value for multiple span tag
foreach ($span_list as $key => $value) {
echo $value;
echo '<br/>';
}
?>
Add an AJAX code to pass it to PHP
$.ajax({
url: 'your_php_file.php',
method: 'POST',
data: {cid: $('.cid')[0].innerText},
success: function(result){
console.log(result);
}
})
And in your PHP file.
You can just use strip_tags
echo strip_tags($_POST['cid']);
IN Woocommerce, I use Header & Footer plugin to add on body tag a tracking affiliate code for the whole site.
The code is:
<script async src="//go.linkwi.se/delivery/js/tl.js"></script>
<script>
window.lw=window.lw||function(){(lw.q=lw.q||[]).push(arguments)};lw.l=+new Date;
lw("setProgram", "12838");
lw("setDecimal", ".");
</script>
My affiliate partner ask me the code be disabled from woocommerce thank you page (according the image - Line935 to 940).
woocommerce thank you page source code:
I think I need to add_filter action or something to disable it.
Any help will be useful for this.
UPDATE: If I remove the code from Header & Footer plugin is disabled from the whole site.
Instead of using a plugin, use the following to avoid your script to be loaded on thankyou page.
You have 2 choices:
1) On Footer (the best choice, I think):
add_action( 'wp_footer' , 'linkwi_delivery_script' );
function linkwi_delivery_script(){
// Not on thankyou page
if( is_wc_endpoint_url('order-received') ) return;
?>
<script async src="//go.linkwi.se/delivery/js/tl.js"></script>
<script>
window.lw=window.lw||function(){(lw.q=lw.q||[]).push(arguments)};lw.l=+new Date;
lw("setProgram", "12838");
lw("setDecimal", ".");
</script>
<?php
}
2) On Header:
add_action( 'wp_head' , 'linkwi_delivery_script' );
function linkwi_delivery_script(){
// Not on thankyou page
if( is_wc_endpoint_url('order-received') ) return;
?>
<script async src="//go.linkwi.se/delivery/js/tl.js"></script>
<script>
window.lw=window.lw||function(){(lw.q=lw.q||[]).push(arguments)};lw.l=+new Date;
lw("setProgram", "12838");
lw("setDecimal", ".");
</script>
<?php
}
Code goes in function.php file of your active child theme (or active theme). It should works.
So finaly my code in child function.php it look like this.
// Utility function that contain Linkwise Affiliate script
function linkwise_affiliate_scripts( $order_id ){
## --- YOUR SETTINGS START BELOW --- ##
$program_id = '12838'; // <== Your program number
$decimal_sep = '.'; // Decimal separator
$currency = '978'; // For "EUR" => See: https://en.wikipedia.org/wiki/ISO_4217
## --- END SETTINGS --- ##
$order = wc_get_order( $order_id );
$order_status = $order->get_status();
$items_string = array();
$count = 0;
?>
<script async src="//go.linkwi.se/delivery/js/tlwt.js"></script>
<script>
window.lw=window.lw||function(){(lw.q=lw.q||[]).push(arguments)};
lw .l=+new Date;
lw("setProgram", "<?php echo $program_id; ?>");
lw("setDecimal", "<?php echo $decimal_sep; ?>");
</script>
<script>
lw("setCurrency", "<?php echo $currency; ?>"); // Set your currency
<?php
foreach( $order->get_items() as $item ):
$count++;
$item_id = $item->get_id(); // The item ID
// Get an instance of the WC_Product object
$product = $item->get_product();
$product_id = $item->get_product_id(); // Product ID
$price_excl_vat = wc_get_price_excluding_tax( $product ); // Unit price excluding VAT
$item_qty = $item->get_quantity(); // Item quantity
$payout = '1'; // (???)
// The string for the <noscript> at the bottom
$items_string[] = "itemid[$count]=$item_id&itemprice[$count]=$price_excl_vat&itemquantity[$count]=$item_qty&a
mp;itempayout[$count]=$payout";
?>
lw("addItem", {
id: "<?php echo $item_id; // Or can be the product ID (may be) ?>"
,price: "<?php echo $price_excl_vat; ?>"
,quantity: "<?php echo $item_qty; ?>"
,payout: "<?php echo $payout; ?>"
});
<?php
endforeach;
// Set the array of items strings in a unique string
$items_string = implode( '&', $items_string );
?>
// Other items types
<?php
$coupon_discounts = $coupon_discounts_tax = 0;
foreach( $order->get_items('coupon') as $item_coupon ){
$coupon_discounts += $item_coupon->get_discount();
$coupon_discounts_tax += $item_coupon->get_discount_tax();
}
?>
lw("setCoupon", "<?php echo $coupon_discounts; ?>");
lw("thankyou", {
orderid: "<?php echo $order_id; ?>"
,status: "<?php echo $order_status; ?>"
});
</script>
<noscript>
<img
src="//go.linkwi.se/delivery/acl.php?program=<?php echo $program_id; ?>&decimal=<?php echo $decimal_sep; ?>&<?php echo $items_string; ?>&coupon_price=<?php echo $coupon_discounts; ?>&status=<?php echo $order_status; ?>&orderid=<?php echo $order_id; ?>" style="width:0px;height:0px;"/>
</noscript>
<?php echo 'test';
}
add_filter( 'wp_footer', 'wc_linkwise_affiliate_order_received_integration' );
function wc_linkwise_affiliate_order_received_integration() {
if ( ! is_wc_endpoint_url( 'order-received' ) )
return; // Exit
global $wp;
$order_id = absint( $wp->query_vars['order-received'] );
if ( empty($order_id) || $order_id == 0 )
return; // Exit
linkwise_affiliate_scripts( $order_id ); // Run the Linkwise Affiliate
}
add_action( 'wp_footer' , 'linkwi_delivery_script' );
function linkwi_delivery_script(){
// Not on thankyou page
if( is_wc_endpoint_url('order-received') ) return;
?>
<script async src="//go.linkwi.se/delivery/js/tl.js"></script>
<script>
window.lw=window.lw||function(){(lw.q=lw.q||[]).push(arguments)};lw.l=+new Date;
lw("setProgram", "12838");
lw("setDecimal", ".");
</script>
<?php
}
How to create var javascript via php ?
<?PHP
include("connect.php");
$get_data = mysqli_query($db_mysqli,"SELECT * FROM bad_word");
while($resilt_row = mysqli_fetch_array($get_data))
{
$bad_words = $bad_words."".$resilt_row [word].",";
}
//echo $bad_words;
?>
<script>
var bad_words = ["<?PHP echo $bad_words; ?>"];
alert(bad_words);
</script>
I want to get var javascript like this var bad_words = ["fuck", "ass"];
When alert it's get only blank result.
How can i do that ?
<?php
include("connect.php");
$query = mysqli_query($db_mysqli,"SELECT * FROM bad_word");
$badWords = [];
while($row = mysqli_fetch_array($query))
{
$badWords[] = $row['word'];
}
js
<script>
var bad_words = <?= json_encode($badWords); ?>;
alert(bad_words[0]);
console.log(bad_words);
</script>
I don't like gluing the strings if it's an array then pass it as an array with json_encode() function. Also in views it's better to use short syntax with <?= ?> tag
The string you're making is not the one you want.
You're not adding quotes.
Do this instead, using an array is better:
$get_data = mysqli_query($db_mysqli,"SELECT * FROM bad_word");
$bad_words = array();
while($resilt_row = mysqli_fetch_array($get_data))
{
$bad_words[] = "'" . $resilt_row[word]. "'";
}
And then, down in your js:
var bad_words = ["<?php echo implode(",", $bad_words) ?>"];
or (for short)
var bad_words = ["<?= implode(",", $bad_words) ?>"];
If you want alert them as a string you can do it like this:
<script>
var bad_words = ["<?php echo implode('","',$bad_words); ?>"];
alert(bad_words);
</script>
Otherwise, you can print them as an array:
<script>
var bad_words = <?php echo json_encode($bad_words) ?>;
console.log(bad_words);
</script>
<?PHP
include("connect.php");
$get_data = mysqli_query($db_mysqli,"SELECT * FROM bad_word");
while($resilt_row = mysqli_fetch_array($get_data))
{
$bad_words[] = $resilt_row['word'];
}
//echo $bad_words;
?>
<script>
var bad_words = ["<?php print implode('","',$bad_words); ?>"];
alert(bad_words);
</script>
My php invoicing system uses jQuery autocomplete to lookup a customer's name from my database. The layout of the pages is like this:
invoice.php - contains the variable 'customers' and the php database select script
invoice.js - this contains the jQuery on focus command
In Safari everything works fine. I have used the console to see the variables logged - example (CUSTOMERS – ["Paul Smith"] (1))
But in Chrome and Firefox the console shows: "CUSTOMERS" Array [ ]
My code for invoice.php:
var arr_customers = new Array();
<?php $result = mysql_query("select * from customer where breaker='".$_SESSION['breaker_id']."'");?>
<?php $str = ""; $i = 0; while ($row = mysql_fetch_array($result)) { ?>
arr_customers[<?php echo $i;?>] = new Array();
arr_customers[<?php echo $i;?>][0] = "<?php echo $row['customer_name']; ?>";
arr_customers[<?php echo $i;?>][1] = "<?php echo $row['customer_code']; ?>";
arr_customers[<?php echo $i;?>][2] = "<?php echo $row['address']; ?>";
arr_customers[<?php echo $i;?>][3] = "<?php echo $row['uid']; ?>";
<?php if ($i == 0) {
$str = "'" . $row['customer_name'] . "'";
} else {
$str = $str . ",'" . $row['customer_name'] . "'";
}?>
<?php $i++;
} ?>
var customers =<?php echo ("[" . $str . "]") ?>;
and for the invoice.js:
jQuery(document).ready(function($) {
$("#customer_name").on('focus', function() {
console.log("CUSTOMERS", customers);
$( "#customer_name" ).autocomplete({
source: customers
});
});
});
I know I should be using prepared statements as well!
Below is my textbox values....i am unable to put my screen shots here..
i used multiple input tag jquery from this site..
http://loopj.com/jquery-tokeninput/demo.html
and second option of this demo. plz visit demo link ...
but i used multiple input textbox..in which we select multiple tags in one textbox okay.
like 700X 701X 702X
I need to get this textbox value and store in 3 rows..
FOR EX - in above screenshot there are 3 values 700,701,702 ok...now i need to ask you...when i click save i need to store this values in 3 different rows...
Rows No - used_receipt
1 700
2 701
3 702
i try like below but wont work...
textbox code
<input id="demo-input-local" type="text" value="<?php echo $data['used_receipt'];?>" name="used_receipt" />
javascript
<script type="text/javascript">
$(document).ready(function() {
$("#demo-input-local").tokenInput([
<?php
$receipt = $database->getRows("SELECT DISTINCT SM.receipt_no FROM scheme_master SM Inner join book_issue BI ON BI.book_no = SM.Book_no2 where SM.receipt_no not in (select used_receipt from book_return)");
foreach($receipt as $row){ ?>
{name: "<?php echo $row['receipt_no']; ?>"},
<?php } ?>
]);
});
</script>
php code to insert multiple values in database
$used_receipt = $_POST['used_receipt'];
$arr = explode(",", $used_receipt);
$max = count($arr);
for ($i = 0; $i < $max; $i++)
{
$insertrow = $database->insertRow("INSERT INTO book_return (book,surveyor,used_receipt,city,return_date,created)
VALUES (:book,:surveyor,:used_receipt,:city,:return_date,:created)",
array(':used_receipt'=>$arr[$i]);
}
Instead of
foreach($receipt as $row){ ?>
{name: "<?php echo $row['receipt_no']; ?>"},
<?php } ?>
Try this
$r = array();$i=1;
foreach($receipt as $row){
$r[]['name'] = $row['receipt_no'];$r[]['id'] = $i++;
}
echo "JSON.parse(\"".json_encode($t)."\")";
below is script which i used
<script type="text/javascript">
$(document).ready(function() {
$("#demo-input-local").tokenInput([<?php
$receipt = $database->getRows("SELECT DISTINCT SM.receipt_no FROM scheme_master SM Inner join book_issue BI ON BI.book_no = SM.Book_no2");
foreach($receipt as $row){ ?>
{id:<?php echo $row['receipt_no']; ?>,name: "<?php echo $row['receipt_no']; ?>"},
<?php } ?>
]);
});
</script>
and get this input in like
$used_receipt = $_POST['used_receipt'];
$arr = explode(",", rtrim($used_receipt));