How can I make a form displayed only under its parent? - javascript

I'm creating a comment-reply function where I would like the reply-form to show up under its parent when users presses the "Reply"-button.
Right now my code makes the form show up under every comment and not only the specific "parent-comment-reply-button". How can I avoid the form on other comments?
My code looks like this:
HTML
<head>
<?php
include ('headCont.php');?>
</head>
<body>
<?php
include('navBar.php');?>
<div class="container">
<div class="row">
<div class="box">
<div>
<!------------container------->
<form action="" method ="POST">
Namn: <br>
<input type="text" name ="name"><br>
Kommentar: <br>
<textarea name="comment" placeholder="Ställ en fråga" rows="10" cols="20"></textarea><br>
<input type ="submit" name ="submit" value="Skicka">
</form><br>
</div>
<div>
<?php
include ('commentBox/storeComments.php');
include ('commentBox/getComments.php');?>
</div>
</div>
</div>
</div>
<!-- /.container -->
<footer>
<?php
include ('footer.php');
?>
</footer>
<!-- jQuery -->
<script src="jsOld/jquery.js"></script>
</body>
</html>
<script>
$(document).ready(function(){
$("#show").click(function(){
$(".reply-form").show();
});
$("#hide").click(function(){
$(".reply-form").hide();
});
});
</script>
getComments
<?php
include ('connectDB.php');
if($connect){
mysqli_select_db($connect, "comments");
$query2 = "SELECT * FROM data ORDER BY `id` DESC";
$result = mysqli_query($connect, $query2);
$comments = array();
while($row = mysqli_fetch_array($result)){
$name = $row['name'];
$comment = $row['comment'];
$date = $row['date'];
echo "
<div style='width:60%' class='col-lg-12'>
<div class='panel panel-default'>
<div class='panel-heading'>
<strong> $name </strong><span style='float:right'class='text-muted'>$date</span>
</div>
<div class='panel-body'>$comment
<button id='show' style='float:right'>Reply</button>
</div>
</div><!-- /panel panel-default -->
</div><!-- /col-sm-5 -->";
echo " <div class='col-lg-12 padd'>
<form method='POST' action='' class='reply-form'>
Namn:<br>
<input name='_method' type='text'</input><br>
Kommentar:<br>
<textarea name='reply_comment' cols='50' rows='10'></textarea>
<div class='button-group'>
<input type='submit' name='submit_reply' value='Skicka'></input>
<button id='hide' type='submit' name='close' value='Stäng'>Stäng</input>
</div>
</form>
</div>";
}
}
?>
Output

You need to create the form inside the parent DOM. Which means, the following like should be at the end of the your send echo statement. And the .reply-form should be hidden initially using css.
</div><!-- /col-sm-5 -->";

The HTML IDs show and hide can appear multiple times in your DOM, keep in mind that HTML ids should be unique. So it would be best to change it to classes.
Now to the answer your question you could try to add a counter, this basically connects the form to the show button, example:
<button id='show' style='float:right' data-counter="0">Reply</button>
<form method='POST' action='' class='reply-form reply-form-0'>
$("#show").click(function(){
var counter = $(this).data("counter");
$(".reply-form-"+counter).show();
});

Related

How to put php code into html button

I want to put function type submit in a button with CSS style and when the button is clicked the PHP code run.
This is my code:
</head>
<body>
<div class="container-contact100">
<div class="wrap-contact150">
<form class="contact150-form validate-form">
<div class="row">
<div>
<h1><br>HOME AUTOMATION</br></h1>
</div>
</div>
<div class="row">
<div>
<h3><br>LAMPU</br></h3>
</div>
</div>
<div class="row">
<div>
<td><p style=\"font-family:arial;color:red;font-size:35px;\">OFF</p> </td>
</div>
</div>
<div class="row">
<div>
<br><button class="contact100-form-btn">
On
</button></br>
</div>
<div class="col-sm-5">
<br><button class="contact100-form-btn">
Off
</button></br>
</div>
</div>
</form>
<?php
include 'connect.php';
function OnOne()
{
$sql = "UPDATE relay SET data_relay = '1' WHERE id = '1';
$result = mysqli_query($conn, $sql);
}
function OffOne()
{
$sql = "UPDATE relay SET data_relay = '0' WHERE id = '1';
$result = mysqli_query($conn, $sql);
}
if(isset($_POST['on_1']))
{
OnOne();
}
if(isset($_POST['off_1']))
{
OffOne();
}
?>
</div>
</div>
</body>
</html>
After I applied this code my web interface become messy. How I can fix this?
I want my CSS button run the PHP code to send a value to database.
Put your php code in seperate file, wrap button into form and add action="path-to-your-php-file"

JS function to create a dropdown filled with names from a DB onclick?

I need help writing this small piece of code. I need a function that creates a dropdown menu that is filled with names from a Database when a button is clicked. The names in the dropdown list will eventually be submitted to a different table in the database, so I need to know how to set the names as "vales" in the dropdown list also. What would be the best way to go about implementing these issues? I've commented out where I think things should go.
Javascript:
var room = 1;
function ReviewForm() {
room++;
var objTo = document.getElementById('ReviewForm')
var divtest = document.createElement("div");
divtest.setAttribute("class", "form-group removeclass" + room);
var rdiv = 'removeclass' + room;
divtest.innerHTML =
'<hr>' +
'<h2>Student:</h2>' +
'<select>' +
//Instead of these three names, I need to use the DB's info go generate the text and values
'<option value="Adam">Adam</option> ' +
'<option value="Bob">Bob</option> ' +
'<option value="Cat">Cat</option>' +
'</select></h2>' +
objTo.appendChild(divtest)
PHP:
<?php
$NumberOfStudents = "";
// $NumberOfStudents=$_GET['SelectedStudents'];
$hostname = "host";
$username = "user";
$password = "pass";
$databaseName = "_db";
$conn ;
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
/*if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} */
//BELOW IS THE QUERY FROM THE DB THAT I AM TRYING TO GET TO REPRINT EACH TIME THE FUNCTION IS CALLED
$query = "SELECT concat (FirstName,' ', LastName) as StudentNames FROM `Student`";
$result = mysqli_query($connect, $query);
?>
HTML:
<body>
<!-- Wrapper -->
<div id="wrapper">
<!-- Main -->
<div id="main">
<div class="inner">
<!-- Content -->
<section>
<!-- Form -->
<form method="post" action="#">
<div class="row uniform">
<!-- Break -->
<div class="12u$">
<div style="height:550px;border:1px solid #ccc;font:16px/26px Georgia, Garamond, Serif;overflow:auto;"><!-- container for reviews-->
<div id="ReviewForm">
<hr>
<h2>
Student:
<select>
<!-- It is hardcoded into the page here, which is fine, but I would rather it generate when the page is loaded, and then can
be called again each time a new dropdown is needed. -->
<?php while($row1 = mysqli_fetch_array($result)):;?>
<option value="<?php echo $row1['StudentNames'];?>"><?php echo $row1['StudentNames'];?></option>
<?php endwhile;?>
</select>
</h2>
</div>
</div>
</form>
<input type="hidden" name="count" value="1" />
<div class="control-group" id="fields">
<label class="control-label" for="field1"></label>
<div class="controls" id="profs">
<form class="input-group-btn">
<div>
<!--Here is the button that calls the function for a new dropdown menu-->
<button class="btn btn-success" type="button" onclick="ReviewForm();">Add another student</button>
</div>
</form>
<br>
<br>
</div>
</div>
</section>
</div>
</div>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/skel.min.js"></script>
<script src="assets/js/util.js"></script>
<!--[if lte IE 8]><script src="assets/js/ie/respond.min.js"></script><![endif]-->
<script src="assets/js/main.js"></script>
</body>

Same structure, but Ajax success response acts differently from previous version

Have been working on a form with Ajax and used to work on a version with no extras (css and so on) before. It worked all fine, data has been inserted successfully into the database and I have been able to show and hide two divs.
Now I used to apply it to the form I've been working on. It acts different from the previous version, so it's exactly the same (sure, changed some names, added some inputs), like no "success message" from the PHP-file, suddenly all data visible in the URL, the current form doesn't hide and shows the next one.
I can't understand the sudden change in behavior, took a look for mistakes, compared the codes, but have no idea. It seems to be such a small mistake that I don't spot it or something is wrong with the whole construction.
The current file is:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?
require 'config.php';
session_start();
// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
$_SESSION['message'] = "You must log in before viewing your profile page!";
header("location: error.php");
}
else {
// Makes it easier to read
$id = $_SESSION['id'];
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$active = $_SESSION['active'];
$hash = $_SESSION['hash'];
}
?>
<script type="text/javascript">
function getState(val) {
$.ajax({
type: "POST",
url: "demo_ajax.php",
data:'country_id='+val,
success: function(data){
$("#region").html(data);
}
});
}
$(document).ready(function(){
$("#submit").click(function(){
var size=$("#size").val();
var industry=$("#industry").val();
var country=$("#country").val();
var region=$("#region").val();
var url=$("#website").val();
var fb=$("#fb").val();
var lkdn=$("#lkdn").val();
$.ajax({
type:"post",
url:"process2.php",
data:"size="+size+"&industry="+industry+"&country="+country+"&region="+region+"&url="+url+"&fb="+fb+"&lkdn="+lkdn,
success:function(data){
$("#theform").hide();
$("#info").html(data);
//$("#partone").css();
$("#partone").show();
alert("Hello");
}
});
});
});
</script>
<?php include 'js/js.html'; ?>
<?php include 'css/css.html'; ?>
</head>
<body class="w3-blue r_login_corp_body">
<div id="info" style="color:white"></div>
<div class="r_login_corp_body"></div>
<div class="w3-content w3-white r_siu r_centered_div">
<header class="w3-camo-black w3-container">
<div class="w3-container ">
<span class="w3-xlarge r_caption">eRecruiter</span> <span class="large">Corporate Login</span>
</div>
<div class="w3-black">
<a href="javascript:void(0)" onclick="selectForm('register');">
<div class="w3-half tablink w3-hover-text-yellow w3-padding w3-center w3-padding-16">Register</div>
</a>
</div>
</header>
<!-- Register -->
<div id="register" role="form" class="r_form_elements">
<form name="formone" class="form" autocomplete="off">
<div id="profed" class="w3-container w3-padding-16">
<div class="alert alert-error"></div>
<label>Company Industry</label>
<input class="w3-input" name="industry" id="industry" type="text" placeholder="Your Industry" >
<label>Company Size</label>
<input class="w3-input" name="size" id="size" type="integer" placeholder="Your Company Size" >
<label >Country:</label>
<select name="country" id="country" class="demoInputBox" onChange="getState(this.value);" >
<option value="">Select Country</option>
<?php
$sql1="SELECT * FROM pentagonal_country";
$results=$mysqli->query($sql1);
while($rs=$results->fetch_assoc()) {
?>
<option value="<?php echo $rs["country_code"]; ?>"><?php echo $rs["country_name"]; ?></option>
<?php
}
?>
</select>
<label>State:</label>
<select id="region" name="region" onKeyup="checkform()">
<option value="">Select State</option>
</select>
<label>Website</label>
<input class="w3-input" name="website" id="website" type="url" placeholder="Your Website-Address" >
<label>Facebook</label>
<input class="w3-input" name="fb" id="fb" type="url" placeholder="https://facebook.com/" >
<label>Linkedin</label>
<input class="w3-input" name="lkdn" id="lkdn" type="url" placeholder="https://linkedin.com/in/">
</div>
<div class="w3-row">
<button type="submit" id="submit" class="w3-button w3-black w3-half w3-hover-yellow" >Add</button>
<button class="w3-button w3-black w3-half w3-hover-pale-yellow">Forgot Password</button>
</div>
</form>
</div>
<!-- Register -->
<div id="partone" style="display:none">
<form>
name : <input type="text" name="name" id="name">
</br>
message : <input type="text" name="message" id="message">
</br>
</br>
name : <input type="text" name="url" id="url">
</br>
message : <input type="text" name="fb" id="fb">
</br>
name : <input type="text" name="lkdn" id="lkdn">
</br>
</br> </br>
Send;
</form>
</div>
</div>
</body>
</html>
and the PHP-file to insert data is:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "remotejobs";
session_start();
// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
$_SESSION['message'] = "You must log in before viewing your profile page!";
header("location: error.php");
}
else {
// Makes it easier to read
$id = $_SESSION['id'];
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$active = $_SESSION['active'];
$hash = $_SESSION['hash'];
}
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$industry=$_POST["industry"];
$size=$_POST["size"];
$country=$_POST["country"];
$region=$_POST["region"];
$website=$_POST["url"];
$fb=$_POST["fb"];
$lkdn=$_POST["lkdn"];
$usrid=$id;
$sql = "INSERT INTO corp_user_profile (id, industry, size, nation, region, url, facebook, linkedin)
VALUES ('$usrid', '$industry','$size', '$country', '$region', '$website', '$fb', '$lkdn')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
I used to work with the previous file I've worked with just to be sure that everything's right after a week of bug fixing.
Can somebody tell me where the problem is, probably why it is a mistake to avoid future problems like this?
The most obvious bug (aside from the SQL injection stuff mentioned above) is that
<button type="submit" will cause the form to submit normally via postback, unless you prevent it using script. Add event.preventDefault() to the first line of your "click" handler.
$("#submit").click(function(event){
event.preventDefault(); //prevent default postback behaviour
var size=$("#size").val();
//...etc
You're seeing the data in the URL because the form is posting normally (before the ajax has chance to run) and doing a GET because there's no other method specified in the form's markup, and GET is the default..
You may want to prevent the default behavior by passing the event to your click function and calling event.preventDefault().

Hide/Show toggle echo results in php

I am trying to toggle results i have echo'd out of table but i am having no luck.
I have tried the same code in HTML and it works perfectly.
Ive been working on this for a while now, and was wondering if someone could point me in the right direction.
What I've tired
Adding the javascript inside the php echo.
Adding a counter to the id, to make it unique on loop
Placing each line of the echo results in echo(""); tags.
adding a counter, to make the id unique on loop.
PHP
$i = 1;
while ($output = $fc_sel->fetch_assoc()) {
$fc_run .= $output['Food_Cat_name'] . $output['Food_Cat_Desc'] . '<br>';
$_SESSION['Food_Cat_name'] = $output['Food_Cat_name']; //echo out product name
$_SESSION['Food_Cat_Desc'] = $output['Food_Cat_Desc']; //echo out product desc
echo"
<div id='first_product'>
<button onclick='toggle_visibility('tog')'>Toggle</button>
<div id='tog'>
<div id='red_head'>
<p id='menu_title' class ='hidden' onclick='toggle_visibility('tog')'> Add your first menu item</p>
</div>
<h3 id='menu'>Menu Section</h3>
<form name='first_prod' id='first_prod' enctype='multipart/form-data' action='testing.php' method='POST' accept-charset='utf-8' >
<label id='cat_label' name='cat_label'>Name</label>
<input type='text' id='cat_name' name='cat_name' value=''>
<label id='desc_label' name='desc_label'>Description</label>
<input type='text' id='cat_desc' name='cat_desc' value=''>
</form>
</div>
</div>
";
}
}
JAVASCRIPT
<script>
//turn entire div into toggle
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block' || e.style.display == '')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
The single quotes in onclick='toggle_visibility('tog')' are conflicting with the outer single quotes. So either escape them or use double quotes in either the outer pair or the inner pair.
Then in PHP, remove the <?php echo. Just put the HTML in PHP. The echo only complicates things. If you need dynamic data in your HTML, just inject it at that place with <?php ... ?>. But so far I haven't seen any of that in your HTML: it is static.
Here is a working snippet, after having made that change in two places:
//turn entire div into toggle
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block' || e.style.display == '')
e.style.display = 'none';
else
e.style.display = 'block';
}
<div id='first_product'>
<button onclick="toggle_visibility('tog')">Toggle</button>
<div id='tog'>
<div id='red_head'>
<p id='menu_title' class ='hidden' onclick="toggle_visibility('tog')"> Add your first menu item</p>
</div>
<h3 id='menu'>Menu Section</h3>
<form name='first_prod' id='first_prod' enctype='multipart/form-data' action='testing.php' method='POST' accept-charset='utf-8' >
<label id='cat_label' name='cat_label'>Name</label>
<input type='text' id='cat_name' name='cat_name' value=''>
<label id='desc_label' name='desc_label'>Description</label>
<input type='text' id='cat_desc' name='cat_desc' value=''>
</form>
</div>
</div>
Edit after modification of the question
The code in the question was extended so the HTML is produced in a loop now.
You should now take care to produce unique id values only. So you'll probably want to add <?=$i?> at several places, like this:
<?php
session_start();
// ....
$i = 1;
while ($output = $fc_sel->fetch_assoc()) {
$fc_run .= $output['Food_Cat_name'] . $output['Food_Cat_Desc'] . '<br>';
$_SESSION['Food_Cat_name'] = $output['Food_Cat_name'];
$_SESSION['Food_Cat_Desc'] = $output['Food_Cat_Desc'];
?>
<div id='first_product<?=$i>'>
<button onclick="toggle_visibility('tog<?=$i>')">Toggle</button>
<div id='tog<?=$i>'>
<div id='red_head<?=$i>'>
...etc. Note that the PHP was closed before the HTML output started. Do this, instead of a large echo. Then at the end of it, open PHP tag again to end the loop:
<?php
}
?>
please modify your code
echo "
<div id='first_product'>
<button onclick='toggle_visibility(\"tog\")'>Toggle</button>
<div id='tog'>
<div id='red_head'>
<p id='menu_title' class ='hidden' onclick='toggle_visibility(\"tog\")'> Add your first menu item</p>
</div>
<h3 id='menu'>Menu Section</h3>
<form name='first_prod' id='first_prod' enctype='multipart/form-data' action='testing.php' method='POST' accept-charset='utf-8' >
<label id='cat_label' name='cat_label'>Name</label>
<input type='text' id='cat_name' name='cat_name' value=''>
<label id='desc_label' name='desc_label'>Description</label>
<input type='text' id='cat_desc' name='cat_desc' value=''>
</form>
</div>
</div>
"
<button value='tog' onclick='toggle_visibility(this)'>Toggle</button>
Just use "this" and assign value to button its working
Try this ;)
<?php
$i = 1;
while($output = $fc_sel->fetch_assoc()){
$fc_run .= $output['Food_Cat_name'] . $output['Food_Cat_Desc'] . '<br>';
$_SESSION['Food_Cat_name'] = $output['Food_Cat_name']; //echo out product name
$_SESSION['Food_Cat_Desc'] = $output['Food_Cat_Desc']; //echo out product desc
?>
<div id="first_product<?php echo $i; ?>">
<button onclick="javascript:toggle_visibility('tog<?php echo $i; ?>')">Toggle</button>
<div id="tog<?php echo $i; ?>">
<div id="red_head<?php echo $i; ?>">
<p id="menu_title<?php echo $i; ?>" class ="hidden" onclick="toggle_visibility('tog<?php echo $i; ?>')"> Add your first menu item</p>
</div>
<h3 id="menu<?php echo $i; ?>">Menu Section</h3>
<form name="first_prod" id="first_prod<?php echo $i; ?>" enctype="multipart/form-data" action="testing.php" method="POST" accept-charset="utf-8">
<label id="cat_label<?php echo $i; ?>" name="cat_label">Name</label>
<input type="text" id="cat_name<?php echo $i; ?>" name="cat_name" value="">
<label id="desc_label<?php echo $i; ?>" name="desc_label">Description</label>
<input type="text" id="cat_desc<?php echo $i; ?>" name="cat_desc" value="">
</form>
</div>
</div>
<?php
$i++;
}
?>

I'm trying to get the id when clicking different messages from sql database

I'm trying to get the id when I click different messages.
This is my javascript:
$(document).ready(function() {
$('#message-subject-result').click(function(){
var message = document.getElementById('message_id').value;
alert(message);
});
});
I am pulling it from a php function that is:
<div id="message-subject-result">
<div id="message-date">'.$date.'</div>
<input type="hidden" id="message_id" value="'.$row['mes_id'].'"><div id="message-sender-name">FROM: '.$row['firstname'].' '.$row['lastname'].'</div>
<div id="message-subject">SUBJECT: '.$row['subject'].'</div>
<div id="message-preview">'.$row['message'].'</div>
</div>
The javascript works but only when I click on the first echoed result. What am I doing wrong?
Replace duplicating ids with classnames and use find method:
$('.message-subject-result').click(function() {
var messageId = $(this).find('.message_id').val();
alert(messageId);
});
valid HTML should be:
<div class="message-subject-result">
<div clas="message-date">'.$date.'</div>
<input type="hidden" class="message_id" value="'.$row['mes_id'].'">
<div class="message-sender-name">FROM: '.$row['firstname'].' '.$row['lastname'].'</div>
<div class="message-subject">SUBJECT: '.$row['subject'].'</div>
<div class="message-preview">'.$row['message'].'</div>
</div>
You must have all unique ids. Something like this will give you unique id's:
<?php
$i = 0;
foreach($result as $row) { ?>
<div id="message-subject-result">
<div id="message-date">'.$date.'</div>
<input type="hidden" id="message_id<?php echo $i; ?>" value="'.$row['mes_id'].'"><div id="message-sender-name">FROM: '.$row['firstname'].' '.$row['lastname'].'</div>
<div id="message-subject">SUBJECT: '.$row['subject'].'</div>
<div id="message-preview">'.$row['message'].'</div>
</div>
<?php $i++;
} ?>

Categories

Resources