Javascript variable not working in php echo - javascript

My code :
<?php echo ' <script>var p=0;for(var i=0;i<=5;i++){p++;}alert("ques".p);? >
The value of p is displayed as 0.

You need to close your php tag properly as well as the <script> tag like so:
<?php echo '<script>var p=0;for(var i=0;i<=5;i++){p++;}alert("ques" +p);</script>'; ?>
Also, change the . to a + as you are concatenating in javascript not PHP

The correct answer is:
<?php echo '<script>var p=0;for(var i=0;i<=5;i++){p++;}alert("ques" + p)'; ?>

Strings in single quotes will be escaped, use quotation marks instead.
<?php echo "<script>var p=0;for(var i=0;i<=5;i++){p++;}alert('ques' +p);</script>"; ?>

The mistakes in your code are,
Close your php tag properly - ?> instead of ? >
Close the script tag in the end - </script>
Close the single quote you started with echo
The correct code would be
<?php echo '<script>var p=0;for(var i=0;i<=5;i++){ p++; } alert("ques" + p); </script>'; ?>

Related

JS Script link accepting PHP variables and showing %27

I have a <script> link were I pass vaiables into it however on the network tab in the console its showing %27 why?
Code:
type=calculator&min=50&max=400&amount='".<?php echo $price;?>.
Full Code:
<div class="col-md-4">
<?php if($product->is_on_sale())
{
$price = $product->get_sale_price();
echo 'sale';
}else{
$price = $product->get_price();
echo 'Normal';
}
echo 'The Price is:'. $price;
?>
<script async src="widget-0.1.0.js?type=calculator&min=50&max=400&amount=".<?php echo $price;?>" type="application/javascript"></script>
As Satpal says, encoded value of ' is %27
remove the single quote like:
type=calculator&min=50&max=400&amount=".<?php echo $price;?>
as it is also useless in your query string so you can remove it, and try again.
Edited: Instead of:
type=calculator&min=50&max=400&amount=".<?php echo $price;?>"
try
type=calculator&min=50&max=400&amount=<?php echo $price; ?>"
You can use like this .remove space if it is present .
<?php
$price = 27;
?>
<script src="http://testSite.com/resources/js/animatedcollapse.js?type=calculator&min=50&max=400&amount=<?php echo $price;?>" type="text/javascript"></script>
You have mentioned the single quotes in code block.But there is not single quotes in script attributes.And also you need to remove dot and try like this:
<script async src="widget-0.1.0.js?type=calculator&min=50&max=400&amount="<?=$price?>" type="application/javascript"></script>

Pass a php variable to a jQuery function

I have searched and tried several different methods to pass a php $variable to a jQuery function. I can pass a string simply by using myfunction("Hello");. But if I try myfunction(); or myfunction($variable); with or without quotes it fails to run.
function wholesection(val) {
$("#whole-section").slideUp("fast", function () {
});
$('#label-cemetery').text("Section*");
$('#poc').val(val);
}
The above works if I send a literal string enclosed in double quotes, using:
<?php
echo '<script>',
'wholesection("Hello");',
'</script>'
;
?>
</head>
<body>
<?php
$variable = "Hello";
echo '<script>',
'wholesection(' . $variable . ');',
'</script>'
;
?>
Or other similar variants do not work.
'wholesection($variable);',
'wholesection("$variable");',
Suppose your $variable has value "Hello".
Then this code:
echo 'wholesection('.$variable.');',
is rendrered in html like
wholesection(Hello);
See? You're passing Hello to a function. Not "Hello" but Hello.
And Hello is considered a javascript variable. I bet you don't have it.
So, the fix is - add quotes:
echo 'wholesection("'.$variable.'");',
which will be rendered as:
wholesection("Hello");
You can pass it by echoing your php varriable in the script
try below code :
<?php
$variable = "Hello";
?>
<script type="text/javascript">
var simple = '<?php echo $variable; ?>';
</script>
<?php
$variable = "Hello";
if(true){
?>
<script>
wholesection("<?php echo $variable?>");
</script>
<?
}
?>

qtip and html data in title="" is causing conflict

I'm trying to load html content into visjs timeline and using qtip2 to display a tooltip when a hyperlink inside a timeline is clicked. This tooltip needs to display html content, so it has "" in it, which causes a problem when its inserted into a title="". Normally i would be able to use a single quote in the title='<-html - content->' so it should be able to handle the quotes. But now i'm facing a problem, because i'm trying to do this from inside javascript which already uses a single quote from the javascript itself.
if i want to add a item to visjs timeline, i need to insert new items to the timeline like this.
{id: <?php echo $key; ?>, group: <?php echo $aspects['group'][$key]; ?>, content: '<a title="<?php if(isset($aspects['interpretation'][$key])): echo $aspects['interpretation'][$key]; endif;?>" role="button"><?php echo $aspects['symbols'][$key]; ?></a>', start: new Date(<?php echo $aspects['dates']['start'][$key]['year']; ?>, <?php echo $aspects['dates']['start'][$key]['month'] - 1;?>, <?php echo $aspects['dates']['start'][$key]['day'];?>, <?php echo $aspects['dates']['start'][$key]['hour'];?>, <?php echo $aspects['dates']['start'][$key]['min'];?>), end: new Date(<?php echo $aspects['dates']['end'][$key]['year']; ?>,<?php echo $aspects['dates']['end'][$key]['month'] - 1; ?>, <?php echo $aspects['dates']['end'][$key]['day']; ?>, <?php echo $aspects['dates']['end'][$key]['hour']; ?>, <?php echo $aspects['dates']['end'][$key]['min']; ?> ) },
But as you can see, content:' href etc ' already uses a single quote. So how can i escape this html quotes so it doesn't cause a conflict? I tried things like title = \" \" in the href, but i am not finding any solution yet to solve my problem.
You should use htmlspecialchars before outputting your PHP variables.
Try using templating strings in JavaScript.
var string = `hello " and ' work in this string`;

How to retrieve $_SESSION value in a JavaScript/HTML

I have this working script yet when I change it to retrieve(supposedly) the value inside $_SESSION["username"], it doesn't retrieve anything. The whole page is saved as .php as I am using some codes that uses PHP.
Code:
echo "<script type=text/javascript>";
echo "var hidden = false;";
echo "function actiondb1() {";
echo "if(!hidden) {";
echo "document.getElementById(\'clickdb1\').style.visibility = \'hidden\';";
echo "document.getElementById(\'db1\').style.visibility = \'visible\';";
echo "document.getElementById(\'db1\').disabled = false;";
echo "document.getElementById(\'db1\').value =".$_SESSION["username"];.";";
echo "}";
echo "}";
echo "</script>";
How can I make the script to properly retrieve the data inside $_SESSION["username"];?
Observe that, for instance, if the value of $_SESSION["username"] is John, your echo will be generating this result:
document.getElementById('db1').value = John;
But John is supposed to be a string and should be wrapped in quotation marks, otherwise JavaScript will understand it as a variable name (which value will be probably undefined).
As Havenard mentioned, this line is missing Javascript single quotes to properly denote a string variable:
echo "document.getElementById(\'db1\').value ='".$_SESSION["username"];."';";
However, you really shouldn't print JS out with PHP if you can help it. Though iatboy's answer answer won't ultimately fix your bug, it is a much cleaner way of doing things.
?>
<script type=text/javascript>;
var hidden = false;
function actiondb1() {
if(!hidden) {
document.getElementById('clickdb1').style.visibility = 'hidden';
document.getElementById('db1').style.visibility = 'visible';
document.getElementById('db1').disabled = false;
document.getElementById('db1').value ='<?php echo $_SESSION["username"];?>';
}
}
</script>;
<?php
Did you start session in this page?If you didn't,use the follow code to start session.
session_start();
Then change your code to
echo "<script type=text/javascript>";
echo "var hidden = false;\n";
echo "function actiondb1() {\n";
echo "alert('".$_SESSION['username']."')\n"; //test code
echo "if(!hidden) {\n";
echo "document.getElementById('clickdb1').style.visibility = 'hidden';\n";
echo "document.getElementById('db1').style.visibility = 'visible';\n";
echo "document.getElementById('db1').disabled = false;\n";
echo "document.getElementById('db1').value ='".$_SESSION["username"]."';\n";
echo "}\n";
echo "}\n";
echo "</script>";
it will be ok.

Add div class with php in jQuery

My variable contains a color name. My example:
<?php
$myvar = blueColour;
?>
I need to add this value to body of a html page using jQuery:
<script type="text/javascript">
jQuery(body).addClass("<?php echo $myvar; ?>");
</script>
Can I use php inside jQuery this way? Thank you.
EDIT: its an wordpress site. I use this in a if to add that class on a specific page template.
<script type="text/javascript">
jQuery("body").css("color", "<?php echo $myvar; ?>");
</script>
yes, as long as your html file is interpreted by php (having .php/.phtml extension)
I did it. Worked.
Correct is:
jQuery('body').addClass("<?php echo $myvar; ?>");
with
jQuery('body')
not
jQuery(body)
if ( is_page_template('nameOfYouTemplate.php') ) {
echo '<body class='. $myvar .'>';
} else {
echo '<body>';
}

Categories

Resources