How to show div in if block in php - javascript

I have index.php, in index.php there is a login form with session. If username and password are correct, it would go to home.php. But if username or password is incorrect I want to show div above login form that contains an error message like this .
I want this warning div is hidden and it will be shown only if username or password is incorrect. I've tried some other solution but none of them work, first If I put div in else condition, it will appear above login form no matter what the condition are. Second, if I put javascript to change style display = block, it won't appear in index page. Please help me to solve this problem. Thanks.
Index.php
<?php
session_start();
if(isset($_POST['login']))
{
$user = $_POST['user'];
$pass = $_POST['pass'];
if($user == "admin" && $pass == "admin")
{
$_SESSION['user']=$user;
?>
<script language="javascript">window.location.href='home.php' </script>
<?php
} else {
//What should I do here?
?>
<script language="javascript">document.getElementById("warning").style.display = "block" </script>
<?php
}
}
?>
<!-- Warning that I want to show if username or password is incorrect -->
<div id="warning" class="w3-container w3-red w3-text-white w3-card-2 w3-animate-opacity" style="position: relative;margin-top: 20px;display:none">
<span onclick="this.parentElement.style.display='none'" class="w3-closebtn">×</span>
<strong>Warning!</strong> Incorrect Username or Password!
</div>
<!-- Login form -->
<form class="w3-container" action="" method="post">
</form>
[EDIT]
I finally solved the problem by following Sharky's suggesstion to put php code below warning div. In else case I'm still using javascript that will change style display of warning div to block. Thanks for all your help :)

The best way should be what you already tried: use the #warning div in the else case. Maybe it didn't work because you chose the wrong else?
<?php
session_start();
if (isset($_POST['login'])) {
$user = $_POST['user'];
$pass = $_POST['pass'];
if($user == "admin" && $pass == "admin") {
$_SESSION['user']=$user;
?>
<script type="text/javascript">window.location.href='home.php';</script>
<?php
} else {
?>
<div id="warning" class="w3-container w3-red w3-text-white w3-card-2 w3-animate-opacity" style="position: relative;margin-top: 20px;">
<span onclick="this.parentElement.style.display='none'" class="w3-closebtn">×</span>
<strong>Warning!</strong> Incorrect Username or Password!
</div>
<?php
}
}
?>
//Login form
<form class="w3-container" action="" method="post">
</form>
Another tipp (which has nothing to do with your question, but may help anyway): instead of using a redirection with JavaScript, you could simply use php, so that the additional roundtrip to the browser is not needed any more:
header('Location: home.php');
This requires, that no 'normal' output is created before the header() call and would work in this example, but may fail if there is some html code before it.

The reason why your div is not showing, is because your javascript which sets the display:block; is being executed BEFORE that div is generated in your markup.
Simple scenario (which fails):
<html>
<head>
<script language="javascript">
document.getElementById("warning").style.display = "block";
</script>
</head>
<body>
<div id="warning" style="display:none;">hello</div>
</body>
</html>
this will result to
Uncaught TypeError: Cannot read property 'style' of null because the moment javascript tries to get the element with id warning there is only this markup "existing" in the browser:
<html>
<head>
<script language="javascript">
document.getElementById("warning").style.display = "block";
</script>
do you see any div with id warning on the above markup? no, there isn't any div at all. in fact there is no <body> yet!
So in order for this to work, your javascript must go after that div. put it at the bottom just before the </body>. See the following, which works:
<html>
<head>
</head>
<body>
<div id="warning" style="display:none;">hello</div>
<script language="javascript">
document.getElementById("warning").style.display = "block"
</script>
</body>
</html>
Now, about your code: if you do not want to move that big block of if you can just set a flag variable like
$need_to_show_warning = false;
if($user == "admin" && $pass == "admin")
{
$_SESSION['user']=$user;
?>
<script language="javascript">window.location.href='home.php' </script>
<?php
} else {
//What should I do here?
$need_to_show_warning = true;
}
then, AFTER your div:
<!-- Warning that I want to show if username or password is incorrect -->
<div id="warning" class="w3-container w3-red w3-text-white w3-card-2 w3-animate-opacity" style="position: relative;margin-top: 20px;display:none">
<span onclick="this.parentElement.style.display='none'" class="w3-closebtn">×</span>
<strong>Warning!</strong> Incorrect Username or Password!
</div>
<?php
if($need_to_show_warning)
{
?>
<script language="javascript">document.getElementById("warning").style.display = "block"; </script>
<?php
}

How about this.
<?php
session_start();
if(isset($_POST['login']))
{
$user = $_POST['user'];
$pass = $_POST['pass'];
if($user == "admin" && $pass == "admin")
{
$_SESSION['user']=$user;
?>
<script language="javascript">window.location.href='home.php' </script>
<?php
} else {
//What should I do here?
?>
<!-- Warning that I want to show if username or password is incorrect -->
<div id="warning" class="w3-container w3-red w3-text-white w3-card-2 w3-animate-opacity" style="position: relative;margin-top: 20px;">
<span onclick="this.parentElement.style.display='none'" class="w3-closebtn">×</span>
<strong>Warning!</strong> Incorrect Username or Password!
</div>
<!-- Login form -->
<form class="w3-container" action="" method="post">
</form>
<?php
}
}
?>
?>

Related

PHP read more read less - Magento 2

I made an read more read less script for my Magento 2 webshop. This is used on a category page where there are serval subcategorie blocks to choose, each subcategory has a description with.
The problem: if I click read more all the descriptions of the subcategories will expand in stead of only the description of the subcategory I clicked read moreI am starting to learn PHP and Magento 2 but I can't fix this, does someone know the solution?
<div class="product description product-item-description">
<div class="more">
<?php if ($_subCategory->getDescription()) {
$string = strip_tags($_subCategory->getDescription());
if (strlen($string) > 250) {
// truncate string
$stringCut = substr($string, 0, 250);
$string = substr($stringCut, 0, strrpos($stringCut, ' ')).'... Lees meer';
}
echo $string;
?>
</div>
<?php
}else {?>
<?php /* #escapeNotVerified */ echo $_attributeValue;
}
?>
</div>
<div class="less" style="display:none">
<?php echo $_subCategory->getDescription(); ?>
Lees minder
</div>
<script type="text/javascript">
console.log('test');
require(["jquery"],function($){
$('.readmore').on("click",function(){
$('.less').show();
$('.more').hide();
});
$('.readless').on("click",function(){
$('.less').hide();
$('.more').show();
});
});
</script>
</div>
This is because, when you type $('.less').hide(); this is grabbing every element with the attribute class='less'. This is the way I would overcome this:
Start by attaching a unique attribute to each <div class="more"> or <div class="less"> - in this case, we use the class attribute: (and move 'more' or 'less' to an id)
<div id="read-more-block" class="cat-<?php echo $_subCategory->getId(); ?>">
<!-- my "read more" content -->
<a class="link" href="#read-more-block">Read Less</a>
</div>
<div id="read-less-block" class="cat-<?php echo $_subCategory->getId(); ?>">
<!-- my "read less" content -->
<a class="link" href="#read-less-block">Read More</a>
</div>
We now have a read-more-block and a read-less-block for each subcategory. When we click the inside link a jQuery event should fire which will hide itself and display the other.
And then, in your jQuery:
$('#read-more-block .link').on('click', function() {
var $readLessBlock = $('#read-less-block.' + $(this).parent().attr('class'));
$readLessBlock.show(); //Show the read less block
$(this).parent().hide(); //Hide the read more block
});
..and vice versa for read less.

How to hide a message button in a website on logout action?

In my website, I want to hide my message button after logging out, message option should be disabled after logout..Using Javascript and PHP. People Can you please help me in this...
This is the button I want to hide after Logout
<div class="fixed-sidebar right fixed-sidebar-responsive">
<div class="fixed-sidebar-right sidebar--small" id="sidebar-right-responsive">
<a href="/messages" class="olympus-chat inline-items customHeaderMessage">
<svg class="olymp-chat---messages-icon"><use xlink:href="/svg-icons/sprites/icons.svg#olymp-chat---messages-icon"></use></svg>
</a>
</div>
</div>
what you can do is to store the current user id in a sesion then using jquery you can check if the current user is not null then display the button otherwise you can hide it .
like say your button has an id of myButton, you can do this
<?php
sesion_start()
$currentUser = sesion['user'];
?>
<html>
<head>
<script>
var myButton = getElementById("myButton");
if(currentUser != null ){
myButton.show();
}
else{ myButton.hide()}
</script>
</head>
<body>
....
</body>
</html>
You will need to add current user to session on login and then destroy the session on logout.
You can use sessions to hide message button by keeping a condition for that
<?php
session_start();
$_SESSION['login_user']= $username;
if ($_SESSION['login_user']!="admin") {
// your code
} else {
// your code
}
session_destroy();
?>

Execute JavaScript, into the divs opened previously with jQuery/JavaScript

I am doing a comment system. Yesterday I asked for the same problem in stackoverflow and I didn't get any answer. Now I have simplified the code, so I hope that its easier to understand. I also write complete code if someone what to try it.
The main HTML page has multiple divs:
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="http://code.jquery.com/jquery-3.0.0.min.js"></script>
<script type="text/javascript" src="jscripts/actions.js"></script>
</head>
<body>
<div class="comments_div" id="comments_div" data-id="22" >
div_22--->
<div class="comments_more_22" id="comments_more"> </div>
</div>
<br>
<div class="comments_div" id="comments_div" data-id="23" >
div_23--->
<div class="comments_more_23" id="comments_more"> </div>
</div>
<br>
<div class="comments_div" id="comments_div" data-id="24" >
div_24--->
<div class="comments_more_24" id="comments_more"> </div>
</div>
<br>
</body>
The jQuery/JavaScript functions open/hide the div and show the post_id (data-id). It works perfectly.
//Open div
$(function() {
$(".comments_div").click(function() {
var post_id = $(this).attr('data-id');
$.ajax({
url: "jscripts/comment.php",
type: "POST",
data: { post_id: post_id },
success: function(datos) {
$('.comments_more_' + post_id).html(datos);
$('.comments_more_' + post_id).show('slow');
//alert(post_id);
}
});
});
})
//Hide div
$(document).mouseup(function (e){
var container = $('div[id^="comments_more"]');
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{ container.hide('slow'); }
});
//Put text in some div
function showText()
{ document.getElementById("flash").textContent = 'works!';}
...and comment.php (here the code will be more complicated, with forms, captchas, etc)
<?php
echo 'post_id: ';
echo $_POST['post_id'];
?>
<div class="flash" id="flash">- </div>
<span style="margin-left:20px;"><small>click<a href='javascript: showText();'>here</a> </small></span><br/>
Nice, isn't it?.
But I need to execute another JavaScript: showText(). This script works when you click in this order: div_24, div_23, div_22. But stop works when you try click first div_22, then div_23,... etc.
Well I solved the problem: the div "flash" must have a unique id, so showText can find the correct div.
<?php
echo 'post_id: ';
echo $_POST['post_id'];
$post_id=$_POST['post_id'];
?>
<div class="flash" id="flash_<?php echo $post_id; ?>">- </div>
<span style="margin-left:20px;"><small>click<a href='javascript: showText();'>here</a> </small></span><br/>
<script type="text/javascript">
//Put text in some div
function showText()
{
var post_id = "<?php echo $post_id; ?>" ;
document.getElementById("flash_" + post_id).textContent = 'works!';
}
</script>
:P

Programmatically running action instead of using button

I want a box with a welcome message etc to appear after a user registrers on my website. But instead of making it appear from just clicking on a button, i want it to happend when the email,password,username etc gets sendt to the database. So, instead of doing this :
<button onclick="document.getElementById('id01').style.display='block'" style="width:auto;">Login</button>
Is there any ways i can do this programmatically? I have also tried :
<script>
self = function(id01)
</script>
but it wont work. Any tips on what i should try/ do?
This is how i send the info to my database :
//if no errors have been created carry on
if(!isset($error)){
$hashedpassword = $user->password_hash($_POST['password'], PASSWORD_BCRYPT);
$activasion = md5(uniqid(rand(),true));
try {
$stmt = $db->prepare('INSERT INTO members (username,password,email,active) VALUES (:username, :password, :email, :active)');
$stmt->execute(array(
':username' => $_POST['username'],
':password' => $hashedpassword,
':email' => $_POST['email'],
':active' => $activasion
));
$id = $db->lastInsertId('memberID');
//send email
$to = $_POST['email'];
$subject = "Registration Confirmation";
$body = "<p>Thank you for registering at Game World.</p>
<p>To activate your account, please click on this link: <a href='".DIR."activate.php?x=$id&y=$activasion'>".DIR."activate.php?x=$id&y=$activasion</a></p>
<p>Regards Site Admin</p>";
$mail = new Mail();
$mail->setFrom(SITEEMAIL);
$mail->addAddress($to);
$mail->subject($subject);
$mail->body($body);
$mail->send();
//redirect to index page
header('Location: index.php?action=joined');
?>
well you can achieve what the results you want in many ways, js alerts, jquery pop up. bootstrap modals.
Option 1 :
using jquery and jquery ui
<!-- latest stable jquery -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<!-- latest stable jquery ui -->
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
<?php
if(isset($_GET['action']) && !empty($_GET['action'])){
$action = $_GET['action'];
if($action == "joined"){?>
<div id="modal" style="display: none;">
This is pop up, add message.
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#modal").dialog();
});
</script>
<?php
}else{
//action != joined do something
}
}else{
//$GET NOT set do something
}
Option 2 :
Using Bootstrap
<!-- latest stable jquery -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<!-- Bootstrap links -->
<?php
if(isset($_GET['action']) && !empty($_GET['action'])){
$action = $_GET['action'];
if($action == "joined"){?>
<div class="modal fade" id="success">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<div class="alert alert-block alert-success">
<h4>Welcome</h4>
<p>Add Message</p>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$('document').ready(function(){
$('#success').modal('toggle'); });
</script>
<?php
}else{
//action != joined do something
}
}else{
//$GET NOT set do something
}
Option 3
Js alert
<?php
if(isset($_GET['action']) && !empty($_GET['action'])){
$action = $_GET['action'];
if($action == "joined"){?>
<script type="text/javascript">
alert('welcome');
</script>
<?php
}else{
//action != joined do something
}
}else{
//$GET NOT set do something
}
The first option, you will need to style the pop/div according to your design needs.
as you can see u need to first check if the action in the url is joined, meaning they have successfully signed up, then show the popup
You can do this using server side language PHP using $_GET['action'] or $_REQUEST['action'] on a proper return of your header - index.php?action=joined
Create logic on your DB insert page that checks to see if your query was successful. On success, it routes you to the header redirect, else returns an error message and exits the script.
Something like this:
$query = 'INSERT INTO members (username,password,email,active) VALUES (:username, :password, :email, :active)';
$stmt = $db->prepare($query);
$stmt->execute(array(
':username' => $_POST['username'],
':password' => $hashedpassword,
':email' => $_POST['email'],
':active' => $activasion
));
//Check to see if your $stmt is set, will return true if successful else it will return false
if($stmt){
$id = $db->lastInsertId('memberID');
//send email
$to = $_POST['email'];
$subject = "Registration Confirmation";
$body = "<p>Thank you for registering at Game World.</p>
<p>To activate your account, please click on this link: <a href='".DIR."activate.php?x=$id&y=$activasion'>".DIR."activate.php?x=$id&y=$activasion</a></p>
<p>Regards Site Admin</p>";
$mail = new Mail();
$mail->setFrom(SITEEMAIL);
$mail->addAddress($to);
$mail->subject($subject);
$mail->body($body);
$mail->send();
//redirect to index page
header('Location: index.php?action=joined');
}else{
echo 'Sorry but there was an issue with the INSERT.';
exit();
}
On index.php use an if/else statement or switch to check if $_GET['action'] (isset) and see if it is == to your value 'joined'. Then create a variable to hold your welcome message and display it else declare the variable null or post an alternate message perhaps.
Top of your index.php page:
$message = "";
if(isset($GET['action']) && $GET['action']=="joined"){
//place your Welcome message here
$message .= "<h2>Welcome and thank you for signing up!</h2>";
}else{
$message .= "<h2>Some other message</h2>";
//Or you could go with empty quotes or declare $message NULL
}
Then in your HTML call on your variable $message with something like:
<?=$message?> or <?php echo $message; ?>
<body>
<div id='wrapper'>
<header>Some header</header>
<nav id='nav'>
<ul>
<li class="nav-item">
BUTTON 1
</li>
<li class="nav-item">
BUTTON 2
</li>
</ul>
</nav>
<div id="content">
<?=$message?>
<div id="heading">Some Page Heading</div>
<div id="">
<p>
Some page content.
</p>
</div>
</div>
</div>
</body>
I am not the most proficient in PHP but this is probably how I would handle a server side request like this.
*** Keep in mind that you are requesting an update to your page on the update of your server, not a client side action like pressing the button.
Hope this helps.

Loading PHP Response with Jquery Ajax POST

I have a php script that loops over the results of a database query and prints them out. I am trying to load them into an Admin Interface Panel with AJAX, but to no avail. My job requires me to write mostly backend code, so I haven't gotten around to learning much JS/Jquery. Anyways, I have a page "insert.php" that has a button I want to click and have it call the results from the "posts.php" page. Here are my files
insert.php
Load Posts
</div>
</div>
<div class="row main">
<div class="small-8 columns" id="posts">
</div>
</div>
</div>
posts.php
<?php
require_once 'connect.php';
$user = 'admin';
$sql = "SELECT * FROM posts WHERE author = ?";
$stmt = $db->prepare($sql);
$stmt->bindParam(1, $user);
$stmt->execute();
$data = $stmt->fetchAll();
foreach ($data as $row)
{
$id = $row['id'];
$title = $row['title'];
$author = $row['author'];
$date = $row['date'];
$smalltext = $row['smalltext'];
$bodytext = $row['bodytext'];
$images = $row['images'];
$imagelist = split(' ', $images);
$shorttext = str_replace(
array("\r\n", "\n"),
array("</p><p>", "</p><p>"),
$smalltext);
echo
"
<div class='row main'>
<h1 class='padding-top-12 bottom-rule-green'>$title</h1>
<div class='small-2 columns'>
<p class='text-justify small-text'>
Post MetaData goes here
</p>
</div>
<div class='small-10 columns bottom-rule-red text-justify'>
<p>
$shorttext
";
foreach ($imagelist as $key => $value)
{
echo "<img src='users/$author/img/$value'>";
}
echo
"
</p>
</div>
</div>
<div class='row main small-text padding-top-1'>
<div class='small-2 small-oofset-2 columns'>
<a href='posts/$author/$id'>Edit Post</a>
</div>
<div class='small-4 columns'>
Timestamp: $date
</div>
<div class='small-4 columns'>
Author: <a href='users/$user'>$user</a>
</div>
</div>
";
}
?>
postAjax.js
$.ajaxSetup ({
cache: false
});
var loadUrl = "../../includes/posts.php";
$(function(){
$('#ajaxbtn').on('click', function(e){
e.preventDefault();
$('#ajaxbtn').fadeOut(300);
$.post(loadUrl, {language: "php", version: 5},
function(res){
$("posts").html(res)
}, "html");
});
});
This is the file that loads my scripts into the page
<!--Foundation Framework Necessities-->
<script type="text/javascript" src="../../assets/js/vendor/jquery.js"></script>
<script type="text/javascript" src="../../assets/js/foundation/foundation.min.js"></script>
<script type="text/javascript" src="../../assets/js/postAjax.js"></script>
<script type="text/javascript">
$(document).foundation();
</script>
When I click the #ajaxbtn button, it fades out so I know the JS is being called to that element onclick, but it doesn't post the results of posts.php. I think this may just be my misunderstanding of how Ajax works; if you would please tell me what I did wrong.
Try changing,
$("posts").html(res)
to
$("#posts").html(res)
Also I see some mistakes in your code in posts.php
You are not embedding php variables in strings properly.
I believe you need to use a delegated event. Change your code from:
$('#ajaxbtn').on('click', function(e)
to:
$('#ajaxbtn').on('click', 'a', function(e)
This way event handlers will fire as expected even if the contents of that parent element change. I had the same issue and this solved it. Good luck.

Categories