Active if null then hide div in PHP - javascript

I think I'm going to have to use Jquery for this.
I have a print button that I only want to show if my array has data in it.
Here's my really simplified version of what I'm trying to accomplish
HTML
<?include 'anotherpage.php'?>
<button class='printButton' name='printButton'>Print</button>
PHP
$data = array();
if($statement == true){
array_push($data, 'some value', 'another value');
}
if (empty($data)){
echo "No trace currently found";
**<<I want to set a hidden class to the button here somehow>>**
}
Any help in the right direction would be greatly appreciated. I'm still trying to grasp the whole JQuery thing.

Why don't you just include the button IF there is $statement == true?
Another way could be to set an jQuery / JavaScript function that hides the button.
Then if there should be no button, print a html part which calls the function.
Something like this:
jQuery
hidePrintButton = function()
{
$('.printbutton').hide();
}
PHP
if (empty($data)){
echo "No trace currently found";
echo '<script>';
echo 'hidePrintButton();';
echo '</script>';
}

What about just putting the button inside the if statement in PHP?
PHP
$data = array();
if($statement == true){
array_push($data, 'some value', 'another value');
echo "<button class='printButton' name='printButton'>Print</button>";
}
if (empty($data)){
echo "No trace currently found";
**<<I want to set a hidden class to the button here somehow>>**
}
HTML
<?include 'anotherpage.php'?>

If the button is allready rendered on the page, and assuming there is only one button with class printButton, using jquery you could do something like this:
if (empty($data)){
echo "No trace currently found";
echo "$('.printButton').hide();";
}
But this is not a good way to do it because you are mixing server behaviour and client behaviour, which will result in code difficult to maintain and debug.
You better rewrite your code to use only php, not printing the button in the first place if it is not needed, or using a class to hide it if it could be needed later.
Using a class to hide the button:
$hideClass = "";
if (empty($data)){
$hideClass = "hideButton";
}
echo "<button class='printButton $hideClass' name='printButton'>Print</button>";
This way, if you later need to show the button with jquery, you could call:
$('.printButton').removeClass('hideButton');

Related

How to add php variable/function into a javascript function [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
I cant seem to add a php function / variable into my javascript. I need it to set options into a dynamic select form I have in javascript.
I tried "" inside the javascript which everyone recommended.
<?php
function options(){
include "connection.php";
$sql="SELECT DISTINCT PartID, PartName FROM parts";
$result = mysqli_query($conn,$sql);
if ($result) {
while ($row=mysqli_fetch_assoc($result)){
echo "<option value='{$row['PartID']}'>{$row['PartName']}</option>";
}}}
?>
<script>
$(function(){
$('p#add_part').click(function(){
counter_part += 1;
$('#container').append(
'<strong>Part No.'+ counter_part + '</strong><br />');
$('#container').append(
'<select><option>Select a Part</option>((((((HERE)))))
</select>');
});
});
</script>
The whole function does not work in relation to the methods I keep trying. When ever I add a '' inside the script to add a variable inside the option, the whole function stops working. However its possible to add a counter variable. Btw I have some other functions above the script etc that was irrelevant.
You can try storing it in an HTML element in PHP, then you can read it from JavaScript and then delete it from JavaScript. You can also set it at the bottom of the page and set the text color the same as the background color so you can't see it. I don't know much about PHP, but I do for JavaScript and HTML, so, sorry but I can only add the JavaScript and HTML.
HTML:
<span style="background-color:white; color:white;" id="phpVariable"></span>
JavaScript:
var element = document.getElementById("phpVariable"); // Get the element
var phpString = element.textContent; // Get a string
var phpInteger = parseInt(element.textContent) // Get an integer
var phpFloat = parseFloat(element.textContent) // Get a float
element.parentNode.removeChild(element); // Delete the element
For the PHP, you just have to append the HTML element above to the bottom of the page. If you're background is a different color, then you can just set both the background color and the text color to the background color of the page. Doing this will make the text invisible by just looking at it until the JavaScript picks it up and deletes the element.
Just echo your JavaScript function with PHP, and you can easily insert function variables with string concat. In example echo 'alert("'.$var.'"); or something like this!
I'm not sure that is what you want, but you can use PHP values of variables in your JS with simple echo to text. I just edited your to work. Declaring options into $options variable and return it in function is giving possibility to write them into JS with echo. You could do it with $options directly, without options() function.
PHP code works only once, then your echo values counted as hardcoded text in html file. Use this only if you need to get value once.
<?php
function options(){
include "connection.php";
$sql="SELECT DISTINCT PartID, PartName FROM parts";
$result = mysqli_query($conn,$sql);
if ($result) {
$options = '';
while ($row=mysqli_fetch_assoc($result)){
$options .= "<option value='".$row['PartID']."'>".$row['PartName']."</option>";
}
}
return $options;
}
?>
<script>
$(function(){
$('p#add_part').click(function(){
counter_part += 1;
$('#container').append(
'<strong>Part No.'+ counter_part + '</strong><br />');
$('#container').append(
"<select><option>Select a Part</option><?php echo options() ?></select>");
});
});
</script>

PHP altering HTML on first connection

Currently I have a php-page using include to show an html-page.
What I want to do is use a variable the php-page received when being called and project data into a field of the html-page depending on this variable. The problem is that I can't seem to pass the variable from php to html without using html to call php.
I know that I can simply echo the php-part, but because I can't echo straight into one of the html-page's divs it ends up putting the echo at the beginning or end of the page.
What I want to accomplish is for the html-page to load the php-part into one of the div's the first time the php includes the html-page. Is there any way to do such a thing?
If this isn't possible, then how do I get the javascript in the html-page to use the variable from the php-file? Is the best option really the href?
As requested some of the code:
php:
if (filter_input(INPUT_GET, "event", FILTER_SANITIZE_STRING))
{
include "../Html/EventPage.html"; //target page
$temp = filter_input(INPUT_GET, "event", FILTER_SANITIZE_STRING); //get the variable
include "../PHP/Connector.php"; //include the connection page
$value = callFunction(Connect(), $temp); //call connection page and return value
echo "<div class = 'cant select div in html'>" . $value . "</div>"; //echo value in location
}
html:
<div id = "dynamic">
this should have the php
</div>
I assume you use some code like this to display the page:
include('page.html');
A safer way would be to prevent evaluation in page.html:
echo file_get_contents('page.html', true);
You can then do any string modification you want for the content:
$replacement = 'MY REPLACEMENT';
echo str_replace('<div id="my-div">', '<div id="my-div">' . $replacement, file_get_contents('page.html', true));

Using Javascript to change style of elements in PHP

I have a problem with javascript in PHP. I want to use Javascript function to change ccs atribute display to block for only those div elements that contain certain text that is in php variable which is taken from column in MySQL table. I don't know if it is actually possible this way but here's the code:
PHP:
$sql="SELECT * FROM Filter1";
$result=$conn->query($sql);
while($row = $result->fetch_assoc()) {
$meno=$row['meno'];
echo '<script type="text/javascript"> filterTovar() </script>';
JavaScript:
function filterTovar()
{
var meno='<?php echo $meno; ?>';
var produkt=document.getElementsByClassName("tovar");
produkt.style.display="none";
for(var i=0;i<produkt.length;i++)
{
produkt[i].style.display="none";
}
for(var i=0;i<produkt.length;i++)
{
if(produkt[i].innerHTML==meno)
{
produkt[i].style.display="block";
}
}
}
I am trying to make some kind of filter that makes only certain divs shows depending on result of table but the code above doesn't work and I'm not sure if it is possible to make work this way.
MySQL table I'm taking data from:
id meno znacka cena op format
425 H81M-S2V GIGABYTE 46.03 DDR3 mATX
426 H110N GIGABYTE 83.05 DDR4 mITX
EDIT: Better explanation of my problem: User uses checkboxes to filter products on my website, in database php creates table with corresponding products. My code above is supposed to take that table and use column "meno" in which is name of product to show only those div that contain string "meno".
EDIT2: I want to ask if it is possible to change or work with elements css via DOMDocument(). If yes it would answer my question.
Yes, it is possible but there is no need to use javascript/jQuery - just use HTML and CSS.
Basically, you have your database result set and you loop through it with a while loop, right?
I guess you are constructing HTML in that while loop.
In each iteration of the loop, test your MySQL column value and add a class to the desired HTML element.
Here is an example:
$out = '<table><tbody>';
while($row = $result->fetch_assoc()) {
$theclass = ($row['something']=='hideme') ? ' hiddenTD' : '';
$out .= '<tr><td class="' .$theclass. '">' .$row['something']. '</td></tr>'
}
$out = '</tbody></table>';
echo $out;
Of course, you would have CSS defined in the document, like:
<style>
.hiddenTD{display:none;}
</style>
This is a terrible example because you can't "hide" a TD, but it's an example.

Get element by ID does nothing

In my PHP document I pull data from, for example, myDatabase. I then proceed to assign a value from a table in my Database to a variable. I know that this variable, which happens to be $fileLoc1, does have a value, for when I put
echo $fileLoc1;
It returns a value, or in my case a url to a file. Basically, what this does is tell the user if a file is available for download. I have the following code to check this.
if ($fileLoc1 === NULL) {
echo "<script>
document.getElementById ('alert-sng-available').style.display
= 'none !important';
</script>";
echo "<script>
document.getElementById ('alert-sng-Navailable').style.display
= 'block !important';
</script>";
}
In the code above #alert-sng-available is the alert that will show the green available div and the alert-sng-Navailable (not available) will show the red div.
When I first put this into my .php file, I thought nothing of it because it worked. $fileLoc1 is NOT null, therefore using the original settings of the div, showing the green, hiding the red. However if I edit the code ever so slightly...
if ($fileLoc1 !== NULL) {
echo "<script>
document.getElementById ('alert-sng-available').style.display
= 'none !important';
</script>";
echo "<script>
document.getElementById ('alert-sng-Navailable').style.display
= 'block !important';
</script>";
}
Can you guess what happens? Nothing. Absolutely, positively nothing. Below is an image showing results from both attempts. On the second snippet of code the green div should go away, being replaced by a red div. (yes, I'm using bootstrap, that's why I'm using the !important, but it doesn't work with or without it)
The Next picture will show the tag in the HTML once I change the if statement from === to !==
This is in inspect element, clearing showing php evaluated the !== equation to true, which is correct, but now the javascript doesn't work.
Lets try this again but with the === equation. It works! There are no script tags 'cause it evaluated to false as it should.
I'm at a loss here.
Yes, the divs are labeled correctly, no bootstrap isn't interfering. Because if I change the properties of both the alert-sng divs using "ctrl + shift + i" it works properly! Also, yes my javascript is at the bottom of the page
A gif showing it can work
You shouldn't be using the PHP–JS–HTML/CSS pipeline. In fact, you can simply rely on PHP itself to dictate what is shown/hidden on the page itself.
As you have not provided any markup in your code, I will be using a hypothetical example. Let's say you want to print <p>File available</p> when the $fileLoc1 variable is not null, and <p>File not available</p> otherwise, we can do this:
<?php
if ($fileLoc1 === NULL) {
echo '<p>File available</p>';
} else {
echo '<p>File not available</p>';
}
?>
For a more concise example, you can also use the ternary operators (?:), i.e.:
<?php
echo $fileLoc1 === NULL ? '<p>File available</p>' : '<p>File not available</p>';
?>
If you want both markups to be present so that you can manipulate them using JS later, you can even print both, and dictate the styles conditionally:
<p style="<?php echo $fileLoc1 === NULL ? 'display: none': 'display: block'; ?>">File available</p>
<p style="<?php echo $fileLoc1 === NULL ? 'display: block': 'display: none'; ?>">File not available</p>
In the case when $fileLoc is NULL, you will get the following markup:
<p style="display: none">File available</p>
<p style="display: block">File not available</p>

echo variable to document via button click

First time here so apologies if I'm doing something wrong.
I have the following php code:
<?php
$quoteFile = "quotes.txt"; //File holding qoutes
$fp = fopen($quoteFile, "r"); //Opens file for read
$content = fread($fp, filesize($quoteFile));
$quotes = explode("\n",$content); //Put quotes into array
fclose($fp); //Close the file
srand((double)microtime()*1000000); // randomize
$index = (rand(1, sizeof($quotes)) - 1); //Pick random qoute
?>
The code fetches a random quote from a text file by randomly choosing one of the lines of the .txt file.
I then echo out the result using:
echo $quotes[$index];
However what I want to achieve and don't seem to be able to is to have a button (html) that when clicked executes the echo $quotes[$index]; to the current page. So that each time the button is clicked it prints/echo's out a random quote from the .text file.
I did mess about with just setting a button up to refresh the page which by default made a new random quote display but it sometimes just reloaded a blank so I'm hoping someone can help me achieve this better or prompt me in the right direction. Thank tou.
You can try saving that variable into a session variable like this:
$_SESSION['quote'] = $quote['index'];
Then create an anchor element that redirects to current page:
Refresh
And print the result on the page:
<span><?php echo $_SESSION['quote']; ?></span>
To do all of this, you need to set a session. At top of your php file write:
session_start();
Hope that helps. :)
Your TXT file might have an empty line in it at the end or anywhere else. A second explanation of this, is that the way you are generating randomness is quite questionable.
Check out this simple example by W3 Schools.
$a=array("red","green","blue","yellow","brown");
$random_keys=array_rand($a,1);
echo $a[$random_keys[0]]."<br>";
The array_rand() function returns a random key from an array, or it returns an array of random keys if you specify that the function should return more than one key.
Or, simply:
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
print_r(array_rand($a,1));
?>
Full Post: http://www.w3schools.com/php/func_array_rand.asp
Happy coding !

Categories

Resources