Jquery onload duplicates results - php

I'm having an issue with PHP include and jQuery onload when the <li> content refreshes onload it duplicates the results that returned from the include function
My code as below:
<li class="dropdown">
<a href="#" data-toggle="dropdown" ><img src="style/img/notification.png" /></a>
<ul style="overflow:sauto; width:300px; overflow:auto;" class="dropdown-menu">
<?php include("inc/noti_refresh.php"); ?>
</ul>
</li>
here is my noti_refresh.php:
<?php include("configa.php");
$me = $_SESSION['username'];
$noti = mysql_query("select * from notification where to_user = '$me' order by id DESC ");
//$rown = mysql_num_rows($noti);
while ($notime = mysql_fetch_array($noti)){
$me = $notime['to_user'];
$you = $notime['from_user'];
$p_id = $notime['p_id'];
$type = $notime['type'];
$uimage = mysql_query("select * from users where username = '$you'");
$uname = mysql_fetch_assoc($uimage);
$myimage = $uname['img'];
//if( $rown !=0) {
?>
<li class="ref"><img src="users/<?php echo $myimage; ?>" style="height:32px; width:32;" /> <?php echo $you; ?> Has <?php echo $type; ?> Your Image </li>
<li class="divider"></li>
<?php }?>
and this is my jQuery function:
<script type="text/javascript">
function Load_external_content()
{
$('.ref').load('inc/noti_refresh.php').hide().fadeIn(3000);
}
setInterval('Load_external_content()', 10000);
</script>
Now whenever the <li class="ref"> is refreshed, the results will show duplicated.
Could anyone help?

Shouldn't you load the content into .dropdown-menu instead of into .ref?

i solved it by removing the <?php include('notif_refresh.php');
and instead i just used these two functions
<script type="text/javascript">
$(document).ready(function(){
$('.ref').load('inc/noti_refresh.php');
});
</script>
<script type="text/javascript">
function Load_external_content()
{
$('.ref').load('inc/noti_refresh.php').hide().fadeIn(3000);
}
setInterval('Load_external_content()', 10000);
</script>

Related

Notification system jQuery, PHP, and MySQL

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.

combine jquery in php for displaying a collapsible list fetched from database

The following program is supposed to display the subjects and subcategory in collapsible list order.
But the collapsible list is applied for the first entry only. The rest of the items appear static. They dont collapse. Why??????????
<html><head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<?php
$con = mysqli_connect("localhost","root","","test");
$sql="select * from subject";
$res_subject=mysqli_query($con,$sql);
while($row=mysqli_fetch_array($res_subject))
{
?>
<UL id="subj_tree">
<LI><span> <?php echo $row['sub_name'];?> </span>
<UL>
<?php
$sql="select * from sub_categry where sub_id=".$row['sub_id'];
$res_sub_cat=mysqli_query($con,$sql);
while($val=mysqli_fetch_array($res_sub_cat))
{
?> <LI><span> <?php echo $val['sub_cat_name']; ?> </span></LI>
<?php } ?>
</UL>
</LI>
</UL>
<?php
}
?>
</html>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(function(){
$('#subj_tree').find('UL').hide();
$('#subj_tree').find('SPAN').click(function(e){
$(this).parent().children('UL').toggle();
});
});
mysql db is like as follow:
sub_categry: sub_cat_id, sub_cat_type, sub_id (foreign key subject.sub_id)
subject: sub_id, sub_name.
The jQuery find() method only gives you the first element that matches the selector. If you want all the tags under #subj_tree to be hidden, you would have to use
$('#subj_tree ul').hide();
You can't trigger a click using find() function. You should use this function instead:
$('#subj_tree > li > span').click(function() {
$(this).parent().children('UL').toggle();
});
It's because your structure is completely wrong. Your code is also wildly inefficient. Also, you are including jquery twice. That probably doesn't do much good!
Your script tag also isn't closed and it should be included within the body.(something you are also missing)
Can you try it like this?:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<style>#subj_tree ul {display: none;}</style>
</head>
<body>
<?php
$con = mysqli_connect("localhost", "root", "", "test");
$sql = "select * from subject";
$res_subject = mysqli_query($con, $sql);
while( $row = mysqli_fetch_array($res_subject) ) {
?>
<ul id="subj_tree">
<li><span> <?php echo $row['sub_name']; ?> </span>
<ul>
<?php
$sql = "select * from sub_categry where sub_id=" . $row['sub_id'];
$res_sub_cat = mysqli_query($con, $sql);
while( $val = mysqli_fetch_array($res_sub_cat) ) {
?>
<li><span> <?php echo $val['sub_cat_name']; ?> </span></li>
<?php } ?>
</ul>
</li>
</ul>
<?php
}
?>
<script type="text/javascript">
$(function () {
$('#subj_tree > li span').on("click", function (e) {
var parent = $(this).parent();
$('ul', parent).toggle();
});
});
</script>
</body>
</html>
see this JSFiddle for a working example;
https://jsfiddle.net/qum571nn/

Jquery load() get a variable from another page

On my main page I have a content box where I load the content using Jquery's load() from another page. All is working fine and it's quick and nice.
Next thing I want to do is to add a small filtering feature to it. The variable is sent to the main page (snappage.php) as a GET variable. However the php for the sql query is in another page (i.e all-snaps.php). Let me show you my code:
snappage.php
<?php
require "database/database.php";
session_start();
if($_GET['country']) {
$country = $_GET['country'];
}
?>
<section class="main-snap-page-wrapper">
<nav class="all-snaps-countries">
<h4>Filter by country</h4>
<ul>
<?php
//GET COUNTRY FLAGS
$flagsql = mysql_query("SELECT * FROM countries");
while($getflag = mysql_fetch_array($flagsql)) {
$countryname = $getflag['countryname'];
$flag = $getflag['countryflag']; ?>
<li>
<a href="snappage.php?country=<?php echo $countryname?>">
<img src="<?php echo $flag?>" alt="">
<h5><?php echo $countryname?></h5>
</a>
</li>
<?php } ?>
</ul>
</nav>
<div class="all-snaps-page">
<nav class="main-page-tabs-wrapper">
<ul class="main-page-tabs" id="<?php echo $country?>">
<li class="active-tab">All</li>
<li>Female</li>
<li>Male</li>
</ul>
<div class="main-snaps-content"></div>
</nav>
</div>
</section>
<script type="text/javascript">
$('.main-snaps-content').load('all-snaps.php');
$('.main-page-tabs li').on('click', function () {
$('.main-page-tabs li').removeClass('active-tab');
$(this).addClass('active-tab');
var page = $(this).find('a').attr('href');
$('.main-snaps-content').load(page + '.php');
return false;
});
</script>
Next is the page which I load into .main-snaps-content from i.e all-snaps.php:
all-snaps.php
<?php
require "database/database.php";
session_start();
if($_GET['country']) {
$country = $_GET['country'];
$newsql = mysql_query("SELECT * FROM users JOIN fashionsnaps ON users.id = fashionsnaps.userid WHERE country = '$country' ORDER BY snapid ASC");
}
else {
$newsql = mysql_query("SELECT * FROM fashionsnaps ORDER BY snapid ASC");
}
?>
<ul class="snaps-display">
<?php
//GET SNAPS BY ID
while ($getnew = mysql_fetch_array($newsql)) {
$newsnappics = $getnew['snappic'];
$newsnapid = $getnew['snapid'];
?>
<li>
<a href="snap.php?id=<?php echo $newsnapid?>">
<img src="<?php echo $newsnappics?>" alt="">
</a>
</li>
<?php } ?>
</ul>
So what I want to achieve here is to load the filtered content from all-snaps.php into the .main-snaps-content which is on snappage.php.
Where should I send this $country variable? On which page should I retrieve it?
You can do this pretty easily with jQuery load.
In snappage.php:
$(".main-snaps-content").load("all-snaps.php?" + $.param({country: "<?php echo htmlentities($country); ?>"}));
Update:
You'll need better handling of the PHP GET/$country var. You can initialize it at the top of snappage.php like this:
$country = (isset($_GET['country'])) ? $_GET['country'] : '';
Then, your JS will need a conditional:
var country = "<?php echo htmlentities($country); ?>";
if (country) {
$(".main-snaps-content").load("all-snaps.php?" + $.param({country: country}));
} else {
$(".main-snaps-content").load("all-snaps.php");
}

Weird behavior after using jQuery load function in IE 9

So i have this code that works in all my browsers but has a weird behavior in IE.
$(document).ready(function () {
//$.ajaxSettings.cache = false;
var refresh = setInterval(function () {
$('div#top_right').load('refresh.php?randval=' + Math.random() * 99999);
}, 5000);
$.ajaxSetup({
// Disable caching of AJAX responses
cache: false
});
});
This reloads my user panel div and checks if there is any new messages and such (and as you can see I tried modifying in for IE caching). This works well with all browsers, even IE, but in IE after the first reload it removes all the href attributes to the links (such as the messages link) in the user panel div. I have no clue why this is happening. Please help?
This is the code for refresh.php:
<?php
session_start();
include_once 'functions.php';
$user = $_SESSION['user'];
$new_message = FALSE;
$new_friend = FALSE;
$new_reply = FALSE;
$query = "SELECT status FROM messages WHERE recip='$user'";
$result = queryMysql($query, "divs");
while($row=mysql_fetch_assoc($result)){
if($row['status']=='new') $new_message=TRUE;
}
$query2 = "SELECT status from friends WHERE user='$user'";
$result2 = queryMysql($query2, "nezworld");
while($row2=mysql_fetch_assoc($result2)){
if($row2['status']=='pending') $new_friend=TRUE;
}
$query3 = "SELECT status from replies WHERE recip='$user'";
$result3 = queryMysql($query3, "divs");
while($row3=mysql_fetch_assoc($result3)){
if($row3['status']=='new') $new_reply = TRUE;
}
?>
<div id="top_right"><ul id="login2">
<li class="user_nav"><?php echo $user; ?></li>
<abbr title="Home"><a href="index.php" class='white'><li class='icons home'>N</li></a></abbr>
<abbr title="Messages"><a href="message.php?view=<?php echo $user; ?>" class='white'><?php if($new_message){?><li class='icons2 messages2'><?php }else{?><li class='icons2 messages'><?php }?>M</li></a></abbr>
<abbr title="Replies"><a href="replies.php?view=<?php echo $user; ?>" class='white'><?php if($new_reply){?><li class='icons2 replies4'><?php }else{?><li class='icons2 replies2'><?php }?>R</li></a></abbr>
<abbr title="Friend Requests"><a href="friends.php?view=<?php echo $user; ?>" class='white'><?php if($new_friend){?><li class='icons2 friends2'><?php }else{?><li class='icons2 friends'><?php }?>F</li></a></abbr>
<li><a class="submit" class='white' href="logout.php">LOGOUT</a>
</form>
</li>
</ul></div>

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