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();
})
Related
I have the $value and $field generated dynamically from php $value = 'mango'; $field='user_username'. I now need to check if the text entered in input id user_username is mango or not.
<input type="text" class="input-text um-field " name="user_username" id="user_username" placeholder="">
Something like:
<?php
$value = 'mango';
$field = 'user_username';
<script>
$(document).ready ( function(){
var value = $("#<?php echo $field;?>").val();
if(value === '<?php echo $value;?>') {
alert('hi');
}
});
</script>
?>
A better approach would be to load your desired field into some js variable and then compare.
here is how it works roughly
$(document).ready(function(){
$("button").click(function(){
$.get("demo_test.php", function(data, status){
var server_data=data;
});
});
});
then compare it with desired field
$(document).ready ( function(){
var value = $("#<?php echo $field;?>").val();
if(value === server_data) {
alert('hi');
}
});
hope it helps
You could check the value on blur, because $(document).ready() is called at the beginning of the script. Also you have to close the PHP tag before to write JavaScript:
<?php
$value = 'mango';
$field = 'user_username';
?>
<input type="text" class="input-text um-field " name="user_username" id="user_username" placeholder="">
<script>
$(document).ready(function(){
$("#<?php echo $field;?>").bind('blur', function(){
var value = this.value;
if(value === '<?php echo $value;?>') {
alert('hi');
}
});
});
</script>
As per my comment, your script only compares the input field's value at runtime against a PHP variable. JavaScript does not automagically performs the comparison whenever the user updates the input field—you will have to bind an event handler to your input element, so that when triggered will re-invoke the logic to perform the check:
$(document).ready (function(){
var $field = $("#<?php echo $field;?>");
var expectedFieldValue = '<?php echo $value;?>';
$field.on('change', function() {
if ($(this).val() === expectedFieldValue) {
alert('hi');
}
});
});
Sometimes, it might be just a bit heavy-handed to use jQuery if you're performing a simple logic like this. The above code can also be rewritten in native JS that works in modern, evergreen browsers:
document.addEventListener('DOMContentLoaded', function () {
var fieldElement = document.getElementById('<?php echo $field;?>');
var expectedFieldValue = '<?php echo $value;?>';
fieldElement.addEventListener('change', function () {
if (fieldElement.value === expectedFieldValue) {
alert('hi');
}
});
});
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.
The purpose is to display a DIV when you click on a button and then display text inside that DIV that comes from my database. Thing is that data in databse changes, so text inside that div also. I would need a setInterval... with AJAX
I'm new in javascript and don't know the good way to go...
HTML:
<div onClick="showDiv();"> click </div>
<div style="display: none;" id="div">
Info from database:
<span style="display: hidden;" id="data1"> DATA 1 </span>
<span style="display: hidden;" id="data2"> DATA 2 </span>
</div>
javascript:
function showDiv()
{
document.querySelector("#div").style.display = "block";
setInterval(function () {getData()}, 1000);
}
function getData()
{
$.post(
'process.php',
{
},
function(data){
if(data == '1'){
document.querySelector("#data1").style.display = "inline";
}
else if(data == '2'){
document.querySelector("#data2").style.display = "inline";
}
},
'text'
);
return false;
}
//don't know how to just take data from database without sending by POST or GET.
php:
<?php
SELECT x FROM database
if(x == 1)
{echo '1';}
else if(x == 2)
{echo '2';}
?>
Get data using AJAX : Learn here. Your code to setInterval() is correct or you can do this : setInterval(getData,1000);
Display data in spans :
document.getElementById("data1").innerHTML = "your content from database";
document.getElementById("data2").innerHTML = "your content from database";
You're not giving a lot of info so I will give you a basic example of getting data from a mySQL database with jQuery, Ajax and PHP.
First you need to include jQuery to the head of your document
<script src="http://code.jquery.com/jquery-latest.js"></script>
And then use Ajax
function showDiv(){
document.getElementById("div").style.display = "";
setInterval(function (){ getData('something'); }, 1000);
}
jQuery.noConflict();
jQuery(document).ready(function($){
getData = function(variable){
var postVar = variable;
var postVar2 = "exemple";
$.ajax({
type: "POST",
url: "php/file.php",
data: 'variable=' + postVar + "&" +
'variable2=' + postVar2,
success: function(data){
data = $.trim(data);
var dataSplit = data.split("++==09s27d8fd350--b7d32n0-97bn235==++");
if(dataSplit[0] == "1"){
document.getElementById("data1").innerHTML = dataSplit[1];
}
if(dataSplit[0] == "2"){
document.getElementById("data2").innerHTML = dataSplit[1];
}
}
});
}
});
Finally, you need to create an external php file (in this example "file.php" in the folder "php") to get the data from your database with mysqli
<?php
// to prevent error, I check if the post variable is set and
// if it's not only full of spaces
if(isset($_POST['variable']) && preg_replace("/\s+/", "", $_POST['variable']) != ""){
$con = mysqli_connect("hostname", "username", "password", "database_name");
$query = mysqli_query($con, "SELECT * FROM `table_name` WHERE `column_name` = '".$_POST['variable']."'");
$results = array(); $row = 0;
while($info = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$results[$row] = array();
$results[$row]['column_name1'] = $info['column_name1'];
$results[$row]['column_name2'] = $info['column_name2'];
$row++;
}
foreach($results as $result => $data){
echo "1" . "++==09s27d8fd350--b7d32n0-97bn235==++" .
'<div>'.$data['column_name1'].'</div>'.
'<div>'.$data['column_name2'].'</div>';
}
}
?>
Hope it helps!
I have a php webpage where a user enters their details into a form and after submitting two sections, named profile and images, must then appear. Here is the javascript code:
jQuery(document).ready(function($) {
var registered = <?php echo $registered; ?>;
alert(registered);
if (registered == 'false') {
$("#profile").hide();
$("#images").hide();
}
if (registered == 'true') {
alert('hello');
$("#profile").show();
$("#images").show();
}
});
For some reason it does not go into the if statement at all, even though the alert shows registered's value as true. What could be the problem here?
var registered = <?php json_encode($registered) ?>
if(registered == true) {
alert(registered);
$("#profile").hide();
$("#images").hide();
} else {
alert('hello');
$("#profile").show();
$("#images").show();
}
You are mixing up the string 'true' with the boolean true. Try a version that uses booleans from start to finish instead:
var registered = <?= json_encode($registered) ?>;
if (registered) {
$("#profile").hide();
$("#images").hide();
} else {
$("#profile").show();
$("#images").show();
}
Edit - Thanks to Jon in another comment for suggesting using json_encode.
use JSON.parse() Takes a well-formed JSON string and returns the resulting JavaScript object.
//JSON.parse(registered);
var registered = <?php echo $registered; ?>;
if (!(JSON.parse(registered))) {
$("#profile").hide();
$("#images").hide();
}
else {
$("#profile").show();
$("#images").show();
}
Remove the quotes and try
jQuery(document).ready(function($) {
var registered = <?php echo $registered; ?>;
alert(registered);
if (registered == false) { //Remove the quotes
$("#profile").hide();
$("#images").hide();
}
if (registered == true) { //Remove the quotes
alert('hello');
$("#profile").show();
$("#images").show();
}
});
Reason in this demo.
var registered = true;
alert(registered == 'true'); //return false
alert(registered == 'false'); //return false
In JavaScript data type comparison is a bit inconsistent. So always try to compare same data-types.
so try:
var registered = true;
alert(registered == true); //return true
alert(registered == false); //return false
Change your code to:
if (registered) {
alert('hello');
$("#profile").show();
$("#images").show();
}
else {
$("#profile").hide();
$("#images").hide();
}
Try with this
jQuery(document).ready(function($) {
var registered = "<?php echo $registered; ?>";
alert(registered);
if (registered == false) {
$("#profile").hide();
$("#images").hide();
}
else if (registered == true) {
alert('hello');
$("#profile").show();
$("#images").show();
}
});
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!