How to render PHP output to initialise a variable in JavaScript? - javascript

I wan to call a PHP function in JavaScript code that echoes out a value:
<?php
function ex()
{
$num=10;
echo($num);
}
echo '<script type="text/javascript">
function sam_click(clicked)
{
var x="<?php ex(); ?>";
alert(x);
return false;
}
</script>'?>
However, it doesn't work. Can you help?

Try this:
<?php
function ex()
{
$num=10;
echo($num);
}
echo '<script type="text/javascript">
function sam_click(clicked)
{
var x="' . ex() . '>";
alert(x);
return false;
}
</script>'?>

Just try with:
...
var x="' . ex() . '";
...

Try echoing only what you need
<?php
function ex()
{
$num=10;
echo($num);
}
?>
<script type="text/javascript">
function sam_click(clicked)
{
var x="<?php ex(); ?>";
alert(x);
return false;
}
</script>

function ex()
{
$num=10;
echo $num;
return $num; // if you want to get JS alert
}
echo '<script type="text/javascript">
function sam_click(clicked)
{
var x='.ex().';
alert(x);
return false;
}
sam_click(); // if you want to get JS alert
</script>';

instead of echoing the $num, return it as a result and then append it in the script part.
<?php
function ex()
{
$num=10;
return ($num);
}
echo '<script type="text/javascript">
function sam_click(clicked)
{
var x="' . ex() . '";
alert(x);
return false;
}
</script>'?>

another solution with heredoc and nowdoc:
<?php
// helper to call functions as nowdoc
// example: {$fn( function() )}
function fn($functionCall)
{
return $functionCall;
}
$fn = 'fn';
function ex()
{
return 20;
}
$js = <<<EOT
<script type="text/javascript">
function sam_click(clicked)
{
var x="{$fn(ex())}";
alert(x);
return false;
}
</script>
EOT;
echo $js;
Find more detail on PHPDoc:
Nowdoc (PHP5.3+)
Heredoc
Anonymous Functions (PHP5.3+)

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"];
?>

Echo PHP code inside Javascript

I am having problem getting this to work. I am trying to echo some php code to html if the page is in an iframe. Below is a short example of the php code i try to echo (the real code i try to echo is much longer)...
<?php $pic='https://cdn.pixabay.com/photo/2015/06/19/17/58/sample-815141_960_720.jpg'; ?>
<div id="frameid"></div>
<script type="text/javascript">
function inIframe () {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
if (inIframe()) {
var node = document.getElementById('frameid');
node.innerHTML('<?php echo '<img width="100%" src="'.$pic.'"></img>'; ?>');
}
</script>
Seems there was some quotes issue. You can try the below code:
<div id="frameid"></div>
<script type="text/javascript">
function inIframe () {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
if (inIframe()) {
var node = document.getElementById('frameid');
node.innerHTML(<?php echo "...something involving html and php variables...."; ?>);
}
</script>
Can you try this?
var pic = ;
innerHTML("");
I think is more clear to separate js from php, and recomanded
You are having troubles with single quote, you may consider this function (taken from WP https://developer.wordpress.org/reference/functions/_wp_specialchars/) to escape quote (single and double)
node.innerHTML('<?php echo esc_attr('<img width="100%" src="'.$pic.'"></img>'); ?>');
where you can define
function esc_attr( $text ) {
return _wp_specialchars( $safe_text, ENT_QUOTES );
}

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
}

How to trigger js function inside php?

if (!$errors) {
//Call Js function without any events
}
I want to call js function once inside if came,How to call js function inside if condition?Is it possible to call js fucntion without any events inside php tag?
with jquery
if (!$errors) {
echo "<script type='text/javascript'>
$(document).ready(function(){
myfunction();
});
</script>";
}
without jquery and wait unlit whole page is loaded
if (!$errors) {
echo "<script type='text/javascript'>
window.onload = function() {
myfunction();
};
</script>";
}
and without Onload
if (!$errors) {
echo "<script type='text/javascript'>myfunction();</script>";
}
You can also use this way :
<?php
// php code
if(condition){
?>
<script type="text/javascript">
jsFunction();
</script>
<?php
}
// php code
?>
You can also use jquery:
if (!$errors) {
echo "<script type='text/javascript'>
$(document).ready(function(){
myfunction();
});
</script>";
}
You could just make an echo and call it between two script tags.
Like :
if (!$errors) {
echo "<script> myfunction(); </script>";
}

Call Jquery Function in Codeigniter

I have one if-else and I want to call function which contain jquery script. but its not working
Here is my codeignitor view code
Code
if($osoption == "windows")
{
?>
<script>
windows();
</script>
<?
$mysqldatabasehidden="N/A";
if ($_POST['mssqldatabasehidden']=="")
{
$mssqldatabasehidden = "1 No";
}
else
{
$mssqldatabasehidden = $_POST['mssqldatabasehidden']." No";
}
if($_POST['mssqlstoragehidden']=="")
{
$mssqlstoragehidden = "100";
}
else
{
$mssqlstoragehidden = $_POST['mssqlstoragehidden']." MB";
}
if($_POST['mssqltotalcosthidden'] =="")
{
$mssqltotalcosthidden = "3000 INR";
}
else
{
$mssqltotalcosthidden = $_POST['mssqltotalcosthidden'].".00 INR";
}
//echo ("mssql database =".$mssqldatabasehidden." <br>");
//echo ("mssql storage =".$mssqlstoragehidden." <br>");
//echo ("mssqltotalcost =".$mssqltotalcosthidden." <br>");
}
else
{
?>
<script>
linux();
</script>
<?
if($_POST['mysqldatabasehidden'] =="")
{ $mysqldatabasehidden = "0 No.";
$mysqldatabasecost="0.00 INR";
}
else
{
$mysqldatabasehidden = $_POST['mysqldatabasehidden']." No";
$mysqldatabasecost="0.00 INR";
//echo ("mysqldatabse =".$mysqldatabasehidden." <br>");
}
}
If windows selected than its call function name "windows" and same for "linux" when its in Else condition.
Here is my two functions
JQ Functions
<script>
function windows()
{
alert();
$("#divmssqldb").removeClass("divhide").addClass("divshow");
$("#divmssqlstor").removeClass("divhide").addClass("divshow");
$("#divmssqlprice").removeClass("divhide").addClass("divshow");
$("#divmysql").addClass("divhide");
}
function linux()
{
alert();
$("#divmssqldb").removeClass("divshow").addClass("divhide");
$("#divmssqlstor").removeClass("divshow").addClass("divhide");
$("#divmssqlprice").removeClass("divshow").addClass("divhide");
$("#divmysql").removeClass("divhide").addClass("divshow");
}
</script>
Remove the script which is written in your PHP code and call your functions after there definitions and declarations like,
<script>
function windows(){
alert('windows');
....
}
function linux(){
alert('linux');
....
}
$(function(){// add document ready function
<?php if($osoption == "windows") { ?> windows(); <?php } ?>
<?php if($osoption == "linux") { ?> linux(); <?php } ?>
});
</script>

Categories