AngularJS delay loading data from MySQL database - javascript

I'm using angular in a simple application like:
app.js
app = angular.module('app', []);
app.controller("NavCtrl",function($scope,$http){
var serviceBase = 'v1/';
$http.get(serviceBase + 'orderoverview/58').then(function (results) {
$scope.categories = results.data;
$scope.getTotal = function(){
var total = 0;
for(var i = 0; i < $scope.categories.length; i++){
var categories = $scope.categories[i];
total += (categories.productPrice * categories.orderdetailAantal);
if(categories.extra1 != "")
{
total += categories.extrasPrice;
}
}
return total;
}
});
});
HTML
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8">
<title>Served</title>
</head>
<body ng-cloak="">
<div class="navbar navbar-default megamenu">
<div class="container" ng-controller="NavCtrl">
<ul class="nav navbar-nav">
<li ng-repeat= "p in categories">{{p.orderdetailAantal}} x {{p.productTitle}} {{p.productPrice}} <br> {{p.extra1}} {{p.extra2}} {{p.extra3}} {{p.extra4}} {{p.extrasPrice}}</li>
</ul>
<p>Total: {{ getTotal() }} euro</p>
</div>
</div>
<script src="libs/angular.js"></script>
<script src="app/app.js"></script>
</body>
</html>
And this works but every time I load the page there is a delay of almost 3 seconds to get the data from the db and show it in my html page...
When I surf directly to the API, I built using PHP, the required data is shown instantly...
How is this possible and how can I speed up this proces?
(if needed, my API and .htaccess)
API
require '.././libs/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app = \Slim\Slim::getInstance();
$app->get('/orderoverview/:customerID', function ($customerID) {
$sql = "SELECT `customerName` FROM `customers` WHERE `customerID` = $customerID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$customername = $row["customerName"];
}
}
else {
echo "Customer name failure";
}
$sql = "SELECT `orderID` FROM `order` WHERE `customerID` = $customerID";
$result = $conn->query($sql);
if($result->num_rows > 1){
echo "You already have a pending order! <br>";
}
else if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$orderID = $row["orderID"];
}
step2($orderID, $customername);
} else {
echo "GET orderID failure";
}
});
$app->run();
function step2($orderID, $customername){
mysql_connect($servername, $username, $password);
mysql_select_db($dbname);
$query = mysql_query("SELECT `orderdetailID` FROM `orderdetail` WHERE `orderID` = '$orderID'");
$results = array();
while($line = mysql_fetch_array($query, MYSQL_ASSOC)){
$results[] = $line;
}
step3($orderID, $results, $customername);
}
function step3($orderID, $results, $customername){
global $conn, $servername, $username, $password, $dbname;
$to = 0;
$extracounter = 1;
$extrasprice = 0;
foreach($results as $key=>$odt)
{
$extracounter = 1;
$odb = $odt["orderdetailID"];
$sql = "SELECT `productID`, `orderdetailAantal` FROM `orderdetail` WHERE `orderdetailID` = '$odb'";
$sql2 = "SELECT `extraID` FROM `orderdetailextra` WHERE `orderdetailID` = '$odb'";
$result = $conn->query($sql);
$result2 = $conn->query($sql2);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$sql3 = "SELECT `productTitle` FROM `products` WHERE `productID` = '$row[productID]'";
$sql4 = "SELECT `productPrijs` FROM `products` WHERE `productID` = '$row[productID]'";
$result3 = $conn->query($sql3);
if($result3->num_rows > 0) {
while($row1 = $result3->fetch_assoc()){
$productTitle = $row1["productTitle"];
}
}
$result4 = $conn->query($sql4);
if($result4->num_rows > 0) {
while($row1 = $result4->fetch_assoc()){
$productPrice = $row1["productPrijs"];
}
}
$order[$to] = array(
"orderdetailID" => $odb,
"productTitle" => $productTitle,
"productPrice" => $productPrice,
"orderdetailAantal" => $row["orderdetailAantal"],
"extra1" => "",
"extra2" => "",
"extra3" => "",
"extra4" => "",
"extrasPrice" => ""
);
$to++;
}
} else {
echo 'fout sql 1';
}
}
}
}
}
echoResponse(200, $order);
}
function echoResponse($status_code, $response) {
global $app;
$app->status($status_code);
$app->contentType('application/json');
echo json_encode($response,JSON_NUMERIC_CHECK);
}
.HTACCESS
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ %{ENV:BASE}index.php [QSA,L]
RewriteBase /localsites/serf/weap/api/v1

Related

Why is this AJAX call not working in IE 11?

I have a notifications system on my site, that utilizes AJAX to update in real-time. The problem is that it works on every browser except IE 11. After looking around I noticed some people advising to use cache:false in the call. However, this makes the code non-functional across all browsers. Anyone know what the solution is?
JAVASCRIPT:
<script>
$(document).ready(function(){
$('.notif_count').html('0');
function load_unseen_notification(view = '')
{
$.ajax({
url:"notif_follow.php",
method:"POST",
data:{view:view},
dataType:"json",
success:function(data)
{
$('.notif_follow').html(data.notification);
if(data.notif_count > 0)
{
$('.notif_count').html(data.notif_count);
}
}
});
}
load_unseen_notification();
$(document).on('click', '.notif', function(){
$('.notif_count').html('0');
load_unseen_notification('yes');
});
setInterval(function(){
load_unseen_notification();;
}, 5000);
});
</script>
PHP:
<?php
session_start();
require_once 'class.channel.php';
$user_notif = new USER();
$user_id = $_SESSION['userID'];
if(isset($_POST["view"]))
{
if($_POST["view"] != '')
{
$stmt = $user_notif->runQuery("UPDATE notif_follow SET status = 1 WHERE receive_id = ?");
$stmt->bindValue(1,$user_id);
$stmt->execute();
}
$stmt = $user_notif->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$user_id));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $user_notif->runQuery("SELECT * FROM notif_follow WHERE receive_id= ? ORDER BY id DESC LIMIT 5");
$stmt->bindValue(1,$user_id);
$stmt->execute();
$notifs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$notification = '';
if(count($notifs) > 0)
{
foreach($notifs as $notif)
{
$send_id = $notif['send_id'];
$query2 = $user_notif->runQuery("SELECT * FROM following WHERE user1_id=:uid1 AND user2_id=:uid2");
$query2->execute(array(":uid1"=>$user_id,":uid2"=>$send_id));
$query2result = $query2->fetchAll(PDO::FETCH_ASSOC);
if(count($query2result) > 0){
$follow = '<button class="button" style="margin:2px;">Remove Channel</button>';
}
else{
$follow = '<button class="button" style="margin:2px;">Add Channel</button>';
}
$notification .= '
<li>
<div class="notifbox">
<strong style="color: #4b8ed3;">'.$notif["send_name"].'</strong><p style="color: #fff;"> has added you.</p>
'.$follow.'
<button class="button" style="margin:2px;">View Channel</button>
</div>
</li>
<div class="sectionheader3"></div>
';
}
}
else
{
$notification .= '<li><h2 style="color: #4b8ed3; padding: 10px;">No Notifications Found<h2></li>';
}
$count = $user_notif->runQuery("SELECT * FROM notif_follow WHERE receive_id= ? AND status= 0");
$count->bindValue(1,$user_id);
$count->execute();
$countresult = $count->fetchAll(PDO::FETCH_NUM);
if(count($countresult) > 0){
$notif_count = count($countresult);
}
else{
$notif_count = 0;
}
header('Content-type: application/json');
$notif_array = array('notification'=>$notification,'notif_count'=>$notif_count);
echo json_encode($notif_array);
}
?>

How can I print "not found" when the code output is empty?

I mixed an "ajax select" and "while scrolling load data" script, and this is working, but I don't know how to print "not found data" in div.status when the output variable (on animals.php) is empty.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Animals</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="search">
<div class="filter category">
<select name="category" id="category">
<option value="">All</option>
<option value="free">Free</option>
<option value="lost">Lost</option>
<option value="found">Found</option>
</select>
</div>
<div class="filter chipnumber">
<input type="text" name="chipnumber" id="chipnumber"></div>
</div>
<div class="send">
<button type="submit" id="submit">Search</button>
</div>
</div>
<script>
$(document).ready(function() {
var animal_limit = 6;
var animal_start = 0;
var animal_action = 'inactive';
function load_animal_data() {
var category = $('#category').val();
var chipnumber = $('#chipnumber').val();
$.ajax({
url: "animals.php",
method: "POST",
data: {animal_limit:animal_limit, animal_start:animal_start, animal_action:animal_action, category:category, chipnumber:chipnumber},
success:function(data) {
$('div.animals').append(data);
if (data == '') {
animal_action = 'active';
} else {
animal_action = 'inactive';
}
}
});
}
load_animal_data();
function search() {
var category = $('#category').val();
var chipnumber = $('#chipnumber').val();
animal_start = 0;
load_animal_data();
}
$('#search').on('click', function() {
search();
});
$(window).scroll(function () {
if ($(window).scrollTop() + $(window).height() > $('div.animals').height() && animal_action == 'inactive') {
animal_action = 'active';
animal_start = animal_start + animal_limit;
setTimeout(function() {
load_animal_data();
}, 1000);
}
});
});
</script>
<div class="animals"></div>
<div class="status"></div>
</body>
</html>
animals.php
<?php
$connect = mysqli_connect("localhost", "root", "", "petsdata");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_set_charset($connect,"utf8");
$output = '';
$animal_start = $connect->real_escape_string($_POST["animal_start"]);
$animal_limit = $connect->real_escape_string($_POST["animal_limit"]);
$category = $connect->real_escape_string($_POST["category"]);
$chipnumber = $connect->real_escape_string($_POST["chipnumber"]);
if (isset($animal_start, $animal_limit, $category, $chipnumber)) {
if (!empty($category) && !empty($chipnumber)) {
$query = mysqli_query($connect, "SELECT * FROM animals WHERE chipnumber LIKE '%".$chipnumber."%' AND category = '".$category."' ORDER BY id LIMIT ".$animal_start.", ".$animal_limit."");
}
else if (!empty($category)) {
$query = mysqli_query($connect, "SELECT * FROM animals WHERE category = '".$category."' ORDER BY id LIMIT ".$animal_start.", ".$animal_limit."");
}
else if (!empty($chipnumber)) {
$query = mysqli_query($connect, "SELECT * FROM animals WHERE chipnumber LIKE '%".$chipnumber."%' AND status = '1' ORDER BY id DESC LIMIT ".$animal_start.", ".$animal_limit."");
}
else {
$query = mysqli_query($connect, "SELECT * FROM animals ORDER BY id DESC LIMIT ".$animal_start.", ".$animal_limit."");
}
while ($row = mysqli_fetch_array($query)) {
$output .= '<div class="animal">';
$output .= '<span>Category: ' . $row["category"] . '</span>';
$output .= '<span>Chipnumber: ' . $row["chipnumber"] . '</span>';
$output .= '</div>';
}
}
echo $output;
?>
if($query->num_rows > 0){
//Proceed as normally
}else{
$output = 'No data Found';
}

php and ajax JavaScript pagination comment system

Trying to build a commenting system. Were comments are posted with AJAX. With comment count with Pagination. I have success achieving both, but putting them together is another story. I have tried doing 2 ajax calls. One for getting records from the database and showing pagination. The other call for recording records to the database.
// this is the first ajax call to to get the results and show pagination buttons
<script>
function request_page(pn){
var two = <?php echo $img_id; ?>;
var showmax = <?php echo SHOWMAX; ?>; // results per page
var totalpages = <?php echo $totalpages; ?>;
//controls for pigmintation
var pagination_controls = document.getElementById("pagination_controls");
var results_box = document.getElementsByClassName(two)[0];
params = 'showmax=' + showmax + '&totalpages=' + totalpages + '&pn=' + pn + '&img_id=' + two;
request = new ajaxRequest()
request.open("POST", "response5.php", true)
request.setRequestHeader("Content-type",
"application/x-www-form-urlencoded")
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
results_box.innerHTML =
this.responseText
}
else alert("Ajax error: No data received")
}
else alert( "Ajax error: " + this.statusText)
}
}
request.send(params)
function ajaxRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}
var paginationCtrls = "";
// Only if there is more than 1 page worth of results give the user pagination controls
if(totalpages != 1)
{
if( pn > 1){
paginationCtrls += '<button onclick="request_page('+(pn-1)+')"><</button>';
}
paginationCtrls += ' <b>Page '+pn+' of '+totalpages+'</b> ';
if (pn != totalpages) {
paginationCtrls += '<button onclick="request_page('+(pn+1)+')">></button>';
}
}
pagination_controls.innerHTML = paginationCtrls;
}
</script>
<script> request_page(<?php echo $totalpages; ?>); </script>
/// the response
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$curPage = (int) sanitizeString($_POST['pn']);
$showmax = (int) sanitizeString($_POST['showmax']);
$totalpages = (int) sanitizeString($_POST['totalpages']);
$z = (int) sanitizeString($_POST['img_id']);
if ($curPage < 1) {
$curPage = 1;
} else if ($curPage > $totalpages) {
$curPage = $totalpages;
}
$offset = ($curPage-1) * $showmax;
// var_dump($showmax);
$one = $showmax;
$getcomments = "SELECT I.comment, I.created, U.user_pic_path, U.user_id, U.username, G.file_name
FROM users U
INNER JOIN img_comment I
ON I.img_id = ?
LEFT OUTER JOIN gallery G
ON G.img_id = U.user_pic_path
WHERE I.user_id = U.user_id
ORDER BY UNIX_TIMESTAMP(created) ASC
LIMIT ?, ?";
$stmt = $pdo->prepare($getcomments);
$stmt->bindParam(1, $z, PDO::PARAM_INT);
$stmt->bindParam(2, $offset, PDO::PARAM_INT);
$stmt->bindParam(3, $one, PDO::PARAM_INT);
$stmt->execute();
//fetch resuls
while ($row = $stmt->fetch()){
echo "<div class='chat-entry users person triggerProfile'>";
$bulls = get_web_path($row['user_pic_path']);
if(isset($row['file_name']))
{
$done32 = "http://localhost/new11/users/{$row['username']}/thumbs/{$row['file_name']}";
}else
{
$done32 = 'http://localhostnew11/users/noimage.jpg';
}
$bulls = get_web_path($row['file_name']);
echo "<a class='head users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>
<img class='imgcom' src='$done32'>
</a>
<div class='body'>
<div class='basic'>
<span class='username'>
<a class='users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>{$row['username']} </a>
</span>
</div>
<div class='message'>{$row['comment']}
</div>
</div>
</div>";
}
}
////ajax call # 2 is triggered when ever the comment form is submitted
<div>
<form method='post' id="form<?php echo $img_id; ?>" name="<?php echo $img_id; ?>">
<textarea class='lake' name='one' placeholder="Comment" id='<?php echo $img_id; ?>'></textarea>
<input id="submit" onclick="showUser(document.getElementById(<?php echo $img_id; ?>).value, <?php echo $img_id; ?>);" type="button" value="Submit">
</form>
</div>
//// the ajax call function
function showUser(a, b){
name = a;
two = b;
yes = "form" + two;
params = 'name1=' + name + '&two1=' + two;
request = new ajaxRequest()
request.open("POST", "response10.php", true)
request.setRequestHeader("Content-type",
"application/x-www-form-urlencoded")
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
document.getElementsByClassName(two)[0].innerHTML =
this.responseText
}
else alert("Ajax error: No data received")
}
else alert( "Ajax error: " + this.statusText)
}
}
request.send(params)
function ajaxRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}
document.getElementById(yes).reset();
return false;
}
The response
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
define('SHOWMAX', 5);
$q = sanitizeString($_POST['name1']);
$z = sanitizeString($_POST['two1']);
$b = sanitizeString($_SESSION['user_id']);
$sql = 'INSERT INTO img_comment (img_id, comment, user_id)
VALUES(:img_id, :comment, :user_id)';
// prepare the statement
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':img_id', $z, PDO::PARAM_INT);
$stmt->bindParam(':comment', $q, PDO::PARAM_STR);
$stmt->bindParam(':user_id', $b, PDO::PARAM_INT);
$stmt->execute();
$OK = $stmt->rowCount();
$getCount = 'SELECT COUNT(*) FROM img_comment WHERE img_id ='. $z;
// submit query and store result as $totalPix
$total = $pdo->query($getCount);
$totalCount = $total->fetchColumn();
// var_dump($totalCount);
$total = (int)$totalCount;
$totalpages = (int) ceil($total/ SHOWMAX);
$offset = ($totalpages-1) * SHOWMAX;
$one = SHOWMAX;
if($totalCount > 0){
$getcomments = "SELECT I.comment, I.created, U.user_pic_path, U.user_id, U.username, G.file_name
FROM users U
INNER JOIN img_comment I
ON I.img_id = ?
LEFT OUTER JOIN gallery G
ON G.img_id = U.user_pic_path
WHERE I.user_id = U.user_id
ORDER BY UNIX_TIMESTAMP(created) ASC
LIMIT ?, ?";
$stmt = $pdo->prepare($getcomments);
$stmt->bindParam(1, $z, PDO::PARAM_INT);
$stmt->bindParam(2, $offset, PDO::PARAM_INT);
$stmt->bindParam(3, $one, PDO::PARAM_INT);
$stmt->execute();
while ($row = $stmt->fetch()){
echo "<div class='chat-entry users person triggerProfile'>";
$bulls = get_web_path($row['user_pic_path']);
if(isset($row['file_name']))
{
$done32 = "http://localhost/new11/users/{$row['username']}/thumbs/{$row['file_name']}";
}else
{
$done32 = 'http://localhostnew11/users/noimage.jpg';
}
$bulls = get_web_path($row['file_name']);
echo "<a class='head users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>
<img class='imgcom' src='$done32'>
</a>
<div class='body'>
<div class='basic'>
<span class='username'>
<a class='users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>{$row['username']} </a>
</span>
</div>
<div class='message'>{$row['comment']}
</div>
</div>
</div>";
}
}
}

how to change value on mysql with php and view it dynamically without redirection refresh page

<?php echo"<td align ='center'>\".$bookstatus.\"<img src=\"img/refresh.png\" class=\"icon\"/></td>"; ?>
this link reach to s_bookstatus then change the value of bookstatus.
else if(isset($_GET['s_bookstatus']))
{
$id_commission = $_GET['id_commission'];
$qrycheck = "select * from commission where id_commission='$id_commission'";
$rscheck = mysqli_query($con,$qrycheck) or die(mysqli_error($con));
$rowcheck = mysqli_fetch_array($rscheck);
$s_bookstatus = $rowcheck['book_status'];
$id_book = $rowcheck['id_book'];
$qrybooklist = "select * from booklist where id_book='$id_book' ";
$rsbooklist = mysqli_query($con,$qrybooklist) or die(mysqli_error($con));
$rowbooklist = mysqli_fetch_array($rsbooklist);
$stock = $rowbooklist['stock'];
if($s_bookstatus == 'Available')
{
$check = 'Not Available';
$newstock = $stock - 1;
}
else if($s_bookstatus == 'Not Available')
{
$check = 'Available';
$newstock = $stock + 1;
}
mysqli_query($con,"update booklist set stock = $newstock where id_book = '$id_book' ");
$qry = "update commission set book_status ='$check' where id_commission ='$id_commission' ";
mysqli_query($con,$qry) or die(mysqli_error($con));
echo "<meta http-equiv='refresh' content='0; url=home.php?commission'>";
}
How to change this code to ajax without meta http-equiv refresh so the data changed dynamically in one page.
thank you..
if(isset($_GET['query'])){
$query = $_GET['query'];
$result = mysqli_query($con,$query) or die(mysqli_error($con));
}
else
{
$query = "select * from commission c left join booklist b on c.id_book = b.id_book $filterqry $search";
$result = mysqli_query($con,$query) or die(mysqli_error($con));
}
<td align ='center'>".$bookstatus."<img src=\"img/refresh.png\" class=\"icon\"/></td>
else if(isset($_GET['s_bookstatus']))
{
$id_commission = $_GET['id_commission'];
$query = $_GET['query'];
$qrycheck = "select * from commission where id_commission='$id_commission'";
$rscheck = mysqli_query($con,$qrycheck) or die(mysqli_error($con));
$rowcheck = mysqli_fetch_array($rscheck);
$s_bookstatus = $rowcheck['book_status'];
$id_book = $rowcheck['id_book'];
$qrybooklist = "select * from booklist where id_book='$id_book' ";
$rsbooklist = mysqli_query($con,$qrybooklist) or die(mysqli_error($con));
$rowbooklist = mysqli_fetch_array($rsbooklist);
$stock = $rowbooklist['stock'];
if($s_bookstatus == 'Available')
{
$check = 'Not Available';
$newstock = $stock - 1;
}
else if($s_bookstatus == 'Not Available')
{
$check = 'Available';
$newstock = $stock + 1;
}
mysqli_query($con,"update booklist set stock = $newstock where id_book = '$id_book' ");
$qry = "update commission set book_status ='$check' where id_commission ='$id_commission' ";
mysqli_query($con,$qry) or die(mysqli_error($con));
echo "<meta http-equiv=\"refresh\" content=\"0; url=home.php?commission&query=$query \">";
}

Simple auto-updating AJAX page

So I am sort of new to AJAX and I am trying to get this to work. What I am trying to do is create a messaging app that automatically updates every 3 seconds.
Here is my script:
function first() {
var searchUser = $("input[name='username']").val();
$.post("messageSearch.php", {userVal: searchUser}, function(output){
$('#messageField').html(output);
});
}
function searchm() {
var searchUser = $("input[name='username']").val();
$.post("messageSearch.php", {userVal: searchUser}, function(output){
$('#messageField').val(output);
});
}
setInterval( "searchm()", 3000 );
Here is my messageSearch.php:
<?php
session_start();
$userdb = new mysqli('localhost', 'test', '', 'social-network');
if(isset($_POST['userVal'])) {
$searchm = $_POST['userVal'];
$output = '';
if ($searchm == ''){
echo $output;
exit();
}
$uidquery = mysqli_query($userdb, "SELECT * FROM users WHERE username='$searchm' LIMIT 1");
$uid= '';
while($row2 = mysqli_fetch_array($uidquery)) {
$uid = $row2['id'];
}
$uid = 2;
$query = mysqli_query($userdb, "SELECT * FROM messages WHERE p2=$uid AND `read`='n' LIMIT 3");
$count = mysqli_num_rows($query);
if($count == 0) {
$output = 'You have no messages.';
} else {
while($row = mysqli_fetch_array($query)) {
$from = $row['p1'];
$message = $row['message'];
$time = $row['time'];
$time = date('Y-m-d H:i:s', strtotime($time));
$fromResult = mysqli_query($userdb, "SELECT * FROM users WHERE id = '$from'");
while($row1 = mysqli_fetch_array($fromResult)) {
$fromFirst = $row1['first_name'];
$fromLast = $row1['last_name'];
$from = $fromFirst.' '.$fromLast;
}
$output .= '
<li>
<a href="#">
<div>
<strong>'.$fromFirst.' '.$fromLast.'</strong>
<span class="pull-right text-muted">
<em>'.$time.'</em>
</span>
</div>
<div>'.$message.'</div>
</a>
</li>
<li class="divider"></li>
';
}
$output .= '<li><a class="text-center" href="#"><strong>See All Messages</strong> <i class="fa fa-angle-right"></i></a></li>';
}
}
echo ($output);
?>
For some reason the first load works fine though the second one comes up blank. Hopefully you can help, though thanks in advance.
setInterval( "searchm()", 3000 ); should be
setInterval( searchm, 3000 );
Another error, in your PHP:
$query = mysqli_query($userdb, "SELECT * FROM messages WHERE p2=$uid AND `read`='n' LIMIT 3")
should be:
$query = mysqli_query($userdb, "SELECT * FROM messages WHERE p2=".$uid." AND `read`='n' LIMIT 3")
Lastly
$fromResult = mysqli_query($userdb, "SELECT * FROM users WHERE id = '$from'");
to
$fromResult = mysqli_query($userdb, "SELECT * FROM users WHERE id = ".$from);

Categories