Notification system jQuery, PHP, and MySQL - php

I'm trying to develop a notification system using jQuery and PHP. So I've created a new table in the database where I'm going to store all the new notifications. Using jQuery I've been able to show an alert (bubble icon) showing the number of new lines added to the database, but I'm now stuck because I don't really know how to update the database (fire update.php file) when I click the icon (.icon-bell) which does activate a drop-down menu.
This is the jQuery script I've added to the index page
<script type="text/javascript">
$(document).ready(function(){
$("#datacount").load("select.php");
setInterval(function(){
$("#datacount").load('select.php')
}, 20000);
});
</script>
This is the HTML code in the index page
<li class="dropdown dropdown-extended dropdown-notification dropdown-dark" id="header_notification_bar">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<i class="icon-bell">
</i>
<span class="badge badge-success"><div id="datacount">
</div>
</span>
</a>
<ul class="dropdown-menu" >
<li class="external">
<h3>
<span class="bold">12 pending</span>
notifications
</h3>
view all
</li>
<li>
<ul class="dropdown-menu-list scroller" style="height: 250px;" data-handle-color="#637283">
<li>
<a href="javascript:;">
<span class="time">just now</span>
<span class="details">
<span class="label label-sm label-icon label-success">
<i class="fa fa-plus">
</i>
</span> New user registered. </span>
</a>
</li>
</ul>
</li>
</ul>
</li>
This is the select.php file
<?php
$sql = "SELECT * from tbl_noti where status = 'unread'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$count = $result->num_rows;
echo $count;
$conn->close();
?>
This is the update.php file
<?php
$sql = "update tbl_noti set status = 'read'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$count = $result->num_rows;
echo $count;
$conn->close();
?>

You can use PHP + Ajax to accomplish this task. I have created a simple notification system and you can easily clone it from GitHub(https://github.com/shahroznawaz/php-notifications).
let's create an index.php file and put the following code. it will create a form. all the data will get by ajax call and updated in the view.
<!DOCTYPE html>
<html>
<head>
 <title>Notification using PHP Ajax Bootstrap</title>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
 <br /><br />
 <div class="container">
  <nav class="navbar navbar-inverse">
   <div class="container-fluid">
    <div class="navbar-header">
     <a class="navbar-brand" href="#">PHP Notification Tutorial</a>
    </div>
    <ul class="nav navbar-nav navbar-right">
     <li class="dropdown">
      <span class="label label-pill label-danger count" style="border-radius:10px;"></span> <span class="glyphicon glyphicon-bell" style="font-size:18px;"></span>
      <ul class="dropdown-menu"></ul>
     </li>
    </ul>
   </div>
  </nav>
  <br />
  <form method="post" id="comment_form">
   <div class="form-group">
    <label>Enter Subject</label>
    <input type="text" name="subject" id="subject" class="form-control">
   </div>
   <div class="form-group">
    <label>Enter Comment</label>
    <textarea name="comment" id="comment" class="form-control" rows="5"></textarea>
   </div>
   <div class="form-group">
    <input type="submit" name="post" id="post" class="btn btn-info" value="Post" />
   </div>
  </form>
 </div>
</body>
</html>
Now create ajax calls like this:
<script>
$(document).ready(function(){
// updating the view with notifications using ajax
function load_unseen_notification(view = '')
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{view:view},
dataType:"json",
success:function(data)
{
$('.dropdown-menu').html(data.notification);
if(data.unseen_notification > 0)
{
$('.count').html(data.unseen_notification);
}
}
});
}
load_unseen_notification();
// submit form and get new records
$('#comment_form').on('submit', function(event){
event.preventDefault();
if($('#subject').val() != '' && $('#comment').val() != '')
{
var form_data = $(this).serialize();
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data)
{
$('#comment_form')[0].reset();
load_unseen_notification();
}
});
}
else
{
alert("Both Fields are Required");
}
});
// load new notifications
$(document).on('click', '.dropdown-toggle', function(){
$('.count').html('');
load_unseen_notification('yes');
});
setInterval(function(){
load_unseen_notification();;
}, 5000);
});
</script>
You also need to fetch all the records from database and update the status for the notification viewd. create fetch.php file and add the following code:
<?php
include('connect.php');
if(isset($_POST['view'])){
// $con = mysqli_connect("localhost", "root", "", "notif");
if($_POST["view"] != '')
{
   $update_query = "UPDATE comments SET comment_status = 1 WHERE comment_status=0";
   mysqli_query($con, $update_query);
}
$query = "SELECT * FROM comments ORDER BY comment_id DESC LIMIT 5";
$result = mysqli_query($con, $query);
$output = '';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
  $output .= '
  <li>
  <a href="#">
  <strong>'.$row["comment_subject"].'</strong><br />
  <small><em>'.$row["comment_text"].'</em></small>
  </a>
  </li>
  ';
}
}
else{
    $output .= '<li>No Noti Found</li>';
}
$status_query = "SELECT * FROM comments WHERE comment_status=0";
$result_query = mysqli_query($con, $status_query);
$count = mysqli_num_rows($result_query);
$data = array(
   'notification' => $output,
   'unseen_notification'  => $count
);
echo json_encode($data);
}
?>
Now you will be able to see the notification in navigation bar like this:
when you click the dropdown the status of views notification will update and count will disappear.

To execute PHP asynchronously, you need to use AJAX. jQuery has a few functions for this purpose.
$.ajax: Fully customizable asynchronous request, including error handling, headers, etc.
$.post: AJAX restricted to POST.
$.get: AJAX restricted to GET.
Both $.post and $.get can be accomplished with $.ajax, however they are, in most situations, easier to work with. You most likely will only need $.get in this case, since no additional data is being passed in the request.
Example code:
$.get(
"update.php",
function(result) {
console.log(result)
}
);
Here, result is the data outputted from update.php.

Use ajax to execute the PHP queries so they can execute in real time without page reload.

Related

Back to the main content of a div box from a Jquery .load

I have a chatting system project php with a nav and has a child div called inbox where inbox has a children div.message and div.message__requests:
<div class="inbox">
<div class="messages">
<header>
<nav>
<a id="messages"><b>Messages</b></a><a id="messageRequests"><b>Message Requests</b></a>
</nav>
<hr>
<form action="includes/chatsearch-inc.php" method="POST">
<input type="text" name="search" placeholder="Search a user or applicant\'s name">
<button name="submit"><i class="fa fa-search"></i></button>
</form>
</header>
<section>';
$sql = "SELECT * FROM users WHERE NOT usersId ='".$_SESSION['userid']."';";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo '<div class="user__container">
<input type="hidden" data-userid="'.$row['usersId'].'">
<img src="profilepic/'.$row['usersProfilePic'].'">
<div class="user">
<p><b>'.$row['usersName'].'</b></p>
<p class="message">You: dssasdas</p>
</div>
</div>
<hr>';
}
echo '</section>
</div>
<div class="message__requests">
<nav>
<a id="messages"><b>Messages</b></a><a id="messageRequests"><b>Message Requests</b></a>
</nav>
<section>
<div class="user__container">
<img src="profilepic/'.$profilepic.'">
<div class="user">
<p><b>'.$_SESSION['username'].'</b></p>
<p class="message">asdasdsd</p>
</div>
</div>
<hr>
<div class="user__container">
<img src="profilepic/'.$profilepic.'">
<div class="user">
<p><b>'.$_SESSION['username'].'</b></p>
<p class="message">asdasdsd</p>
</div>
</div>
<hr>
</section>
</div>
</div>
Where div.messages shows the users inbox like the home screen of facebook messenger app.
If I click the said nav, the inbox will pop in the middle of the screen and the div.message is the default content.
Now when I click a div.user__container inside my div.messages, I can load the user chat box, like when you click a user in facebook messenger inside the div.messages, replacing all the content of div.messages with what I have in my other php file (simulating a real time chat box):
$sql = "SELECT * FROM messages AS m LEFT JOIN users AS u ON m.outgoingUsersId = u.usersId WHERE (incomingUsersId = '$incoming' AND outgoingUsersId = '$outgoing') OR (incomingUsersId = '$outgoing' AND outgoingUsersId = '$incoming') ORDER BY msgId DESC;";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
if ($row['outgoingUsersId'] == $outgoing) {
$output .= '<div class="chat outgoing">
<div class="message">
<p>'.$row['msgContent'].'</p>
</div>
</div>';
}
else {
$output .= '<div class="chat incoming">
<img src="profilepic/'.$row['usersProfilePic'].'">
<div class="message">
<p>'.$row['msgContent'].'</p>
</div>
</div>';
}
}
echo $output;
}
And I can achieve this all by my jquery call:
$('section .user__container').click(function() {
var userid = $(this).children('input').data('userid');
$('.inbox .messages').load('includes/ajax-load/chatpage-aload.php',
{
usersid : userid
}, function() {
$('.user__inbox header i').click(function() {
// I want to load back to div.messages content
});
var sender = $('#chatForm #chatSender').val();
var receiver = $('#chatForm #chatReceiver').val();
setInterval(() => {
$.post('includes/ajax-func/getchat-afunc.php', {
outgoingUsersId : sender,
incomingUsersId : receiver
}, function (response) {
$('.user__inbox section').html(response);
});
}, 500
);
$('#chatForm').submit(function(e) {
e.preventDefault();
var message = $('#chatForm input[type="text"]').val();
$.post('includes/ajax-func/insertchat-afunc.php', {
outgoingUsersId : sender,
incomingUsersId : receiver,
message : message
}, function (data) {
$('#chatForm input[type="text"]').val("");
});
});
});
});
My question is, how can I go back to the main content of div.messages (like how users in messenger app can go bck to the home screen when the click the back button beside the users info in their header) without reloading the whole webpage, when I click the:
$('.user__inbox header i').click(function() {
// I want to load back to div.messages content
});
Or any recommendations to my code? Thanks

keeping what i searched in my page

i'm working on a a website and i've made a php file that will show my search results, (i'm working on request appointment) so when i click that it works but the only problem is my webpage refresh and it shows a blank page until i click on home button to redirect
// my research loop...
if(isset($_GET['submit-search'])) {
$search = mysqli_real_escape_string($conn, $_GET['search']);
$sql = "SELECT * FROM doctor WHERE DoctorFullName LIKE '%$search%' OR DoctorLocation LIKE '%$search%' OR DoctorSpeciality LIKE '%$search%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if ($queryResult > 0) {
?>
<div class="container overflow">
<div class="container overflow">
<span class="mentor">
<h2 class="display Text-mentor">
<span class="mentor-admin">If the result shown bellow not seems like what you need then ;</span>
<span class="mentor-admin-quote">select the speciality of the doctor you need and your insurance, and <span class="turquoise">search</span> again</span>
</h2>
</span>
</div>
<div class="container overflow">
<p class="p-about-results"><?php echo "There is ".$queryResult." result matching your search"?></p>
<p class="p-about-results">we hope that these results are the ones you are looking for :</p>
</div>
<?php
while ($row = mysqli_fetch_assoc($result)) :
?>
// my calendar for so i can submit appointment
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<form>
<input type="text" name="ap-time" id="t1" class="modal-input-text" placeholder="Choose a date">
<div id="sub" style="top: 40px;left: 5px;z-index:1;text-align: center;"></div>
<input type=submit name="ap_validation" value="request appointment" class="input-requestdate">
</form>
</div>
</div>
//Ajax code that i've been working on
<script type="text/javascript">
$(document).ready(function(){
//alert("jquery is working");
$(".input-requestdate").click(function(){
var name = $(".modal-input-text").val();
$.ajax({
url: "Appointment.php",
type: "POST",
async: false,
data: {
"done": 1,
"message": name,
},
success: function(data){
alert("requested");
window.location = window.location.href
}
})
});
});
</script>`
thanks for helping :)

I create a like button ,but after refresh the page ,the like count becomes 0

I create a like button, when click it ,first check whether the user is logged in.Only logged in , the user can click the like button and the like counts add 1.But everytime refresh page,the counts become 0 again.Why this would be happen?
html:
<div class="post-footer">
<div class="flag">
<span class="flag-wrapper">
<a class="flag-action" href="#">
<i class="fa fa-heart-o" ></i>
<span class="count">0</span>
<span class="flag-text" >Like this news post</span>
</a>
</span>
</div>
</div>
jquery:
$(document).ready(function(){
$(document).on("click", ".flag" ,function(){
//
var count = $(".count").text();
//
var id= $(".ds-subtitle").attr("rel");
// alert(id);
alert(count);
$.ajax({
url:"functions/php/like.php",
type:"POST",
// cache:false,
data:{count:count,id:id},
success:function(data){
// alert(data);
// console.log(data);
if (data == "0") {
alert("do not log in");
$("#popup-box1").show();
}
if (data == "1"){
alert("already log in");
$("#popup-box1").hide();
// alert();
count++;
$("span .count").text(count);
}
}
});
});
});
php:
<?php
session_start();
if (!isset($_SESSION["id"])) {
echo "0";
}else{
echo "1";//
//
$id= $_POST["id"];
//
$userid = $_SESSION["id"];
//
$conn = mysqli_connect("localhost", "root", "", "maroon5");
//
$sql = " INSERT INTO fav (news_id, user_id)
VALUES ('$id', '$userid') ";
$res = mysqli_query($conn, $sql);
}
?>
But everytime refresh page,the counts become 0 again
Because your function will be only called onclick
$(document).on("click", ".flag" ,function(){
You probably need to call same method or refresh method onload
Finally, I solve this.I put this
<?php
$conn = mysqli_connect("localhost", "root", "", "maroon5");
$sql1 = " SELECT * FROM fav WHERE news_id=1 ";
$res1 = mysqli_query($conn, $sql1);
$nums = mysqli_num_rows($res1);
?>
<div class="post-footer">
<div class="flag">
<span class="flag-wrapper">
<a class="flag-action" href="#">
<i class="fa fa-heart-o" ></i>
<?php
echo "<span class='count'>". $nums ."</span>";
?>
<!-- <span class="count">0</span> -->
<span class="flag-text" >Like this news post</span>
</a>
</span>
</div>
</div>
</article>
</div>
</div>

How to get value from mysql database row by row after each click on button?

I want to get questions one by one by clicking on button from mysql database table. Each question is one single row, want to get every next question by clicking on "next" button from every next row. I have made this code but this only shows first question in the table of first row in the database. My html code is:
<span ng-repeat="record in records" id="next">
<p id="hello">{{record.ques_no}}.
{{record.question}}</p>
<p><input type="text" ng-model="ans" id="ans" value=""></p>
<p align="center">Next</p>
</span>
php code getting value from database is:
$result=mysqli_query($con,"SELECT * FROM quest limit 1");
$record=array();
$number = 0;
while($row =mysqli_fetch_array($result))
{
$record[] = array(
'ques_no'=> $row['ques_no'],
'question'=> $row['question'],
'answer'=> $row['answer']
);
$number++;
}
<html>
<head>
<style>
.invisible{
display:none;
}
.visible{
display:visible;
}
</style>
<script src="js/jquery.min.js"></script>
<script>$(function()
{
$( "#button" ).click(function()
{
$( "div.container div.invisible" ).first().addClass( "visible" ).removeClass("invisible");
});
});
</script>
</head>
<div class="container">
<div class="invisible">1</div>
<div class="invisible">2</div>
<div class="invisible">3</div>
<div class="invisible">4</div>
<div class="invisible">5</div>
<div class="invisible">6</div>
<div class="invisible">7</div>
<div class="invisible">8</div>
<div class="invisible">9</div>
<div class="invisible">10</div>
</div>
<input type="button" id="button"/>
</html>
Something I put together real quick.
$("#nex").click(function() {
var formData1 = $("#ques").val();
$.ajax({
type:'POST',
data:{'tota':formData1},
url:'list1.php',
success:function(data){
alert(data);
var json = $.parseJSON(data);
// $("#hello").html(data);
$("#hello").html(json[0]);
}
});
});
list1.php
<?php
$total=$_POST['tota'];
$input=1;
$con=mysqli_connect("localhost","root","root","school");
$result=mysqli_query($con,"SELECT * FROM quest LIMIT $total OFFSET $input");
$record=array();
echo $input;
while($row =mysqli_fetch_array($result))
{
$record[] = array(
'ques_no'=> $row['ques_no'],
'question'=> $row['question'],
'answer'=> $row['answer']
);
}
echo json_encode($record);
mysqli_close($con);
?>
Facing some problem in retreiving json data

post in jquery do not update element

EDIT WITH NEW JAVASCRIPT
I am trying to make a "I like this" kinda function but I have a small problem.
I am using this small javascript
function coolIt(designid) {
$.post('cool.php', {designid:designid}, function(data) {
//alert(data);
$('#cool_'+designid).text(data);
});
}
And this HTML where the "Like" button is
<span class="like"><span id="cool_'.$row["id"].'">('. $row["cools"] .')</span></span>
The cool.php runs through this:
function UpdateCool($design_id) {
$fields_up = array("cools" => 'cools + 1');
$fields_down = array("cools" => 'cools - 1');
$sql = SQLHandling::updateSQL('tdic_designs', 'id = '. $design_id .'', $fields_up);
SQLHandling::SQLquery($sql);
}
and that works perfectly. It updates the cools field with one increasing value.
When I run alert(data) on the javascript it returns nothing and the #cool_1 span element disappears.
Any idea what I might do wrong?
HTML OUTPUT:
<script type="text/javascript">
function coolIt(designid) {
$.post('cool.php', {designid:designid}, function(data) {
alert(data);
$('#cool_'+designid).text(data);
});
}
</script>
</head>
<body>
<div id="allContainer">
<div id="topArea">
<div id="topNaviArea">
<ul id="navi">
<li class="home">Home</li>
<li class="categories">Categories</li>
<li class="about">About</li>
<li class="faq">FAQ</li>
<li class="submit">Submit</li>
<li class="contact">Contact</li>
</ul>
</div>
</div>
<div id="contentBox">
<div id="login">Login // Register</div> <div id="mainContent">
<h1>// Home // Categories // HTML / CSS</h1>
<div id="catMenu">
<ul>
<li>3D</li><li>Graphic</li><li>HTML / CSS</li><li>Paintings</li><li>Photography</li><li>Portals</li><li>Webshops</li>
</ul>
<h2>1 designs<br />in this category</h2>
</div>
<div id="rightContentBox">
<ul id="displays">
<li class="displayWindow"><div class="dpwImage"><figure><img src="/testen/designs/thatdesigniscool.jpg" width="280" height="175" alt="That Design Is Cool" target="_blank"></figure></div><div class="dpwBox"><div class="dpwLeft"><span class="title">That Design Is Cool</span><span class="comments">Comments (1)</span></div><div class="dpwRight"><span class="like"><span id="cool_1">(29)</span></span></div></div> </li>
</ul>
</div>
</div>
</div>
</div>
I guess you are replacing the whole contents of div with just the server response. Why don't you append?
$('.likeIt').livequery("click",function(e){
var designid = $(this).attr('id').replace('design_id-','');
$.post('cool.php?design_id='+designid, {}, function(response){
$('#cool_'+designid).html($('#cool_'+designid).html() + response); // See if this works!
});
});
See if this helps! :)
I got it solved by editing cool.php to the following:
<?php
session_start();
ini_set("display_errors", 1);
define("INCLUDE_DIR", "includes/classes");
/* Autoload classes when used */
function __autoload($class_name) { include(INCLUDE_DIR.'/class.'. strtolower($class_name) . '.php'); }
SQLHandling::SQLconnect();
if($_POST["designid"] != '') {
$alreadyExist = mysql_num_rows(mysql_query('SELECT id FROM tdic_voted WHERE designid="'.(int)$_POST['designid'].'" AND ip="'.$_SERVER['REMOTE_ADDR'].'"'));
if($alreadyExist == 0) {
mysql_query(' UPDATE tdic_designs SET cools = cools+1 WHERE id="'.(int)$_POST['designid'].'"');
$num = mysql_fetch_row(mysql_query(' SELECT cools FROM tdic_designs WHERE id="'.(int)$_POST['designid'].'" LIMIT 1'));
echo $num[0];
mysql_query(' INSERT INTO tdic_voted (designid, ip) VALUES ("'.(int)$_POST['designid'].'","'.$_SERVER['REMOTE_ADDR'].'")');
} else{
echo 'You already think this is a cool design!';
}
}
?>

Categories