Get element by ID does nothing - javascript

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>

Related

Change user image based on who's logged in

I'm currently working on a login portal.
I already set the log in and log out functions and placed a session start button on every page.
My problem now is that I would like to update the user image based on the identity of who is logged in.
I'm using a template my boss chose, and this is the code where the image is:
<span>
<img src="../../global/portraits/5.jpg" alt="...">
</span>
Just a simple <img> tag with the link where the image is.
My project is in an html file with php implemented, and I tried to do this in the <span> tag, instead of <img>:
<?php
$W = ["Raffaella", "Milena", "Domiziana"];
$M = ["Umberto", "Domenico"];
if ($_SESSION["nome"] == $W) {
echo '<img src="W.jpg">';
} else if ($_SESSION["nome"] == $M){
echo '<img src="M.jpg">';
}
?>
where $_SESSION["nome"] represents the current user logged in. However, it doesn't do anything, not even producing an error.
Can someone explain how I can do it correctly, please? I'm new to php and trying to understand by studying alone on the internet
I was also considering JavaScript for this work (instead of PHP), but I don't know where to start
It looks like both $W and $M are array of names, rather than a single user, if that's the case, I assume you're trying to determine if a user is in that array. In PHP, you can use:
in_array($_SESSION["nome"], $W)
https://www.php.net/manual/en/function.in-array.php
which will return true/false.
if (true === in_array($_SESSION["nome"], $W)) {
echo '<img src="W.jpg">';
} else if (true === in_array($_SESSION["nome"], $M){
echo '<img src="M.jpg">';
}
But, this only gives two separate images for up to 5 unique names, and I'm not sure if that's what you're going for.

Display more of a hidden text on button click, php, phalcon

I have a table that displays items from a database. One of the items is a description so it can be very long.The thing I'm having the most problem with is how can I use JS and HTML smoothly in my controller class.
I want to be able to display a little bit of it if its longer than 100 char, and a button that looks like '...' where if the user clicks on it, it displays the trimmed text. I want to do this using javascript and here is what I tried, this code is in my controller, so I'm just sending these to the view.
The problem is when I press the button it doesn't display anything so what is wrong here? Some suggested to use jquery but I don't want to write my js script elsewhere and call it again since I'm not sure how I will do that in Phalcon controller.
$this->view->tblColumns = [
'element one',
'element two',
function (tablename $instance) {
if (strlen($desc = $instance->getDescription()) > 100) {
return $shortDesc = substr($instance->getDescription(), 0, 100) . '
<button style="background: none;border: none" onclick="(function(){
var desc= <?php echo
$desc; ?>; document.write(desc) ;
})()" >...</button>';
} else {
return $instance->getDescription();
}
},
do NOT use document.write after load of the page. It will wipe the page
your desc needs to be in single quotes and have no carriage returns.
you cannot use an IIFE in an onclick unless it returns a function
if your button is in a form, you will submit the form - it should be type=button
You MAY mean
<button type="button" onclick="var desc='<?php echo $desc; ?>';
document.querySelector('#someContainer').innerHTML=desc;"...>
but a better way is to toggle the existing text inside tags (span for example)
I find a way to do what I wanted, using the code for read more,read less from this link https://codepen.io/maxds/pen/jgeoA
The thing I was having trouble with in phalcon MVC, was that I didn't know I could my java-script, and css in the view of the controller and that's what I did.
I just used the js from that link, into my view file, the same for the css using tag and tag.
And in the function on the controller I wrote the following `
$this->view->tblColumns = [
'one',
'two',
function(tablename $link){
$desc=$link->getDescription();
$html=<<<HTML
<span span class="more"> $desc</span>
HTML;
return $html;
}`

scroll nav via onchange php

I'm not really that familiar with php so hence the question. I have a list of products that is dynamically created via php. When a user clicks one of the generated lists it sorts the products. I also want to move the user to a new part of the page to see the results. I thought I could do this via an smooth scroll using an onchange, but I'm not that sure where to put it. Site is bootstrap so was going to use the scrolling-nav.js.
here is the php generating the list
<?php
echo '<div id="brands">';
// echo $product['name'].'<br>';
echo '<a href="#top-of-products"><input style="display:none"
type="checkbox" data-type="brand" onchange="showlist(this)"
id="b-'.$brand['id'].'" name="'.$brand['name'].'"
value="'.$brand['name'].'"><label id="b-'.$brand['id'].'"
for="'.$brand['name'].'">'.$brand['name'].'</label></a><br>';
}
echo '</div>';
Help much appreciated
You put short stretch of your code, but, I see a } lost before the last line.
I guess you put your code for scrolling a new part of the page in showlist() javascript function.
But, I don't know if onchange method is the better. I would use onclick method
Is the results panel always in the same location on the page? If so, and you're using the jquery library, consider using jquery's scrollTop function:
$('#item).click(function(){
$(html).scrollTop(val); //where val is the number of pixels hidden above the scrollable area when the Results panel is positioned where you want it to be
});
If the vertical position of the Results panel is variable, you can use this to define the "val" variable above:
$('#id-of-rewards-panel').offset().top
You might want to add a few pixels to that, because that will bring your element to the very top of the page
here is the whole code:
<?php foreach($view->brandfromcategory_data as $brand) {
echo '<div id="brands">';
// echo $product['name'].'<br>';
echo '<input style="display:none" type="checkbox" data-type="brand" onchange="showlist(this)" "scrollTo(#buttonreplacement)" id="b-'.$brand['id'].'" name="'.$brand['name'].'" value="'.$brand['name'].'"><label id="b-'.$brand['id'].'" for="'.$brand['name'].'">'.$brand['name'].'</label><br>';
}
echo '</div>';
?>

String value accumulating empty spaces in MySQL database

I have a webpage where admin users can edit the text on the page. But when they insert the text into the mysql database, it sometimes adds more and more white spaces before the acual content.
If you place your cursur before the first word on the page and spam backspace for a while, the whitespace in the database dissappears. But over time, the more you keep editing the page, more and more whitespaces are added again.
I did a lot of trouble shooting, but I just can't figure out what causes the whitespaces to be added. It does not always happen making it really difficult to troubleshoot.
Here's my code:
As my code is pretty long, I tried to translate most of the content to english.
If you want to translate something that in't already translated, the original language is Dutch.
over_ons.php - Shows edit button and page content from the database.
//Active page:
$pagina = 'over_ons'; ?>
<input type='hidden' id='pagina' value='<?php echo $pagina; ?>'> <!--Show active page to javascript--><?php
//Active user:
if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin'){
$editor = $_SESSION['gebruikersnaam']; ?>
<input type='hidden' id='editor' value='<?php echo $editor; ?>'> <!--Show active user to javascript--><?php
} ?>
<!--Editable DIV: -->
<div class='big_wrapper'><?php
//Get eddited page content from the database
$query=mysql_query("SELECT inhoud FROM paginas WHERE naam_pagina='" .$pagina. "'");
while($inhoud_test=mysql_fetch_array($query)){
$inhoud=$inhoud_test[0];
}
//Show Content
?><div id='editedText'><?php echo $inhoud; ?></p></div>
<!--Show edit button-->
<?php
if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin')
{?>
<div id='sidenote'>
<input type='button' value='Bewerken' id='sent_data' class='button' />
<div id="feedback" />
</div>
<?php }
javascript.js - Sents page content to the php file sent_data.php:
//If the system is in edit mode and the user tries to leave the page,
//let the user know it is not so smart to leave yet.
$(window).bind('beforeunload', function(){
var value = $('#sent_data').attr('value'); //change the name of the edit button
if(value == 'Verstuur bewerkingen'){
return 'Are you sure you want to leave the page? All unsaved edits will be lost!';
}
});
//Make content editable and send page content
$('#sent_data').click(function(){
var value = $('#sent_data').attr('value'); //change the name of the edit button
if(value == 'Bewerken'){
$('#sent_data').attr('value', 'Verstuur bewerkingen'); //change the name of the edit button
var $div=$('#editedText'), isEditable=$div.is('.editable'); //Make div editable
$div.prop('contenteditable',!isEditable).toggleClass('editable')
$('#feedback').html('<p class="opvallend">The content from<BR>this page is now<BR>editable.</p>');
}else if(value == 'Verstuur bewerkingen'){
var pagina = $('#pagina').val();
var editor = $('#editor').val();
var div_inhoud = $("#editedText").html();
$.ajax({
type: 'POST',
url: 'sent_data.php',
data: 'tekst=' +div_inhoud+ '&pagina=' +pagina+ '&editor=' +editor,
success: function(data){
Change the div back tot not editable, and change the button's name
$('#sent_data').attr('value', 'Bewerken'); //change the name of the edit button
var $div=$('#editedText'), isEditable=$div.is('.editable'); //Make div not editable
$div.prop('contenteditable',!isEditable).toggleClass('editable')
//Tell the user if the edditing was succesfully
$('#feedback').html(data);
setTimeout(function(){
var value = $('#sent_data').attr('value'); //look up the name of the edit button
if(value == 'Bewerken'){ //Only if the button's name is 'bewerken', take away the help text
$('#feedback').text('');
}
}, 5000);
}
}).fail(function() {
//If there was an error, let the user know
$('#feedback').html('<p class="opvallend">There was an error.<BR>Your changes have<BR>not been saved.<BR>Please try again.</p>');
});
}
});
And finally,
sent_data.php - Get page content from javascript,js and insert into database:
<?php
session_start();
include_once('./main.php');
include($main .'connectie.php');
//Look up which page has to be edited
$pagina=$_POST['pagina'];
//Get the name of the person who eddited the page
$editor=$_POST['editor'];
//Get content:
$tekst=$_POST['tekst'];
$tekst = mysql_real_escape_string($tekst);
$tekst = trim($tekst);
$query="UPDATE paginas SET naam_editer='" .$editor. "', inhoud='" .$tekst. "' WHERE naam_pagina='" .$pagina. "'";
}
if(mysql_query($query)){
echo "<p class='opvallend'>Successfully saves changes.</p>";
}else{
echo "<p class='opvallend'>Saving of changes failed.<BR>
Please try again.</p>";
}
?>
Extra information:
PHP version: 5.5.15
jQuery version: 1.11.1
Testing in browser: Chrome
Database: phpMyAdmin 5.5.39
The content is inserted in a VARCHAR type with space for 10000 caracters
Thanks in advance for you help!
SOLUTION
Thanks to the great help of a lot of people, and especially #avnishkgaur, it is working perfectly now. Here is what I ajusted (also changed it in my code above, so that's working code now).
1. Removed all the white spaces I had in my code between <div id='editable'> and <?php
2. Added $tekst = trim($tekst); to my PHP file to remove white spaces (didn't work)
3. Placed the editable text into another div as the code for getting the data from the database (was in the same div before)
4. Renamed the ID from the editable div to editedText. Also changed the name in the javascript file. This solution made it work perfectly (it was 'editable' before).
This was kind of an unexpected solution, so I think this could help others too.
As to why it is adding extra whitespace, I think it is because you are inserting the text from database into div directly (which contains some white space in html code, which is removed when page is rendered).
One efficient solution would be to insert your content in tag, probably like this:
<div class='big_wrapper'>
<p id='editable'></p>
</div>
Another solution is to trim the text before inserting into db. You can do that either at javascript post stage, or right before inserting in mysql db.
In jQuery, (which you are using) you can implement this :
data: 'tekst=' +$.trim(div_inhoud)+ '&pagina=' +pagina+ '&editor=' +$.trim(editor),
or in sent_data.php, you can use TRIM mysql function in your update query.
First of all, I would strongly suggest to use mysqli or PDO instead of the mysql functions in PHP, as these are deprecated. Please look into this on PHP.net.
As for your problem, I have no tried to reproduce the issue. I suggest you log and check what happens step by step, for example logging the div_inhoud var, are the spaces included at this stage already? And so on.
If you are in a hurry, you could also use the PHP function ltrim on the $tekst var in your sent_data.php, which would trim all spaces on the left side (Or any characters you would want to be trimmed from the string)
Try to add a trim() function in your send_data.php, this will help you to strip white spaces.
$tekst = trim($_POST['tekst']);
My guess is that the newlines after the <div id='editable'> and ?> and the indentation of <?php in over_ons.php is adding the extra whitespace. Specifically, a couple of extra /n's and also spaces from the indentation within the file.
You could trim the whitespace before saving it to your database, or alternatively, before the ajax call, or both.
In php, trim():
sent_data.php
$tekst = trim($tekst);
Or javascript, str.trim():
javascript.js
var div_inhoud = $("#editable").html().trim();
Also, you may want to consider using PHP Data Objects, instead of inserting variables directly into your SQL statements. It's actually really easy to use and in my opinion makes code easier to read and more reusable. There is a fantastic tutorial by Tuts+ that makes it easy to learn and get started. This will ensure you don't accidentally allow SQL injection issues into your application.

Active if null then hide div in PHP

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');

Categories

Resources