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
Related
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.
I am truly a novice at coding and only succeed with trial and error. I use a WYSIWYG program to do all the main pages in my site and then add php coding to do some specified things.What I am trying to do right now is display a log in button along with a register and forgot password links to those forms, all of which I have built and working, have this display in the masterframe page when a user is not logged in and show another set of user name, profile, logout links when they are logged in. By themselves I have all these functions working, I just cant figure out how to do it this way. Any help or steering me in the right direction to teach me would be great. If you need to be paid for your help that can be arranged as well. Thank You.
update:
This is the code that I have right now and use, again I want to have the if else statement show one thing or the other on condition, and have it show in place of, all on the masterframes page.
// have this display if user is logged in
<span id="LoginName1"><?php
if (isset($_SESSION['username']))
{
echo $_SESSION['username'];
}
else
{
echo 'Not logged in';
}
?></span>
<div id="wb_Text2" style="">
<span style="color:#FFFFFF;font-family:Tahoma;font-size:12px;">Profile</span>
</div>
<form name="logoutform" method="post" action="<?php echo basename(__FILE__); ?>" id="logoutform">
<input type="hidden" name="form_name" value="logoutform">
<a id="Logout2" href="javascript:document.logoutform.submit()">Logout</a>
</form>
//have this display if user is logged out
Log In
<div id="wb_Text3" style="">
<span style="color:#FFFFFF;font-family:Tahoma;font-size:12px;">Register</span>
</div>
<div id="wb_Text1" style="">
<span style="color:#FFFFFF;font-family:Tahoma;font-size:12px;">Forgot Password?</span>
</div>
I have tried doing this but I keep getting a syntax error for unexpected '<'
<span id="LoginName1"><?php
if (isset($_SESSION['username']))
{
echo $_SESSION['username'];
<div id="wb_Text2" style="">
<span style="color:#FFFFFF;font-family:Tahoma;font-size:12px;">Profile</span>
</div>
<form name="logoutform" method="post" action="<?php echo basename(__FILE__); ?>" id="logoutform">
<input type="hidden" name="form_name" value="logoutform">
<a id="Logout2" href="javascript:document.logoutform.submit()">Logout</a>
</form>
}
else
{
Log In
<div id="wb_Text3" style="">
<span style="color:#FFFFFF;font-family:Tahoma;font-size:12px;">Register</span>
</div>
<div id="wb_Text1" style="">
<span style="color:#FFFFFF;font-family:Tahoma;font-size:12px;">Forgot Password?</span>
</div>
}
?></span>
<?php
// Setting a session variable when customer is logged in.
$_SESSION['user_loggedin'] = 1;
$_SESSION['customer_id'] = $customer_id; // Some reference of logged in customer
$_SESSION['customer_name'] = $customer_name; // Customer information collected from DB or other resource.
// Deciding whether to display "Login" button or Logged in status / links
if ($_SESSION['user_loggedin']) {
echo 'Hi ' . $_SESSION['customer_name'];
echo 'My Account';
} else {
echo 'Login';
echo ' Register';
echo ' Forgot Password';
}
If you have some PHP function to check whether customer is logged in or not, you can use that function like this in lieu of if ($_SESSION['user_loggedin']) condition
if (UserLoggedin()) {
// Logged in links
} else {
// Links to be displayed when customer is logged out.
}
You are mixing both PHP and HTML code. Please correct.
You have to separate / embed HTML properly in your document while using php conditions.
Example:
<?php
$condition = true;
if ($condition) {
?>
<h1>This will be displayed when condition is true</h1>
<?php
} else {
?>
<h1>This will be displayed when condition is false</h1>
<?php
} // else ends
?>
Please try this:
<span id="LoginName1"><?php
if (isset($_SESSION['username']))
{
echo $_SESSION['username'];
?>
<div id="wb_Text2" style="">
<span style="color:#FFFFFF;font-family:Tahoma;font-size:12px;">Profile</span>
</div>
<form name="logoutform" method="post" action="<?php echo basename(__FILE__); ?>" id="logoutform">
<input type="hidden" name="form_name" value="logoutform">
<a id="Logout2" href="javascript:document.logoutform.submit()">Logout</a>
</form>
<?php
}
else
{
?>
Log In
<div id="wb_Text3" style="">
<span style="color:#FFFFFF;font-family:Tahoma;font-size:12px;">Register</span>
</div>
<div id="wb_Text1" style="">
<span style="color:#FFFFFF;font-family:Tahoma;font-size:12px;">Forgot Password?</span>
</div>
<?php
}
?></span>
Adding some code in your question would be nice, but if I understand your question correctly you might want to try this:
$logged_in = 0;
if($logged_in == 0) {
//all the stuff you want to show when the person is not logged in
$logged_in = 1;
}
if($logged_in == 1) {
//all the stuff you want to show when the person is logged in
}
In order to do what you are trying, you need to implement just a bit of logic on the code. The example of kerv is perfectly valid. The idea is that you will validate if the user is logged in or not, before rendering the html. For example:
if($userLoggedIn){
<div> Welcome to the site </div>
} else {
<div> Your are not logged in, please do so to continue </div>
}
I'll suggest you to edit the question with some code so we can properly help you.
Create a PHP session and use that session variable for your "IF" condition boolean.
i.e. if (session active)
{then display this object}
else
{dont display this object}
Here is some documentation on PHP 5 Sessions. PHP 5 Sessions
The neat thing about PHP is that it is completely interchangeable with HTML. Therefore you and assign elements to divs. Here is an example.
<html>
<body>
<?php
$loggedInTxt="";
$loggedOutTxt="";
if (*session*){
$loggedInTxt="<div>*some html content here*</div>"
}
else{
$loggedOutTxt="<div>*some html content here*</div>"
}
?>
<?php echo($loggedInTxt)?>
<?php echo($loggedOutTxt)?>
</body>
</html>
The idea is that you test the condition within the php and create php strings containing html elements. You can insert the anywhere in your html. So if you create a button and assign the code you used to create that button to a php variable then you can echo that variable(the code for the button) anywhere in your html script. I was blown away by the implications of php. I hope this helps simplify it! (This more of an overview. Do NOT copy and paste the code)
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");
I have simple form:
<div class="form-style-2">
<form action="" name="formular" id="formular" method="GET">
<label for="actual_position"><span>From: <span class="required"></span></span><input name="actual_position" type="text" maxlength="512" id="actual_position" class="searchField"
<?php if(!empty($actual_position)){ ?>
value="<?php echo $_GET['actual_position']?>"
<?php
}else {
?> value = ""; <?php
} ?>/></label>
<label for="final_position"><span>To: <span class="required"></span></span><input name="final_position" type="text" maxlength="512" id="final_position" class="searchField" <?php if(!empty($final_position)){ ?>
value="<?php echo $_GET['final_position']?>"
<?php
}else {
?> value = ""; <?php
} ?>/></label>
<input type="submit" value="Find path" />
And another multiselect in form who gets values form url link and compere with database and get som results. Here is a code:
<table width= "570px">
<tr><td width="200px" style="align:center"><b>Waypoints:</b> <br>
<tr><td width="370px"><select style="float:center; margin-left:5px" multiple id="waypoints">
if(!empty($urls)){
foreach($urls as $url){
if($result = $conn->query("SELECT * FROM $table where $ID = '$url' "));
$atraction = $result->fetch_array(); ?>
<option value="<?php echo $atraction['lat']. "," . $atraction['lon']; ?>"
> <?php echo "<b>".$atrction['City']. ", " . $atraction['Name'];?> </option>
<?php
}
}
?>
</select></td></tr>
<br>
</table>
</form>
And getting ID-s from url code:
if(!empty($_GET[$ID])){
$urls = $_GET[$ID];
foreach($urls as $url){
// echo $url;
}
}
... and after submit, it Post to URL some variables like this:
http://127.0.0.1/responsiveweb/travel.php?actual_position=Paris&final_position=Praha&ID[]=23&ID[]=15&ID[]=55
... very important for me are ID-s values ... but when I change for example actual position and then submit I lost my ID-s and I get something like this: http://127.0.0.1/responsiveweb/travel.php?actual_position=Berlin&final_position=Praha
Can you help me how to get after clicking on submit button full url link? Thanks
I had some trouble understanding your question OP, but I think I understood somehow what you ment, so I decided to try giving you a answer.
I have re-written your code, and tried to make somehow better code-structure. I have also used form method POST in my example, so you can see how you can change the get data on the redirection url.
See my code example here: http://pastebin.com/wQ7QCBmt
I also decided to use the form method POST instead of GET, so you can easily do back-end tasks, and extend your link if neccessary. You could also add more data to the link even when using GET. You could add an hidden input inside your form, example:
<input type="hidden" name="more_data" value="a_value" />
I found a 'HTML5 WYSISYG Inline Editor', I have it working on my localhost(Ubuntu 14.04).
The purpose for this is, to embed it in my website, and use it as my main writing tool for my website. I need to be able to choose the filename or have it add - in the whitespace of the filename.
this is the code i wrote on it to save its content
(CodePen from original author: HTML5 WYSISYG Inline Editor)
inline.php
<form action="effe.php" method="post">
<input type="text" name="author" value="" placeholder="Author">
<input type="text" name="header" value="" placeholder="header">
<input type="datetime" name="datetime" value="" placeholder="datetime">
<div id='editor' contenteditable contextmenu="mymenu" name='editor'>
<p>This is just some example text to start us off</p>
</div>
<div class="tags">
<input type="text" name="" value="" placeholder="tag">
<input type="text" name="" value="" placeholder="tag">
<input type="text" name="" value="" placeholder="tag">
</div>
<input type="submit" value="Submit">
</form>
save.php
<?php
if (!empty($_POST))
{
foreach ( $_POST as $key => $value )
{
if ( ( !is_string($value) && !is_numeric($value) ) || !is_string($key) )
continue;
?>
<?php echo htmlspecialchars( (string)$key ); ?>
<div class="article-meta">
<a class="author" rel="author" title="author" href="/about" target="_blank"><?php echo "$author";?></a>
<time datetime="<?php echo "$datetime";?>" title="<?php echo "$datetime";?>"><?php echo "$datetime";?></time>
</div>
<h1><?php echo "$header"; ?></h1>
<?php echo "$editor"; ?>
<div class="tags">
<span> <?php echo "$tag1"; ?> </span>
<span> <?php echo "$tag2"; ?> </span>
<span> <?php echo "$tag3"; ?> </span>
</div>
<?php
}
}
?>
RESULT:
I have been at this for a good day, and am just not seeing what am doing wrong. Do note that my php knowledge is pretty basic.
I know using a db is an option, but at the top of my head, i only wrote like 20+ article in the past year or two. When i hit a 100 articles i will consider switching to a database.
I'm not 100% sure what it is you;re trying to accomplish. I was the author of the article you mentioned, and I'd be glad to help.
I'm not sure the method you;re trying to use is practical. The best option here would be to set up a database and write the content in there.
With php thats pretty easy, I would suggest taking a look at PDO, the database abstraction layer. There are some others, but this one does some work for you relating to injection attacks etc so it's a nice starting point.
It sounds like you need a fairly simple database table, most likely something like:
create table articles (
article_id INT NOT NULL AUTO INCREMENT,
title VARCHAR(100) NOT NULL,
content TEXT NOT NULL,
article_date DATE
PRIMARY KEY (tutorial_id)
);
When you POST data back from your editor form, you can do something like:
$dbh = new PDO('mysql:host=localhost;dbname=articles', 'user', 'pwd');
$sth = $dbh->prepare('INSERT INTO articles (title, content, article_date) values (:title, :content, NOW())');
$sth->bindParam(':title', $_POST['title']);
$sth->bindParam(':content', $_POST['content']);
$sth->execute();
To recall that back out of the database, use something like:
$dbh = new PDO('mysql:host=localhost;dbname=articles', 'user', 'pwd');
$sth = $dbh->query('SELECT * FROM articles');
There's a little more to it than this, for example you'll want to add a try/catch block to avoid errors, and you may want to select a specific article (i.e. SELECT * FROM articles where article_id=45) but this I hope will point you in the right direction.
I think trying to avoid using a database will cause a lot of extra work, and once you start using something like MySQL you'll be up and running in no time!