I have a PHP Session variable which can be 0 or 1 and this JS function:
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
I would like this function to be run AUTOMATICALLY as soon as the page is opened only if the PHP Session Variable is = 0.
How and where can I create my If statement?
One of the simpliest is just handle it like any normal code block. Add your condition in the if statement.
Basic idea:
<!-- head -->
<?php if($_SESSION['whatever'] === 0): ?>
<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
toggle_visibility('body');
</script>
<?php endif; ?>
<!-- your HTML content, etc. -->
<!-- footer, etc. -->
If $_SESSION['whatever'] is not 0, after all is loaded, then you'll not see this JS code block in the page because remember PHP runs first.
Note: Don't forget to start the session.
Additional Note: Of course, another way would be to create an XMLHttpRequest. You'd need another PHP script that responds to this request. Just respond with a json_encoded response. This answer (vanilla) should give a better illustration.
You could let PHP generate the JS code, you'd then get something like this
<script>
<?php
session_start();
if($_SESSION["name"]=="value"){
echo"document.getElementById('id').style.display='none';";
}
?>
</script>
<?php
$execJs = "false";
session_start();
if (isset($_SESSION['variable']) && $_SESSION['variable'] === 0) {
$execJs = "true";
}
?>
<script>
var id = 'whatever';
var execJs = "<?php echo $execJs ?>";
if (execJs === 'true') {
toggle_visibility(id);
}
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
You could use the following technique :
<?php
if($_SESSION['shouldbezero'] === 0) {
echo '<script src="shouldbezero.js"></script>';
}
?>
The echo statement would run only if the value of $_SESSION['shouldbezero'] is equal to 0, and thus the <script> tag will only be added to your HTML code in that specific situation.
If you use this technique, you should also create a file named shouldbezero.js, which should contain all the JavaScript code you only want to run if the value of $_SESSION['shouldbezero'] is equal to 0.
Note :
If you only want to load CSS based on a certain value in your PHP code, could do the same thing with that CSS code.
For example, you could add echo <link rel="stylesheet" type="text/css" href="shouldbezero.css">'; right beneath the echo '<script src="shouldbezero.js"></script>';, as demonstrated in the code example below :
<?php
if($_SESSION['shouldbezero'] === 0) {
echo '<script src="shouldbezero.js"></script>';
echo '<link rel="stylesheet" type="text/css" href="shouldbezero.css">';
}
?>
If you do this, you should also create a file named shouldbezero.css, which should contain all the CSS code you only want to process if the value of $_SESSION['shouldbezero'] is equal to 0.
Related
I cant seem to get the following code to work;
function add_js_functions(){
$gpls_woo_rfq_cart =
gpls_woo_rfq_get_item(gpls_woo_rfq_cart_tran_key() . '_' . 'gpls_woo_rfq_cart');
if(is_array($gpls_woo_rfq_cart)){
$count = count($gpls_woo_rfq_cart);
}else{
$count = 0;
}
?>
<script type="text/javascript">
var getQuoteIcon = document.getElementsByClassName("icon-account");
if(1 != 0) {
getQuoteIcon[0].style.display = "none";
}
</script>
<?php }
add_action('init','add_js_functions');
The php above the script stores a variable from the quote form on the number of items in the form.
I tried the javascript by itself and its seemed to work but its not working in the functions file.
At the moment im using (1 != 0) to make sure its true and to hide the item so I know the JS works, what will happen afterwards is this will become;
if (<?php $count != 0 ?>) {
//rest of the JS here
}
So that when the page loads, if the form is empty of items then this icon will be hidden (it starts off as inline-block and i dont know how to change this).
I think you want your php to be <?php echo $count != 0 ?>.
Your PHP is executed server-side, and Javascript client side, the two don't communicate by passing variables between the two. In order to get your PHP variable into your Javascript, you need to echo it.
It looks like you are loading the JS too soon and the element you are targeting isn't available yet.
Use add_action('wp_footer') to load the JS in the footer.
function add_js_functions(){
$gpls_woo_rfq_cart =
gpls_woo_rfq_get_item(gpls_woo_rfq_cart_tran_key() . '_' . 'gpls_woo_rfq_cart');
if(is_array($gpls_woo_rfq_cart)){
$count = count($gpls_woo_rfq_cart);
}else{
$count = 0;
}
?>
<script type="text/javascript">
var getQuoteIcon = document.getElementsByClassName("icon-account");
if(1 != 0) {
getQuoteIcon[0].style.display = "none";
}
</script>
<?php }
add_action('wp_footer','add_js_functions');
Hello I am trying to utilize geomapping within in my website and I'm having trouble dynamically pulling the address for a restaurant and putting it into my javascript. I am using the get method to pull the restaurant_id from the url and then use this to pull the restaurant's complete address. This is the line of code I am having trouble with (var destinationAddress):
$con=mysqli_connect("root","");
$rest_id2=$_GET['id'];
$rest_id=(int)$rest_id2;
$sql="SELECT * from restaurant WHERE restaurant_id='".$rest_id."'";
$result=mysqli_query($con,$sql);
$rows=mysqli_fetch_assoc($result);
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script>
$(document).ready(function() {
//exit early if no geolocation
if(!navigator.geolocation) return;
var destinationAddress = "<?php echo $rows['address'].$rows['city'].$rows['state'].$rows['zip']; ?>";
</script>
</head>
....
Any one know see what I am doing wrong here?
Make your life easier: build the destination address outside of the template:
$rows=mysqli_fetch_assoc($result);
if( $rows !== NULL )
{
$destinationAddress = "{$rows['address']}, {$rows['city']}, {$rows['state']}, {$rows['zip']}";
}
else
{
// no rows! (anomaly)
$destinationAddress = "no destination address available";
}
// due to the way you'll later inject the variable
// into JavaScript code double quotes must be escaped
$destinationAddress = str_replace( '"', '\"', $destinationAddress );
Then simply
$(document).ready(function() {
//exit early if no geolocation
if(!navigator.geolocation) return;
var destinationAddress = "<?=$destionationAddress?>";
} );
Try adding the commas and spaces.
var destinationAddress = "<?php echo $rows['address'].$rows['city'].$rows['state'].$rows['zip']; ?>";
becase u forgot to close the function }) , try
<script>
$(document).ready(function() {
//exit early if no geolocation
if(!navigator.geolocation) return;
var destinationAddress = "<?php echo $rows['address'].$rows['city'].$rows['state'].$rows['zip']; ?>";
})
</script>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Here is my php code:
<div class="box-body" id="chosen-tags">
<?php
$cnt = 1;
for($cnt=1;$cnt<=20;$cnt++){
echo "<a id='abcd$cnt' style='float:left;'>abcd".$cnt." </a>";
}
?>
</div>
<div class="box-body" id="tags-toggle-content" style="display: none">
<?php
$cnt = 1;
for($cnt=1;$cnt<=20;$cnt++){
$idd = "abcd".$cnt;
echo "<a id='abc$cnt' style='float:left' onclick='add_tagss($idd)'>abc".$cnt." </a>";
}
?>
</div>
Here is my Javascript Code:
<script type="text/javascript">
function toggle_visibility(id)
{
var f = document.getElementById(id)
if(f.style.display == 'block')
f.style.display = 'none';
else
f.style.display = 'block';
}
function add_tagss()
{
var f = document.getElementById("id");
f.style.display = 'none';
}
</script>
I really think that my error is on my function call inside a echo. Is there any rule on how to execute a function call inside a echo such as the proper usage of single and double quote.
You are messing up with single and double quotes.
Whenever you think you are messing up with javascript and PHP, break the string.
Its not mandatory to echo a string within double quotes at one go.
You can do several concatenations to achieve the same.
Best practice while writing javascript code in PHP is:
1) View source code to find out whether javascript code is properly coded. Of course, view source will not display AJAX generated code. Use Firefox's Inspect Element in this case.
2) Check if parameters of javascript functions are passed properly with single quotes.
3) In Firefox, check in console tab if PHP written javascript code is generating some errors.
4) In javascript function, use console.log() to check if proper variable is passed.
Some modifications:
Change
echo "<a id='abc$cnt' style='float:left' onclick='add_tagss($idd)'>abc".$cnt." </a>";
To:
echo "<a id='".$idd."' style='float:left'" . "onclick=add_tagss('".$idd."')>abc".$cnt." </a>";
And in function you are not receiving any parameter:
Change it to:
function add_tagss(id)
{
var f = document.getElementById(id);
f.style.display = 'none';
}
you are calling pa parameterised function but its defination doesn't have the parameter, look for this add_tagss('param');
call add_tagss(".$idd."); instead onclick='add_tagss($idd)' and definition should accept parameter. Hope this might help you.
Try this, in second for lop - where you add function call in anchor tag - try below script - it will successfully call function :
for($cnt=1;$cnt<=20;$cnt++)
{
$idd = "abcd".$cnt;
echo "<a href='#' id='abc$cnt' style='float:left;' onclick='add_tagss(\"".$idd."\")'>abc".$cnt." </a>";
}
<div class="box-body" id="chosen-tags">
<?php
$cnt = 1;
for($cnt=1;$cnt<=20;$cnt++)
{
echo "<a id='abcd$cnt' style='float:left;'>abcd".$cnt." </a>";
}
?>
</div>
<hr />
<div class="box-body" id="tags-toggle-content" style="display: block">
<?php
$cnt = 1;
for($cnt=1;$cnt<=20;$cnt++)
{
$idd = "abcd".$cnt;
echo "<a id='abcd$cnt' style='float:left' onclick='add_tagss(\"$idd\")'>abc".$cnt." </a>";
}
?>
</div>
<script type="text/javascript">
function toggle_visibility(id)
{
var f = document.getElementById(id)
if(f.style.display == 'block')
f.style.display = 'none';
else
f.style.display = 'block';
}
function add_tagss(idd)
{
var f = document.getElementById(idd);
f.style.display = 'none';
}
</script>
Does anyone know how to hide and show options under select-tag depending on a certain value from database?
Here's what I did but it doesn't work:
<script>
var a = <?php echo $row["status"]; ?>
if(a == 'To be check' || a == 'Endorsed By IT') {
$("#new").show();
} else
$("#new").hide();
</script>
Here's what's under #new:
<div id="new">
<select name="status">
<option value="Request">Request</option>
<option value="Upload">Upload</option>
</select>
</div>
As of your problem b0s3 has the answer. Besides that, I would recommend a different way to handle this problem:
Try to modify the HTML markup while rendering instead of your altering your JavaScript:
<div id="new" <?print ( in_array($row["status"], array('To be check', 'Endorsed By IT')) ? 'class="active"' : ''); ?>
[…]
</div>
You can use a CSS class like:
#new { display: none; }
#new.active { display: block; }
You can still alter the visibility later by using:
document.getElementById('new').classList.toggle('active'); // vanilla JS
$('#new').toggleClass('active'); // jQuery
The advantages are:
The element is hidden right away and won't be visible to the user if your page loads slowly (for whatever reason).
The JavaScript code could be kept and maintained separately from your template, as it doesn't have to be modified by PHP.
Missing the quotes. $row["status"] contains string. You should add the quotes properly.
<script>
var a = '<?php echo $row["status"]; ?>'; // missing the quotes here
if(a == 'To be check' || a == 'Endorsed By IT')
{
$("#new").show();
}
else
$("#new").hide();
</script>
To show/hide div using javascript, you can write like :
<script>
var a = '<?php echo $row["status"]; ?>';
if(a == 'To be check' || a == 'Endorsed By IT')
{
document.getElementById(new).style.display = 'block';
}
else
document.getElementById(new).style.display = 'none';
</script>
Try this:-
<script>
var a = '<?php echo $row["status"]; ?>';
if(a == 'To be check' || a == 'Endorsed By IT')
{
document.getElementById("new").style.display = 'block';
}
else
{
document.getElementById("new").style.display = 'none';
}
</script>
i guess you need to do it write condition in document ready method
$( document ).ready(function() {
var a = '<?php echo $row["status"]; ?>'; // missing the quotes here
if(a == 'To be check')
{
$("#new").show();
}
else
$("#new").hide();
})
First problem
I want to use variable don_settings[don_btn_act] (=checkbox) to define a button action.
IF don_settings[don_btn_act] IS on
THEN -> load checkout
ELSE -> page reload
don_settings[don_btn_act] is definded and it is modified well, so i can turn it on or off. The problem is that I should use it in javascript.
What I have so far:
function reloadpage(){
<?php if(isset($don_config['don_btn_act']) && $don_config['don_btn_act'] =='on') { ?>
window.location.href = 'index.php?route=dcheckout/checkout';
<?php } else { ?>
window.location.reload();
<?php } ?>
}
It is always executing the window.location.reload() function.
Second problem
in the same way i have the variable don_settings[min_amount]. I use it to define the minimum amount of input.
it is defined in php like the previous varible.
But i should use it in javascript part of tpl file, too.
What I have so far:
function validation(){
if(jQuery('#opton').val() == ''){
alert("<?php echo $drop_empty_msg; ?>");
return false;
}
else if(jQuery('#don_amount').val() == '' || jQuery('#don_amount').val() == '0'){
alert("<?php echo $amount_empty; ?>");
jQuery('#don_amount').focus();
return false;
}
else{
return true;
}
}
i use
|| jQuery('#don_amount').val() <= "<?php $don_settings[min_amount]; ?>"
insteed of
|| jQuery('#don_amount').val() == '0'
but it returns false every time
Sorry, I couldn't understand your problem or your intensions. Try correcting your misspelling, your grammar and please take care of beautiful formatted code!
Nonetheless i have some recommendations for writing maintainable code.
Your problem (#1)
If your browser is always executing the window.location.reload(), the problem does not refer to your javascript. It is your server side code which fails. Your following condition seems to be false:
<?php if(isset($don_config['don_btn_act']) && $don_config['don_btn_act'] =='on') { ?>
Don't mix your javascript and php up
First of all, compute your necessary values/conditions:
(Preferably into a seperated file)
<?php
$condition = isset($don_config['don_btn_act']) && $don_config['don_btn_act'] =='on';
?>
Now, you can use it very comfortable and clearly:
function reloadpage() {
var condition = '<?php echo $condition; ?>';
if (condition)
window.location.href = 'index.php?route=dcheckout/checkout';
else
window.location.reload();
}
There are lots of big advantages not to mess up your code.
Also be careful ...
... while injecting code through php to the markup/javascript. Don't offer potential attackers new security holes!