Displaying links/buttons when a user is logged on/off - javascript

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)

Related

Bootstrap Modal On Php Submit using Ajax

Here I'm working on a simple withrawal page where users can select the amount they want to withdraw and submit afterwhich a bootstrap modal pops up confirming to the user that the request has been sent whilst updating the section in the db with the amount selected.
So far im facing no issues when user selects the amount and click on submit, the modal pops up but unfortunately the database is not updated, I can't fathom where i'm getting it wrong.
Here is the Php
<?php
// Define variables and initialize with empty values
$withraw = "";
$withraw_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate Withrawal
if(empty(trim($_POST["withraw"]))){
$withraw_err = "Please Choose a Amount.";
} else{
$withraw = trim($_POST["withraw"]);
}
// Check input errors before inserting in database
if(empty($withraw_err)){
// Prepare an insert statement
$sql = "UPDATE users SET withraw = (?) WHERE id = ".$id;
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_withraw);
// Set parameters
$param_withraw = $withraw;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
echo "";
} else{
echo "Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($link);
}
?>
Here is the code for the form im using.
<form onsubmit="openModal()" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" id="myForm" >
<div class="form-group <?php echo (!empty($withraw_err)) ? 'has-error' : ''; ?>">
<div style='width:50%;' class='selectt'><select name="withraw" class="form-control" value="<?php echo $withraw; ?>"><option >Choose Amount</option>
<option value="500">500</option>
<option value="1000">1,000</option>
<option value="1500">1,500</option>
<option value="2000">2,000</option>
<option value="2500">2,500</option>
<option value="3000">3,000</option>
<option value="3500">3,500</option>
</select>
</div>
<span class="help-block"><?php echo $withraw_err; ?></span>
</div>
<div class="form-group" >
<button type="submit" class="btn btn-info btn-lg" value="Submit">
Withraw <i class="fa fa-check-circle"></i> </button>
<button type="reset" class="btn btn-default" value="Reset"><i class="fas fa-redo"></i> Reset </button>
</div>
</form>
And I've added some javascript to load the bootstrap modal after the form is Submitted
<script>$('#myForm').on('submit', function(e){
e.preventDefault();
$('#myModal').modal('show');
});</script>
Here is where I'm completely lost as, when I remove the e.preventDefault() the form Updates the database row called withraw but the bootstrap does not load at all and I've been trying to set so that the bootstrap loads and the database row is updated as well I do not have more knowledge on how to tackle this situation as I read similar questions and some suggestions are to use Ajax but I have limited knowledge on how to do that.
I didn't post the bootstrap because i don't see it necessarily its a normal Bootstrap modal setup

display comment in post comment section without reloading the page

im trying to make a facebook style post and comment section but i dont know how to display the data inserted to my database without refreshing the page...
this code is for saving the data to my db. i use window.location.reload(); to reload my page so that the data will be displayed on my page..
<script>
$(document).ready(function() {
$('input[name="mycomment"]').on('keyup', function(e){
e.preventDefault();
var comments = $(this).val();
var sid = $(this).closest("div#userspost").find("input[type='hidden']").val();
if(e.keyCode == 13){
if(comments.length)
$.ajax({
url: "../controller/post_controller.php",
type: "POST",
data:{
"id":sid,
"comments":comments,
},
success: function(data)
{
window.location.reload();
}
});
else
alert("Please write something in comment.");
}
});
});
</script>
using this script i can display my comment on a post i need to refresh the page first for me to be able to show the comment.
<?php
foreach ($post_model->getcomment() as $value) {
if($postid == $value['post_uid']){
?>
<div id="mycomments">
<div class="col-lg-12" style="background:#eff9c7;">
<img src="./<?php echo $value['image']?>" class="pull-left" style="border-radius:50%;margin-top:10px;" width="7%" height="7%" />
<p style="margin-top:18px;line-height:15px;"><strong class="font-1" style="margin-left:10px;"><?php echo $value['firstname'].' '.$value['lastname']?></strong> <?php echo $value['pc_comment']?><br>
<span class="" style="margin-left:10px;font-size:.9em;color:gray;"><abbr class="timeago" title="<?php echo $value['pc_datesend']?>"></abbr></span>
</p>
</div>
</div>
<?php
}
}
?>
what im trying to do is that this is where i want to display my comments from my db. i tried researching about append/load but i dont exactly know how this works. is there any idea that i can display my comment in this script?
<div id="mycomments">
<div class="col-lg-12" style="background:#eff9c7;">
<img src="./<?php echo $value['image']?>" class="pull-left" style="border-radius:50%;margin-top:10px;" width="7%" height="7%" />
<p style="margin-top:18px;line-height:15px;"><strong class="font-1" style="margin-left:10px;"><?php echo $value['firstname'].' '.$value['lastname']?></strong> <?php echo $value['pc_comment']?><br>
<span class="" style="margin-left:10px;font-size:.9em;color:gray;"><abbr class="timeago" title="<?php echo $value['pc_datesend']?>"></abbr></span>
</p>
</div>
</div>
I decided to write some pseudo code for you here. If you don't know how to store and fetch comments I would recommend looking into MYSQL. It's relatively simple (for simple things), so that shouldn't be too big of a problem. YouTube tutorials will be your blessing there.
You should have at least three files to properly implement this:
uploadComment.php
<?php
//process the comment upload
echo $_POST['comment'];
?>
getComment.php
<?php
//however you serve commnets, MYSQL, maybe?
//make sure it's properly formatted with HTML
?>
index.html
<form>
<input type="text" name="comment" id="comment" value="Comment here" />
<button id="submit">Submit</button>
</form>
<div id="comments">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$("#submit").click(function () {
$.post("uploadComment.php", {
comment : $("#comment").val()
}, function (data) {
//comment posted.
refreshComments();
});
});
function refreshComments() {
$.get("getComments.php", function(data) {
$("#comments").html(data);
});
}
setInterval(refreshComments,5000);
</script>
Note: Although it may be annoying, if you want immediate satisfaction, append the new comment to the end and then invoke refreshComments. (But I wouldn't recommend doing this because it would force you to update multiple locations in your code whenever you change your comment HTML format).

How to reload user defined tag in CMS Made Simple

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

how to document.getElementById().innerHTML from different html/php file

Hello I am really new to coding in general but I got the basics of what I need.
I have my index.html that contains this:
<!-- Navigation -->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li class="hidden">
</li>
<li class="page-scroll">
Portfolio
</li>
<li id="navbutone" class="page-scroll">
Login
</li>
<li id="navbuttwo" class="page-scroll">
Register
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container-fluid -->
</nav>
keep in mind I got this from a website template that I am editing so I didn't come up with this layout
and I have a php file that has some html in it to try and replace the contents of the list when this part of the code is run:
<?php
if($login_ok)
{
?>
<script type="text/javascript">
function logedin() {
document.getElementById("one").innerHTML = "Logout";
}
</script>
<script type="text/javascript">
logedin();
</script>
<?php
header("Location: index.html");
die("Redirecting to: private.php");
}
?>
This doesn't work and I have no idea if this is even close or not.
Thanks in advance for the help.
also I might add that they link to login.php where they login through an html form at the bottom of the php.
?>
<h1>Login</h1>
<form action="login.php" method="post">
Username:<br />
<input type="text" name="username" value="<?php echo $submitted_username; ?>" />
<br /><br />
Password:<br />
<input type="password" name="password" value="" />
<br /><br />
<input type="submit" value="Login" />
</form>
Register
<script src="index.html"></script>
</html>
Update: I found what I needed instead of messing with the php file i just put this into my index.html were the links will change out:
<?php
require("common.php");
if(empty($_SESSION['user']))
{
?>
<li class="page-scroll">
Login
</li>
<li class="page-scroll">
Register
</li>
<?php
}
else
{
?>
<li class="page-scroll">
Logout
</li>
<li class="page-scroll">
Members Page
</li>
<?php
}
?>
were common.php just connects to my database.
Look, I'm gonna give you some tips you could use for developing this:
First of all, you should use only PHP files (index.php instead of index.html), so it's easier to manage POST data and session variables.
So:
index.php
<?php
// This is PHP code, executed BEFORE any output is sent.
// First, to save data that works across page loads, we should use sessions, so we start a session that has to be called in every PHP page that uses that information.
// Variables use the format $_SESSION['variable_name'] = value
session_name('MySession'); // Give it a unique name
session_start(); // Start a session
?>
<html>
<head>
<title>Some title for your page...</title>
</head>
<body>
<!-- Here you will manage your template. It's plain HTML but, as this is a PHP file, you can include PHP code as well inside the PHP tags -->
<?php
// This is a PHP tag, here we can manage some PHP and output different HTML
// We check if the user logged in or not
if (
isset($_SESSION['logged_in']) // Always check if a variable exists before checking its value, or PHP will complain
&&
$_SESSION['logged_in'] == true
)
{
// The user logged in, show a LOGOUT link
echo '<a href=logout.php>Logout</a>';
}
else
{
// Otherwise, the user did not log in. Show a link to log in.
echo '<a href=login.php>Login</a>';
}
?>
<!-- Any other HTML you want, template or whatever -->
</body>
<html>
Now, we used two files: login.php and logout.php. The first one will show a form, the second one will logout and redirect to the index page.
login.php
<html>
<head>
<title>Please log in</title>
</head>
<body>
<form action="do_login.php" method="post"><!-- Notice another file: do_login.php -->
<input type="text" name="username" placeholder="Your username" />
<br />
<input type="password" name="password" placeholder="Your password" />
<br />
<br />
<input type="submit" name="submit" value="Log in" />
</form>
<body>
</html>
Now we need the file that processes the login (do_login.php in the form) and stores session data.
do_login.php
<?php
// We use the same session as before
session_name('MySession'); // Same name as index.php and all other files
session_start();
// This will be a pure PHP file that stores session data and returns to the index page.
// You want to check data against databases here, but we will use static information for easier reading.
// You also want to check data to be correct, but we won't do that here for simplicity.
$username = $_POST['username']; // This is the "username" from the form.
$password = $_POST['password']; // This is the "password" from the form.
if (
$username == 'John' // Username is John
&&
$password == 'MyPassword' // Password is MyPassword
)
{
// Here the login data is correct, let's save some session variable that says the user correctly logged in.
// Note that this is potentially extremely INSECURE! You should save other data and check every request, but this is just for you to start learning.
$_SESSION['logged_in'] = true;
// Ok, user logged in. Redirect to the index.
header('Location: index.php'); // Send a redirect header (note that NOTHING has been echoed before in this page).
exit;
}
else
{
// Login data incorrect. Redirect to an error page, let's say login_error.php
header('Location: login_error.php');
exit;
}
?>
Now the file to log out:
logout.php
<?php
// First we recreate the session and destroy the variable(s) that say the user has logged in.
session_name('MySession'); // Same name as before
session_start(); // We start the session. At this point, all session variables have been recreated.
unset( $_SESSION['logged_in'] ); // We destroy the variable
session_destroy(); // Now we drop the session
header('Location: index.php'); // Redirect to index.php
exit;
?>
Now we only need the login failed page:
login_error.php
<html>
<head>
<title>Login error!<title>
</head>
<body>
<h1>Login error!</h1>
<p>The login data was incorrect. Try again.</p>
<br />
<p>Go back to the index page</p>
</body>
</html>
I hope this helps, but you really need to read some tutorials.
Have fun!
Use used " instead you should have used '
<script type="text/javascript">
function logedin() {
document.getElementById("one").innerHTML = "<a href='logout.php'>Logout</a>";
}
</script>
Change to following line:
document.getElementById("one").innerHTML = "Logout";
" characters has to be escaped.
And link has to be like that
link
It's worth to use i.e. firefox plugins like JS console where you could see in what line error occurs.
I've got it figured out. in the index.html i just put
<li class="hidden">
</li>
<li class="page-scroll">
Portfolio
</li>
<?php
require("common.php");
if(empty($_SESSION['user']))
{
?>
<li class="page-scroll">
Login
</li>
<li class="page-scroll">
Register
</li>
<?php
}
else
{
?>
<li class="page-scroll">
Logout
</li>
<li class="page-scroll">
Members Page
</li>
<?php
}
?>
does exactly what I need and no messing with the other php files.

How to refresh using ajax and keep form data

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

Categories

Resources