I am working on a project and here I need to fetch data from a MySQL database.
And I need to fetch only that data which contain 38.
For example - I have a table which contain user_from and user_to and msg. Okay, now I have to fetch all data if user_from contain 38.
So I am able to fetch it but the problem is that is it fetching only one row from database nut I want all row which contain user_from 38.
So Please help me.
As Fast As you can
Codes----
<?php
include 'navigation.php';
include 'conn.php';
if(!$_SESSION["login"]){
header("location:index.php");
die;
}
if ($_SESSION['SESS_MEMBER_ID']) {
$id = $_SESSION['SESS_MEMBER_ID'];
} else {
echo "Sorry We are unable to get your id";
}
echo "<center><button type='button' class='btn btn-default' id='myBtn'> Send a message </button></center>";
?>
<!DOCTYPE html>
<html>
<head>
<style>
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
position: relative;
background-color: #fefefe;
margin: auto;
padding: 0;
border: 1px solid #888;
width: 80%;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
-webkit-animation-name: animatetop;
-webkit-animation-duration: 0.4s;
animation-name: animatetop;
animation-duration: 0.4s
}
/* Add Animation */
#-webkit-keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
#keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
/* The Close Button */
.close {
color: white;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
.modal-header {
padding: 2px 16px;
background-color: #5cb85c;
color: white;
}
.modal-body {padding: 2px 16px;}
.modal-footer {
padding: 2px 16px;
background-color: #5cb85c;
color: white;
}
select {
width: 100%;
}
</style>
</head>
<body>
<!-- Trigger/Open The Modal -->
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>Send a Message</h2>
</div>
<div class="modal-body">
<label for="Friends">Select Friends:</label>
<select id="country" name="country">
<option value="Select Friends">Select Friends...</option>
<option value="australia">Australia</option>
<option value="canada">Canada</option>
<option value="usa">USA</option>
</select>
<br> <br>
<textarea cols="149" rows="12"></textarea>
<button type='button' class='btn btn-default' id='myBtn' name="sendmsgnow"> Send Now </button>
</div>
<div class="modal-footer">
<h3>Modal Footer</h3>
</div>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
<?php
$aquery = "SELECT * FROM register WHERE id='$id'";
$aresult = mysqli_query($conn,$aquery);
while ($row = mysqli_fetch_assoc($aresult)) {
$user_id[] = $row["id"];
}
if (isset($_POST["sendmsgnow"])) {
$query = "INSERT INTO chats (user_from,user_to,msg_body,userdate,usertime) VALUES ('$id','1','$message','')";
$result = mysqli_query($conn,$query);
if ($result) {
echo "Your Message has been sent";
}
}
$b_query = "SELECT * FROM chats WHERE user_from='$id'";
$b_result = mysqli_query($conn,$b_query);
while ($data = mysqli_fetch_array($b_result)) {
$messages[] = $data["msg_body"];
$user_from = $data["user_from"];
if($user_from==38){
$d_query = "SELECT * FROM register WHERE id='$user_from'";
$d_result = mysqli_query($conn,$d_query);
while ($fdata = mysqli_fetch_assoc($d_result)) {
$frname = $fdata["firstname"];
echo "$frname sent you a message <br> $messages[]";
}
}
}
?>
As I told in comments you can use a nested while loop for thisUpdated
while ($data = mysqli_fetch_array($c_result)) {
$messages[] = $data["msg_body"];
$user_from = $data["user_from"];
if($user_from==38){
$d_query = "SELECT * FROM register WHERE id='$user_from'";
$d_result = mysqli_query($conn,$d_query);
while ($fdata = mysqli_fetch_assoc($d_result)) {
$frname = $fdata["firstname"];
}
} //This is end of if
echo "$frname sent you a message <br> $messages[]";
}//This END of First while loop
I have wrote what I have understood. Hope it helps you
Related
I've got a "lost property website" which shows items from a database. The form for the website is formatted correctly, but when it is clicked on the button becomes extremely large.
body {
/* apply styling to everything in body */
margin: 0;
/* use all of the page */
font-family: Helvetica, Arial, sans-serif;
/* set primary font to Helvetica, secondary to Arial, and if none are availible use a san-serif font */
background-color: #fff;
/* set background colour to white */
font-size: 18px;
/* set default font size is 18px */
}
.navigation {
/* navigation bar styling */
position: fixed;
/* attach bar to static position */
top: 0;
/* spread to full */
left: 0;
right: 0;
background-color: orange;
/* make navigation bar div orange */
z-index: 1/* place on top of all content */
}
.navigation a {
float: left;
/* move links to left */
color: #fff;
/* text colour white */
text-align: center;
/* align links centre of their boxes */
padding: 14px 16px;
/* add padding to boxes */
text-decoration: underline;
/* add underline to links for platform conventions */
position: relative;
/* move links one after the other */
}
.navigation a:hover {
/* when link is hovered over, make background lighter */
background-color: #ffc864;
}
.right a {
/* ability move links to the right side of navaigation bar div */
float: right;
}
.header {
/* title and image */
position: relative;
top: 5%;
/* add borders */
left: 5%;
right: 15%;
width: 70%;
/* define size */
padding-top: 50px;
}
.header img {
max-width: 225px;
/* max size of image */
float: left;
}
.header h1 {
padding-left: 30px;
padding-bottom: 30px;
}
.gallery {
/* image gallery div styling */
left: 5%;
width: 90%;
position: relative;
}
input {
/* input field styling */
border-radius: 5px;
border: none;
width: 100%;
font-size: 18px;
margin-bottom: 15px;
height: 30px;
}
.submit {
/* button styling */
padding-left: 0;
font-size: 18px;
height: 30px;
text-align: center;
position: relative;
}
.form {
/* form div styling */
position: relative;
width: 75%;
height: 100%;
left: 12.5%;
background-color: #d3d3d3;
padding: 25px;
margin-bottom: 50px;
}
* {
box-sizing: border-box;
}
input[type=text] {
border: 1px solid #ccc;
border-radius: 4px;
resize: vertical;
padding-left: 12px;
}
input[type=file] {
border: none;
border-radius: 4px;
height: 100%;
}
input[type=submit] {
background-color: orange;
color: #fff;
padding: 12px;
border: none;
border-radius: 4px;
cursor: pointer;
height: 100%;
}
input[type=submit]:hover {
background-color: #ffa07a;
}
/* code to make gallery images scale well for all screens */
#media screen and (max-width:600px) {
input[type=submit] {
width: 100%;
margin-top: 0;
}
}
div.image {
margin: 10px;
display: inline-block;
vertical-align: middle;
}
div.image img {
width: 100%;
height: auto;
border: 1px solid #ccc;
}
#media screen and (min-width:1224px) {
div.image {
width: 300px;
}
}
#media screen and (min-width:1044px) and (max-width:1224px) {
div.image {
width: 250px;
}
}
#media screen and (min-width:845px) and (max-width:1044px) {
div.image {
width: 200px;
}
}
.image a {
/* make image links follow platform conventions */
color: inherit;
text-decoration: underline;
}
/* full screen images */
.lightbox {
/** Default lightbox to hidden */
display: none;
/** Position and style */
position: fixed;
z-index: 999;
width: 100%;
height: 100%;
text-align: center;
top: 0;
left: 0;
background: rgba(0, 0, 0, 0.8);
}
a {
color: white;
text-decoration: none;
}
.lightbox img {
/** Pad the lightbox image */
max-width: 90%;
max-height: 80%;
margin-top: 5vh;
}
.lightbox:target {
/** Remove default browser outline */
outline: none;
/** Unhide lightbox **/
display: block;
}
<!-- Declaration tags for the browser to know what to read, and what language -->
<!DOCTYPE html>
<html lang="en">
<!-- Back end code -->
<head>
<title>Lost Property</title>
<!-- title for website -->
<link rel="stylesheet" type="text/css" href="assets/main.css">
<!-- link to css -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- define size -->
<?php
session_start();
include("config.php"); // include configuration to connect to database
$dbconnect = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME); // connect to database
// if can't connect display error
if (mysqli_connect_errno()) {
echo "Connection failed:" . mysqli_connect_error();
exit;
}
// define variables from database to use later in PHP code
$showall_sql = "SELECT * FROM `images` ORDER BY `images`.`ID` ASC";
$showall_query = mysqli_query($dbconnect, $showall_sql);
$showall_rs = mysqli_fetch_assoc($showall_query);
$count = mysqli_num_rows($showall_query);
?>
</head>
<!-- main page content -->
<body>
<!-- navigation bar -->
<div class="navigation">
<!-- links -->
Home
Search
Upload
<div class="right">About</div>
<!-- has float:right property for to move to side -->
</div>
<!-- header -->
<div class="header">
<img src="assets/logo.jpg" alt="Logo">
<!-- image of logo, alt tags for screen readers -->
<h1>Lost Property</h1>
</div>
<?php
$sql = "SELECT * FROM lost_property";
if (!empty($_POST)) {
$name = mysqli_real_escape_string($dbconnect, htmlspecialchars($_POST['name']));
$item = mysqli_real_escape_string($dbconnect, htmlspecialchars($_POST['item']));
$sql = "SELECT * FROM lost_property WHERE name LIKE '%$name%' AND item LIKE '%$item%' ORDER BY name ASC";
}
$result = $dbconnect->query($sql);
?>
<body>
<div class="form">
<label>Search</label>
<form action="" method="POST">
<input type="text" placeholder="Type the name here" name="name">
<select name="item" class="dropdown">
<option value="" disabled selected>item:</option>
<?php
$item_sql = "SELECT * FROM `lost_property` ORDER BY item ASC ";
$item_query = mysqli_query($dbconnect, $item_sql);
$item_rs = mysqli_fetch_assoc($item_query);
do {
?>
<option value="<?php echo $item_rs['item']; ?>">
<?php echo $item_rs['item']; ?>
</option>
<?php
} while ($item_rs = mysqli_fetch_assoc($item_query));
?>
</select>
<input type="submit" value="Search" name="btn">
</div>
</form>
<div class="gallery">
<h2>Found property:</h2>
<?php
//check for results. If there are none display error
if ($count < 1) {
?>
<div class="error">
<h1>No results were found.</h1>
</div>
<?php
} //end if
else {
while ($search_rs = $result->fetch_assoc()) {
?>
<!-- display image and information from database and show in gallery -->
<div class="image">
<h3>
<?php echo $search_rs['name']; ?>
</h3>
<h3>
<?php echo $search_rs['item']; ?>
</h3>
<p>
<?php echo $search_rs['location']; ?>
</p>
</div>
<?php
} // end of do
} //end else
//if there are any display
?>
</div>
</body>
</html>
Obviously it's a bit hard to tell without the attached database, but why does the search button become really big?
Is it the PHP that is changing the size, or is it adjusting to fit something in?
You should use an Editor that shows you opened and closed tags. In your code are several mistakes that should result in several problems, this part here especially:
<body> <--- You open a second Body tag here! Only use one
<div class="form"> <--- start of your div
<label>Search</label>
<form action="" method="POST"> <--- start of your form INSIDE the div
<input type="text" placeholder="Type the name here" name="name">
<select name="item" class="dropdown">
<option value="" disabled selected>item:</option>
<?php
$item_sql = "SELECT * FROM `lost_property` ORDER BY item ASC ";
$item_query = mysqli_query($dbconnect, $item_sql);
$item_rs = mysqli_fetch_assoc($item_query);
do {
?>
<option value="<?php echo $item_rs['item']; ?>">
<?php echo $item_rs['item']; ?>
</option>
<?php
} while ($item_rs = mysqli_fetch_assoc($item_query));
?>
</select>
<input type="submit" value="Search" name="btn">
</div> <-- div closes before the form which is INSIDE the div
</form> <-- form closes after div, wrong way around!
So i highly recommend to practice a bit how to make code cleaner, so that you notice mistakes like this.
example:
<div class="main-container">
<div class="form-container">
<form>
<input type="text" placeholder="Testinput">
<input type="submit" value="search" id="submitbutton">
</form>
</div>
</div>
Basically: Avoid unecessary white-space, align opening and closing tags on the same level.
With that information you should be able to rearrange your code and fix the Button-Bug yourself.
I'm working on a custom PHP, modal login form. When I click the Login button, I receive the 404 resource not found, being my PHP file that handles the authentication.
The two files are here:
action_page.php
<?php
session_start();
$name = 'user1';
$pwd = 'home';
if(isset($_POST['submit'])){
// get vars
$username = $_POST['username'];
$password = $_POST['password'];
if ($username == $name and $password == $pwd){
redirect('http://www.mden.com');
} else {
redirect('http://www.youtube.com');
}
} else {
redirect('login.html');
}
?>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
form {
border: 3px solid #f1f1f1;
}
input[type=text], input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}
button:hover {
opacity: 0.8;
}
.cancelbtn {
width: auto;
padding: 10px 18px;
background-color: #f44336;
}
.container {
padding: 16px;
}
span.psw {
float: right;
padding-top: 16px;
}
/* Change styles for span and cancel button on extra small screens */
#media screen and (max-width: 300px) {
span.psw {
display: block;
float: none;
}
.cancelbtn {
width: 100%;
}
}
/* The Modal (background) */
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.9);
background-color: rgb(0,0,0,0.4);
padding-top: 60px;
}
/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 5px auto;
border: 1px solid #888;
width: 20%;
}
/* The Close Button */
.close {
/* Position it in the top right corner outside of the modal */
position: absolute;
right: 25px;
top: 0;
color: white;
font-size: 35px;
font-weight: bold;
}
/* Close button on hover */
.close:hover,
.close:focus {
color: red;
cursor: pointer;
}
/* Add Zoom Animation */
.animate {
-webkit-animation: animatezoom 0.6s;
animation: animatezoom 0.6s
}
#-webkit-keyframes animatezoom {
from {-webkit-transform: scale(0)}
to {-webkit-transform: scale(1)}
}
#keyframes animatezoom {
from {transform: scale(0)}
to {transform: scale(1)}
}
</style>
</head>
<body>
<!-- Button to open the modal login form -->
<button onclick="document.getElementById('id01').style.display='block'">Login</button>
<!-- The Modal -->
<div id="id01" class="modal">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<!-- Modal Content -->
<form class="modal-content animate" method="post" action="/action_page.php">
<!-- No Avatar!!! -->
<!-- Login Info -->
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required><br /><br />
<label><b>Password</b></label>
<input type="text" placeholder="Enter Password" name="psw" required><br /><br />
<button name="do_login" type="submit">Login</button>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
</div>
</form>
</div>
<script>
// Get the modal
var modal = document.getElementById('id01');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
The file path used in your form's action is correct?
Try remove the "/" from action="/action_page.php" if action_page.php stay on same directory.
I have been creating a small map with different positions for a fabric. My goal is to make sure I can drag 1, 2, 3 and 4 (persons) into a position (e.g. Production Leader) and save the position of the DIV into the MySQL Database. I want a global map so each person which visit this page will see the same.
I created different DIV's for each person (1, 2, 3 and 4) which are already in the database.
I'm stuck right now.. can somebody help me?
Fiddle: https://jsfiddle.net/fj1zgw2o/
Database connection and showing persons from the database:
function choosePerson() {
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, image, position FROM Persons";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo '<div class="boxPersons posLeft" id="'. $row['id'] .'">'. $row['id'] .'</div>';
}
} else {
echo "0 results";
}
}
// Move the box into the corresponding id.
// When you load your boxPersons have each
// person an id column that matches what position they will be in.
$(".boxPersons").each(function(e){
var target = $(this).attr("data-id");
$("#"+target).append($(this));
});
$(".boxPersons").draggable({
revert: 'invalid',
containment: '.box',
cursor: 'move'
});
$(".openSpots, .box-persons").droppable({
accept: ".boxPersons",
drop: function(event, ui) {
var droppable = $(this);
var draggable = ui.draggable;
// Move draggable into droppable
draggable.appendTo(droppable);
draggable.css({
top: '0px',
left: '0px'
});
}
});
.box-content {
display: flex;
}
.toPlan {
width: 10%;
}
.overviewPlanning {
flex: 1;
}
.box-persons {
overflow: hidden;
border-radius: 4px;
border: 1px solid #d8d8d8;
}
.boxPersons {
width: 60px;
height: 72px;
padding: 5px;
margin: 10px;
text-align: center;
border: 1px solid #d8d8d8;
border-radius: 4px;
z-index: 99;
float: left;
background: #888;
}
.posLeft {
float: left;
}
.openSpots {
width: 60px;
height: 72px;
padding: 5px;
margin: 10px;
text-align: center;
border: 0.5px dashed #000000;
border-radius: 4px;
z-index: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<header>
Header
</header>
<div class="box">
<div class="box-content">
<div class="toPlan">
<div class="productionLeader">
<strong>Production Leader</strong>
<div id="Leader" class="openSpots" id="openSpots">
</div>
<strong>Free</strong>
<div id="Free" class="openSpots positionFree">
</div>
<strong>Ill</strong>
<div id="Ill" class="openSpots positionIll">
</div>
<strong>Otherwise</strong>
<div id="Otherwise" class="openSpots positionOtherwise">
</div>
</div>
</div>
<div class="overviewPlanning">
Fabric map
</div>
</div>
<div class="box-persons">
Available collegues (to drag and drop into a spot)<br>When you load the data into this box change the id to match what was saved. You can use AJAX to keep everything synced.<br>
<div class="boxPersons" data-id='Free'>bob</div>
<div class="boxPersons" data-id='Ill'>marry</div>
<div class="boxPersons" data-id=''>mark</div>
</div>
</div>
<footer>
Footer
</footer>
code:
<style>
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
</style>
<script>
var modal = document.getElementById('myModal');
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
<?php
$sql = "select * from enquires2";
$result = mysqli_query($link,$sql);
while ($row = mysqli_fetch_array($result))
{
?>
<tr>
<td>
<span><img src='gridview/view.png' alt='View' id='myBtn<?php echo $row['id']; ?>'></span>
</td>
</tr>
<div id='myModal' class='modal'>
<div class='modal-content'>
<span class='close'>×</span>
<p>Some text in the Modal..</p>
</div>
</div>
<?php
}
?>
In this code when I click on id i.e.
id='myBtn<?php echo $row['id']; ?>'
it display only one modal but when I click on new row id it show nothing. so, I want to open multiple modal with different row id. How can I fix this issue ? please help.
Thank You
I have a div (inbox-chat) which contains data retrieved from database using ajax. the content is refreched every 5 seconds.
the div have a scroll bar. the problem here is when the div is refreshed to load new data, the scroll bar goes to top, and then the user cannot read what is written on the bottom of the div content.
the content is loaded here
messages.php
<div id="inbox">
<img src="assets/images/loaders/preload.gif" class="loading_inbox" >
</div>
here is an example of HTML code
ajax/inbox.php (EIDTED)
<?php
ob_start();
session_start();
require_once '../../config/connect.php';
require_once '../../functions/func.php';
$uid = $_GET['sender_id'];
$uid = get_username_id($_GET['sender_id']);
$stmt = $PDO->prepare("SELECT * FROM `forum_inbox`
WHERE
(sender_id=? AND receiver_id=?)
OR
(sender_id=? AND receiver_id=?)
ORDER BY dateMsg DESC");
$stmt->execute(array($uid, $_SESSION['id_userf'], $_SESSION['id_userf'], $uid));
$messages = $stmt->fetchAll(PDO::FETCH_OBJ);
?>
<?php if($stmt->rowCount() != 0): // STARTS CHECK IF ANY RECORDS EXISTS IN INBOX TABLE ?>
<div id="inbox-chat">
<section class="chat-container">
<ol class="chat-box">
<div class="new-msg"></div>
<?php
foreach($messages AS $msg):
if(get_username($msg->sender_id) == $_SESSION['usernamef']){
$direction = 'another';
}else{
$direction = 'me';
}
?>
<li class="<?php echo $direction ?>">
<div class="avatar-icon">
<a title="Voir profil de <?php echo get_username($msg->sender_id); ?>" href="profil.php?user=<?php echo get_username($msg->sender_id) ?>&pane=profile">
<img src="assets/images/profiles/<?php echo get_user_profile_pic($msg->sender_id)?>">
</a>
</div>
<div class="messages">
<p><?php echo $msg->message ?></p>
<time datetime="<?php echo convert_date_format_full(convert_timestamp($msg->dateMsg));?>">
<?php echo time_stamp($msg->dateMsg);?>
<i class="fa fa-clock-o"></i> <?php echo convert_date_format_full(convert_timestamp($msg->dateMsg)); ?>
</time>
</div>
</li>
<?php endforeach; ?>
</ol>
</section>
</div>
<?php else: ?>
<div class="panel-body" style="width:50%; margin:5px auto;text-align:center;">
<div class="media v-middle">
<h2>Pas de message</h2>
<img src="assets/images/no-msg.png">
</div>
</div>
<?php endif; // ENDS CHECK IF ANY RECORDS EXISTS IN INBOX TABLE ?>
js file (inbox.js)
$(document).ready(function(){
var sender_id = $(".u").val();
var $container = $("#inbox");
$.ajax({
url : 'ajax/inbox.php',
data : 'sender_id='+sender_id,
before : function(){
$(".loading_inbox").show();
},
success : function(data){
$(".loading_inbox").hide();
$("#inbox").html(data);
}
});
var refreshId = setInterval(function()
{
$container.load('ajax/inbox.php?sender_id='+sender_id);
}, 10000);
});
Im using this css for the inbox-chat class
#inbox-chat .chat-container {
width: 100%;
margin: 10px auto;
height: 450px;
background-color: #FAFCFB;
}
#inbox-chat .chat-box {
list-style: none;
background: #fdfdfd;
margin: 0;
padding: 0 0 50px 0;
height: 100%;
overflow-y: auto;
}
#inbox-chat .chat-box li {
padding: 0.5rem;
overflow: hidden;
display: flex;
}
#inbox-chat .chat-box .avatar-icon {
width: 50px;
position: relative;
}
#inbox-chat .chat-box .avatar-icon img {
display: block;
width: 100%;
background-color:#fff;
padding: 3px;
border-radius:50%;
}
#inbox-chat .me {
justify-content: flex-end;
align-items: flex-end;
}
#inbox-chat .me .messages {
order: 1;
border-bottom-right-radius: 0;
}
#inbox-chat .me .avatar-icon {
order: 2;
}
#inbox-chat .messages {
background: white;
padding: 10px;
border-radius: 2px;
width: 80%;
border: 1px solid #c9cccd;
color:#424242;
}
#inbox-chat .messages p {
font-size: 13px;
margin: 0 0 0.2rem 0;
}
#inbox-chat .messages time {
font-size: 0.7rem;
color: #ccc;
}
Take a look at the div from here
http://jsfiddle.net/devstar/rgjfqsb2/
That's because you're replacing the entire content of your inbox element with $("#inbox").html(data);.
Before replacing, save the scroll position with var scroll=$("#inbox")[0].scrollTop; and after replacing, restore it with $("#inbox")[0].scrollTop=scroll;.
I don't know if you're ajaxing the entire message history or only maybe the 10 newest and if newer messages are at the end or at the beginning - but you may need to calculate heights of the new elements and add/substract it to/from the scroll value.
Edit:
Btw, why are you ajaxing all the messages every 5 seconds, and not just the new ones and append or prepend them next to the existing messages? This would eliminate the need for storing and restoring the scroll position.
Add message id to each of your messages and a class to select them with:
<li class="message me" data-messageid="65">
<div class="avatar-icon">
<img src="http://simpleicon.com/wp-content/uploads/user1.png">
</div>
<div class="messages">
<p>Hi buddy !</p>
</div>
</li>
Then select the newest message and send that to your php handler:
var sender_id = $(".u").val();
var newest_msg=$(".message:last").data("messageid");
$.ajax({
url : 'ajax/inbox.php',
data : {
sender_id: sender_id,
newest_msg: newest_msg
},
success : function(data){
$("#inbox").append(data); //append it, not replace
}
});
And in your PHP:
$uid = $_GET['sender_id'];
$uid = get_username_id($_GET['sender_id']);
$newest_msg = $_GET['newest_msg'];
$stmt = $PDO->prepare("SELECT * FROM `forum_inbox`
WHERE
(sender_id=? AND receiver_id=?)
OR
(sender_id=? AND receiver_id=?)
AND
message_id > {$newest_msg}
ORDER BY dateMsg DESC
");
Notice I select only messages with id's greater than the newest message.
something like this?
var refreshId = setInterval(function()
{
$container.load('ajax/inbox.php?sender_id='+sender_id);
$(".chat-box").css("height", "auto");
var height = $(".chat-box").height();
$(".chat-box").css("height", 450);
$(".chat-box").scrollTop(height);
}, 10000);
replace this function.