Good day everyone,
I have the following code structure. This code structure loads a page with different post subject and content on it. For each loaded post, a user can leave a comment. Have a look at the following code:
<?php
$getposts = "SELECT * FROM posts";
if ($result = $con->query($getposts)) {
while ($row1 = $result->fetch_assoc()) {
$id = $row1['id'];
$subject = $row1['sub'];
$content = $row1['body'];
$comments = $row1['comments'];
echo"
<div class='content_wrap'>
<div class='subject'>$subject</div>
<div class='content'>$content</div>
<div class='comment'>$comments</div>
</div>
";
?>
<form id='reply' autocomplete="off">
<input type="hidden" value="<?php echo $id;?>" name="id" id="pid"/>
<input type="text" name="comment" id="comment" placeholder="Type a commmment here..."></input>
</form>
<?php
}
}
?>
<script type="text/javascript">
$('form').submit(function () {
var comment = $(this).find('input[name=comment]').val();
var id = $(this).find('input[name=id]').val();
$.post("comments_ins.php", { pub_id: id, comment: comment});
$(this).parent().children('.content_wrap').append("<div
class='comment'" + comment + "</div");
var comment = $(this).find('input[name=comment]').val('');
return false;
});
</script>
All of the above codes I currently have in one page...and the file is a php file type.
Notice that there is a form generated for each loaded post on the page according to the while loop.
The code above works about 90 percent correct. But one thing I don't seem to get right.
I want that when a user leaves a comment, that the comment displays on the page for that post only....nut all of the loaded posts on the page.
So, if a user types a first comment, it is visible, and, if the user types another comment on to that same post, the new comment falls under the previous comment posted....and is visible ....so that it appends to a div element each time a user types a comment.
How do I go about accomplishing this?
If you look at my javascript above, I made an attempt but it did not work for me.
Guidance would be appreciated.
Thanks
try appending an ID to your divs so you can locate them more easily
$id = $row1['id'];
$subject = $row1['sub'];
$content = $row1['body'];
$comments = $row1['comments'];
echo"
<div class='content_wrap'>
<div class='subject' id=subject_$id>$subject</div>
<div class='content' id=content_$id>$content</div>
<div class='comment' id=comment_$id>$comments</div>
</div>
";
This should let you append to only the div you want it on.
Related
So far i have such code
<form action="register.php" target="login" type=post>
<label for="name">Account </label><br><br>
<input type=text id="name" name="account" size=20 maxlength=<?php Echo MaxNameLength; ?> /><br><br>
<label for="name">Password</label><br><br>
<input type=text id="name" name="password" size=20 maxlength=<?php Echo MaxNameLength; ?> /><br><br>
<button type=submit>Register</button>
</form>
I placed it inside an IFrame but when i try to use php with such code:
<?php
If (IsSet($_GET["account"]["password"])) { $Account = $_GET["account"]; $Password = $_GET["password"];
$AllRight = True;
For ($I=0; $I<StrLen(WrongChars); $I++) {
If (StrPos($Account, SubStr(WrongChars,$I,1))) {
Echo "<p>Your Name musn't contain the char \"".SubStr(WrongChars,$I,1)."\"</p>";
$AllRight = False;
}
}
If (file_exists(AccountFilesPath.$Account.AccountFilesEnding)) {
Echo "<p>This Account already exists!</p>";
$AllRight = False;
}
If ($AllRight) {
$Text .= "$Password ";
File_Put_Contents (AccountFilesPath.$Account.AccountFilesEnding, $Text);
if(!file_exists(AccountFilesPath.$Account.AccountFilesEnding)) {
echo "<p>Error during account cration!</p>";
}
Echo "<p>This Account is created succesfully!</p>";
}
}
?>
yet the responce im getting is a fresh registration page with no work done...
i want my iframe to individually register text files like (user1.txt) with ($Password) inside. Along with having a link to the login, and upon login have a User Control Panel.
I don't understand why you are using an iframe for this but I can see that you use $_GET in your php when your form submits $_POST (type="post")
Try changing that in your PHP code and see if it works
Edit*
As stated in the comments this is not a $_GET index $_GET["account"]["password"]
Let's say you stick with POST since your html form submits a POST,you must use something like this:
if(isset($_POST["account"]) && isset($_POST["password"]))
And to be sure what variables you get from your form, I recommend you to print your Post array before any manipulation.
print_r($_POST);
I have a form.php file that redirects to a sendformdata.php file when I submit the form. However, I can't get the sendformdata.php file to display an error message within the form when the proper fields aren't filled out.
I am simply redirected to the include file, db_connect.php, which shows up as a blank page. How can I get the page to stay on form.php and display an error message in html? This is my current sendformdata.php file:
<?php
include_once('db_connect.php');
$lokotitle = $description = $category = $showyourname = $yourname = $lat = $lng = "";
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$lokotitle=$_POST['lokotitle'];
$description=$_POST['description'];
$category=$_POST['category'];
$showyourname=$_POST['showyourname'];
$yourname=$_POST['yourname'];
$lat=$_POST['lat'];
$lng=$_POST['lng'];
// Validation will be added here
if(empty($lokotitle)) {
$error_message = "Please input a Loko title.";
?><script>$('#notitle'.text($error_message));</script><?php
exit;
}
if(!isset($error_message)){
//Inserting record in table using INSERT query
$insqDbtb="INSERT INTO `new`.`web_form`
(`lokotitle`, `description`, `category`, `showyourname`, `yourname`, `lat`, `lng`) VALUES ('$lokotitle', '$description', '$category', '$showyourname', '$yourname', '$lat', '$lng')";
mysqli_query($link,$insqDbtb) or die(mysqli_error($link));
?><script>window.location.href = "../index.php"; </script> <?php
exit;
}
}
?>
This is a section of form.php that I am trying to display an error message in:
<form class="form-horizontal" role="form" action="handleform/sendformdata.php" method="POST">
<legend></legend>
<div class="form-group">
<label for="lokotitle" class="col-sm-2">Loko Title</label>
<div class="col-sm-4">
<input type="text" class="form-control" name="lokotitle" id="lokotitle" placeholder="Title">
<span id="notitle"></span>
</div>
Thanks in advance for the help!
I recommend you to use both html5 required attribute which will force the user to enter the data. But remember the user can bypass front end validation (by means of inspect element), hence back end validation is also necessary.
Use required attribute like:
<input type="text" required />
You can try this
if(empty($lokotitle)) {
$error_message = "Please input a Loko title.";
echo "<script>
document.getElementById('#notitle').value='".$error_message."';".
"</script>";
exit;
}
Let me know if this solves your problem
I have a html file which loads a list from my database and allows the front end user to remove a particular entry.
The HTML Code looks like this:
<script type="text/javascript">// <![CDATA[
function sendForm() {
var dataSend=$("#clientid").val();
$("#responseDiv").html("<h2>Removing from Database...</h2>");
$.post("RemoveClient.php",{
ClientId: dataSend
},function(data) {
$("#responseDiv").html(data);
$("#clientlist").empty();
$("#clientlist").html("{client_list nocache}");
});
return false;
}
// ]]></script>
</p>
<div id="MainForm"><form class="form" onsubmit="return sendForm()">
<h2 class="formstyle">Client Wizard</h2>
<p>Please fill all the required fields.</p>
<div id="clientlist">{client_list nocache}</div>
<p><input style="font-size: 1.5em; font-color: #000000;" onclick="sendForm()" type="submit" value="Delete" /></p>
</form>
<div id="responseDiv"> </div>
</div>
The UDT called for {client_list} is given below.
$dbhost='127.0.0.1';
$dbuser='user';
$dbpass='pass';
$dbname='dbname';
$conn=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if(!$conn)
{
die('Could not connect:'.mysqli_connect_error());
}
$sql="SELECT clientid,clientname FROM client order by clientid";
echo "<label> Select Client: </label>";
echo "<select id=clientid name=clientid>";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($result))
{
echo "<option value=".$row['clientid'].">".$row['clientname']."</option>";
}
echo "</select>";
Now, once I click on delete, I want the drop down list to refresh with the new list not having the deleted client. I tried doing that by emptying the div and then reloading the UDT. Unfortunately this does not seem to be working, the way I want it to, as the list does not get refreshed until and unless I refresh the page. Is there anyway I can make this work?
The quick/easiest option would be to assign it an id and to remove the entry via javascript.
Second, would be to have RemoveClient.php return it as part of the response from the AJAX.
var response = data.split('|');
$("#responseDiv").html(response[0]);
$("#clientlist").html(response[1]);
Third, I would strongly advise against this way but it is the question you ask, put the UDT alone on new page then load the page with the ?showtemplate=false parameter.
$("#clientlist").load("//www.mydomain.com/myudt.html?showtemplate=false");
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm currently in the process of creating a reservation page for our company. What I would like to do is have it to where when the user clicks the Reserve Now Button a form pops up for them to complete. After the user completes the form the reserve button is disabled permanently to everyone accessing the site. How can I accomplish this? I am not very well versed in java script or php. Any help would be greatly appreciated.
<div class="container">
<div class="row">
<div class="col-lg-12">
<table class="table table-striped">
<tr>
<td>Product</td>
<td>RESERVE NOW</td>
</tr>
</table>
<form>
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
</div>
</div>
</div>
I have mocked up an example that can be found here:
https://jsfiddle.net/rman215/gw2m53w9/1/
If I understood you you want to provide ability ti reserve something, but only for 1 person, right?
So, you can store flag in database (for example in disabled_at [timestamp, default = null] column). When somebody click on button and call processing page (via ajax or simple redirect) set flag disabled_at value NOW(). And each time on processing page is disabled_at IS NULL. If yes - save first and last name to database.
On page with form need to add attribute disabled to submit button if disabled_at IS NOT NULL
EDIT:
disable.php
<?php
function reserveItem($name = null, $value = null)
{
$name .= '.reserved';
$value = $value ? $value : 1;
return file_put_contents($name, $value);
}
function isDisabled($name = null)
{
return file_exists($name . '.reserved');
}
$disabled = isDisabled('item1');
if (isset($_POST['submit'])) {
$name = isset($_POST['firstname']) ? $_POST['firstname'] : '';
$lastName = isset($_POST['lastname']) ? $_POST['lastname'] : '';
if (!$disabled) {
reserveItem('item1', $name . $lastName);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<table class="table table-striped">
<tr>
<td>Product</td>
<td>RESERVE NOW</td>
</tr>
</table>
<form method="post" action="disable.php">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit" <?= $disabled ? 'disabled' : ''; ?>>
</form>
</div>
</div>
</div>
</body>
</html>
Note: code written in editor only and not tested.
give id to submit button and on click of submit call this function
function disableButton() {
$("#idOfButton").attr("disabled","disabled")
}
After form submit you will get the success response. After getting success just disable the Reserve Now Button using this code :
If you are using ajax to submit form then you need to do that :
suppose Reserve Now Button id : reserve_btn_id
$.ajax({
// your code....
}).done(function() {
$("#reserve_btn_id").attr("disabled","disabled");
});
Since JavaScript is executed every time a client loads the page, you cannot insert JavaScript code to block the button.
I suggest you to use a simple MySQL database, something like:
CREATE TABLE Items(
ItemID INTEGER AUTO_INCREMENT PRIMARY KEY,
Description VARCHAR(255),
IsReserved TINYINT(1) //this works like a boolean
);
So that your page will have a select of all items, something like this:
SELECT * FROM Items ORDER BY ItemID
And then you will print them with something like this:
$server = "localhost";
$username = "root";
$password = "root";
$database = "mydatabase";
$connection = mysqli_connect($server, $username, $password, $database);
$result = mysqli_query($connection, "SELECT * FROM Items ORDER BY ItemID");
if (mysqli_num_rows($result) > 0){
echo("<form action=\"mypage.php\" method=\"post\">");
while($row = $result->fetch_assoc()){
echo("input name=\"id\" type=\"hidden\" value=" . $row['ItemID'] . ">"); //this input type hidden isn't shown on the page but we use it to store the id of the item so that we can retrieve it on the PHP page on submit
echo("ID: " . $row['ItemID']);
echo("Description: " . $row['Description']);
if ($row['IsReserved'] == 1){
echo("<button class=\"mybutton\" type=\"submit\" disabled>Reserve</button>");
}
else{
echo("<button class=\"mybutton\" type=\"submit\">Reserve</button>");
}
}
echo("</form>");
}
else{
echo("No data");
}
Then to update the status of an item that is reserved, just update the status when the form has been submitted to the other PHP page, you will have something like this:
$server = "localhost";
$username = "root";
$password = "root";
$database = "mydatabase";
$connection = mysqli_connect($server, $username, $password, $database);
$id = (int) $_POST['id']; // here you get the id of the hidden input
// $data = mysqli_query($connection, "SELECT * FROM Items WHERE ItemID = $id");
/* $data now contains all info stored about the item, you can use it if you
need to insert those info in another table, etc. */
// UPDATING STATUS
mysqli_query($connection, "UPDATE Items SET IsReserved = 1 WHERE ItemID = $id");
mysqli_close($connection);
So this is it, basically, I hope it helps you with your project :)
I leave you this guide on how to handle Forms & their data with PHP.
I'm working on a live discussion form. The page loads the threads from MySQL, and refreshes via AJAX every 4 seconds. After the last comment on each thread, there's a text input for comments (very similar to Facebook).
Everything works fine, except that when the user is writing in the input and the page refreshes, the message disappears. Security and privacy is the main goal on this project, that's why I don't want to use cookies. I have tried many solutions, and searched several hours for a solution but nothing seems to work.
Is it a possible solution to $_post every time that page refreshes?
In case of caching the entered values and retrieving them from $_session or local storage, can anyone suggest a more specific approach? i.e: where to put the listeners :)
I've tried to make a function that prevents reloading the page if the value of the input is different to "", but even this didn't work for me.
Here is my refresh code:
<script type="text/javascript">
var PHP = "msgboard.php";
function updateShouts(){
$('#msgboard').load(PHP);
}
window.setInterval( "updateShouts()", 4000 );
</script>
And here is the main PHP function:
while($row = mysql_fetch_array($resultados)) {
echo '<div class="post">
<div class="user"><b>'.$row["user"].'</b></div>';
echo ' <div class="txt">'.$row["msg1"].'</div>
</div>';
$sql2="SELECT * FROM table WHERE masterid = '".$row['id']."'ORDER BY id ASC";
$resultados2 = mysql_query($sql2);
while($row2 = mysql_fetch_array($resultados2)) {
echo '<div class="comment">
<div class="txt"><b>'.$row2['user'].'</b>';
echo ' '.$row2['msg1'].'</div>
</div>';
}
echo '<div class="commentform">
<form action="board.php" method="post">
<input type="text" size="75" name="message" id="message1">
<input type="hidden" name="masterid" value="'.$row['id'].'">
<input type="submit" name="Submit" value="Enviar"></form>
</div>' ;
}
Thanks in advance!
As #aziz pointed out in the comments, if you just want to update the comments, you only need to update that part of your page.
Step 1: Add a container to the comments so you can target the update to that container
You will notice there is now a new div <div id="comments_contaner"> in the code which will contain all the comments.
Also when you are outputting HTML, it is easier / more legile to just close the PHP tag and use <?= $variable ?> if you need to place a PHP variable in the HTML.
msgboard.php:
<?
while($post = mysql_fetch_array($resultados))
{
?>
<div class="post">
<div class="user"><b><?= $post["user"]?></b></div>
<div class="txt"><?= $post["msg1"]?></div>
</div>
<div id="comments_contaner">
<?
// This code can be ommited as you can just call updateShouts() upon page load to fetch the comments
$comments = mysql_query("SELECT * FROM table WHERE masterid = '{$post['id']}' ORDER BY id ASC");
while($comment = mysql_fetch_array($comments))
{
?>
<div class="comment">
<div class="txt"><b><?= $comment['user'] ?></b> <?= $comment['msg1'] ?></div>
</div>
<?
}
?>
</div>
<div class="commentform">
<form action="board.php" method="post">
<input type="text" size="75" name="message" id="message1">
<input type="hidden" name="masterid" value="<?= $post['id'] ?>">
<input type="submit" name="Submit" value="Enviar">
</form>
</div>
<?
}
?>
Step 2: Create a PHP function to update the comments
This function will only output the comments, it will need the masterid as a parameter to know which comments to output.
updateComments.php:
<?
$masterid = $_GET['masterid']
$comments = mysql_query("SELECT * FROM table WHERE masterid = '{$masterid}' ORDER BY id ASC");
while($comment = mysql_fetch_array($comments))
{
?>
<div class="comment">
<div class="txt"><b><?= $comment['user'] ?></b> <?= $comment['msg1'] ?></div>
</div>
<?
}
?>
Step 3: Call the PHP update function in your script targeting the container div
You will need to pass the $row['id'] as a parameter in the URL
<script type="text/javascript">
var PHP = "updateComments.php?masterid=<?= $post['id']?>";
function updateShouts(){
$('#comments_contaner').load(PHP);
}
window.setInterval( "updateShouts()", 4000 );
</script>
PD: I have not tested this code, it is just to show you the main idea.
EDIT: Corrected variable names and added comment.
Perhaphs you should look into stateful HTTP connections. So whenever a new message is added to the board on the server-side, all the clients are notified. This way, you don't have to refresh the page unnecessarily. HTML5 supports Web Sockets that can make it possible. Here are some links I came across that you may find useful:
Create Bi-directional connection to PHP Server using HTML5 Web Sockets
Wikipedia Page on WebSocket
socketo.me