Ajax setInterval is executed twice for manipulated notification - javascript

First, Let's me explain. I have a page to monitoring my users. In this page, I can see all the request of my users on a table and I can see too the total of the request is in to the server. My question is, How can I make a notification when a new request is come. I want to make a notification like big window pop-up said "New Request Is Come" and one tone of music that will be play.
This is my code :
Main page
<!-- start: Header -->
<div class="container-fluid-full">
<div class="row-fluid">
<noscript>
<div class="alert alert-block span12">
<h4 class="alert-heading">Warning!</h4>
<p>You need to have JavaScript enabled to use this site.</p>
</div>
</noscript>
<!-- start: Content -->
<!--First indicator-->
<marquee>Belum Diterima: <span id="request_belum_terima"><?php
if ($request_belum_terima > 0) {
echo $request_belum_terima;
} else {
echo "0 ";
};
?></span> buah Request</marquee>
<div class="box-header">
<h2><i class="halflings-icon align-justify"></i><span class="break"></span>Penerimaan Request</h2>
<div class="box-icon">
<i class="halflings-icon chevron-up"></i>
</div>
</div>
<!--Table one-->
<div class="box-content" id="things_table">
<?php $this->load->view('view_monitoring_belum_terima'); ?>
</div>
<!--Second indicator-->
<marquee>Belum Selesai: <span><?php
if ($request_sudah_terima > 0) {
echo $request_sudah_terima;
} else {
echo '0 ';
}
?></span> Request</marquee>
<div class="box-header">
<h2><i class="halflings-icon align-justify"></i><span class="break"></span>Outstanding Request</h2>
<div class="box-icon">
<i class="halflings-icon chevron-up"></i>
</div>
</div>
<!--Table two-->
<div class="box-content" id="things_table2">
<?php $this->load->view('view_monitoring_belum_selesai'); ?>
</div>
</div><!--/.fluid-container-->
</div><!--/row-->
<?php $this->load->view('view_monitoring_modal') ?>
<div class="clearfix"></div>
<!-- start: JavaScript-->
<?php $this->load->view('/include/js.html'); ?>
<!-- end: JavaScript-->
<?php $this->load->view('view_monitoring_js'); ?>
I using codeigniter and some jquery to develop my app. So, I solve it one by one.
First, I use the indicator from first marquee. If you can see, there are one ID's jquery on span tag. For ex, First indicator have value 1. So, I use ajax to pool the data from database and check it with old value;
This is the code :
Controller
public function hitungRequestBelumTerima() {
$row = $this->model_request->hitungRequestBelumTerima();
echo json_encode($row);
}
Model
public function hitungRequestBelumTerima() {
$this->db->select('*');
$this->db->where('is_approved', 1);
$this->db->where('by_who is not null');
$this->db->where('it_person is null');
$query = $this->db->get('tbl_requestfix');
if ($query->num_rows() > 0) {
return $query->num_rows();
}
return NULL;
}
After that, I write a jquery's code to autorefresh the indicator like this :
function refresh() {
var ini;
var requestMasuk = $('#request_belum_terima').text();
setTimeout(function() {
$.ajax({
url: '<?php echo base_url() . 'control_closing/hitungRequestBelumTerima/' ?>',
type: 'POST',
dataType: 'json',
success: function(obj) {
if (obj > requestMasuk) {
ini = obj;
$('#request_belum_terima').text(obj);
alert("New request coming");
}
}
}).always(function() {
$('#request_belum_terima').text(ini);
}).done(function() {
$('#request_belum_terima').text(ini);
});
$('things_table2').fadeOut('slow').load('<?php ?>').fadeIn('slow');
refresh();
}, 20000);
}
$(document).ready(function() {
refresh();
}
It working to refresh, but I dont know, why alert is pop up twice. So, the case is : one new request but two alert of notif has pop-up on one interval. So, in first 10 minutes for ex, Alert is raising. In 20 minutes, alert still coming. But in 30 minute, the alert is not raise. Why the alert raise twice ?

use setInterval instead of setTimeout. Here is your ajax function (ajax not tested, as you say its working)
function refresh() {
var ini;
var requestMasuk = $('#request_belum_terima').text();
$.ajax({
url: '<?php echo base_url() . 'control_closing/hitungRequestBelumTerima/' ?>',
type: 'POST',
dataType: 'json',
success: function(obj) {
if (obj > requestMasuk) {
ini = obj;
$('#request_belum_terima').text(obj);
alert("New request coming");
}
}
}).always(function() {
$('#request_belum_terima').text(ini);
}).done(function() {
$('#request_belum_terima').text(ini);
});
$('things_table2').fadeOut('slow').load('<?php ?>').fadeIn('slow');
}
$(document).ready(function() {
setInterval(function () {
refresh();
}, 20000);
}

Related

How to pass a value form db to popup windows

I want to pass value to popup windows by using a tag with href when I click a
get values form db into hidden layer how to passing values by js.
A tag code
<a 'href=index.php?id=3'></a>
Hidden layer
<div class='wrap'>
<div class='content'>
<h2>Well Hello!</h2>
<p>
<? if ( isset($_GET['id'])){
$id = $_GET['id'];
echo $id ;} ?>
</p>
</div>
</div>
js code
$('a').on('click', function(){
$('.wrap, a').toggleClass('active');
return false;
});
If you want to do this the javascript way, see this example.
$(document).ready(function() {
$('a.toggle-wrap').on('click', function(e) {
e.preventDefault(); // prevent default behaviour of the link that would reload the page
$('.wrap, a.toggle-wrap').removeClass('active'); // remove class active on every link clicking
var target_id = $(this).attr("data-id"); //get the desired id from link
var wrap_element = $('.wrap[data-target=' + target_id + '] p');
var link_element = $('a[data-id=' + target_id + ']');
link_element.toggleClass('active');
$.ajax({
type: "GET",
url: "someOtherScriptThatOnlyOutputsResults.php",
data: "id="+target_id,
success: function(resultData) {
wrap_element.html(resultData).toggleClass('active'); // only toggle desired ids
}, error: function() {
wrap_element.html('Could not load data').toggleClass('active');
}
});
});
});
.wrap {
display: none;
}
.wrap.active {
display: block;
}
a {
color: green;
}
a.active {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="toggle-wrap" data-id="3">Link 3</a>
<a class="toggle-wrap" data-id="4">Link 4</a>
<div class="wrap" data-target="3">
<div class="content">
<h2>Well Hello content 3!</h2>
<p>Your db content related to id 3 from database, using php.
</p>
</div>
</div>
<div class="wrap" data-target="4">
<div class="content">
<h2>Well Hello content 4!</h2>
<p>Your db content related to id 4 from database, using php.
</p>
</div>
</div>
Add identifiers to the hidden wrap(s) and the link(s) and work with those. By using queries as seen in the js snippet, you can target certain HTML tags. Use CSS display to hide and show your wrap tag.
Create a new PHP file someOtherScriptThatOnlyOutputsResults.php to get and return data:
<?php
if(isset($_GET['id'])) {
$pdo = new PDO('mysql:host=someHost;dbname=someDatabase', 'someUser', 'somePass');
$statement = $pdo->prepare("SELECT columnWithContent FROM yourContentTable WHERE id = ?");
$statement->execute(array($_GET['id']));
$row = $statement->fetch();
$content = $row['columnWithContent'];
echo $content;
}
?>

Pop up Related Issue

There is a button in my webpage which calls another page through AJAX.The page carries certain data named "Match" if the query is successfully ran. Now I want that if a Match is recieved from the other page then a pop up comes. Here's my code
<div id="myNav" class="overlay">
×
<div class="overlay-content">
<h>ksadjaskjdaskdjaskdjaskdjaskdjaskdjasdk</h> </div>
</div>
<button class="abc" style="font-size:30px;cursor:pointer" >☰ Accept</button>
<script type="text/javascript">
var a="Match";
$(document).ready(function(){
$(".abc").click(function(){
$.ajax({
type: 'POST',
url: 'accept.php?w1=<?php echo $id ?>',
success: function(data) {
// $("p").text(data);
if(a=data)
{
function openNav()
{
document.getElementById("myNav").style.height = "100%";
}
}
else
{
location.reload();
}
}
});
});
});
function closeNav() {
document.getElementById("myNav").style.height = "0%";
}

PHP echo through Ajax doesn't give style?

Got blocked.
Created a php page with normal html, css, js and php.
Inside of that file, wanted for the user to be able to see events accordingly to the selected date.
In order to do that, once the date was selected, the value associated that date would get posted into a php script.
Inside of that php script, the posted variable was going through some conditions and echoing the results.
Then, the result of this php script, would be displayed in the initial php page.
Ok, so far so good.
Thing is,
Want the text to appear styled, which means, want it to allow styling classes.
Did some research but can't seem to find any problem like that.
When you go to the page and write, for example, the following in input: 12/22/2016, you can see data being displayed. Problem is, it doesn't come anywhere close to styled.
This makes sense, somehow, because the php script doesn't have mentioned anywhere to use those styles.
The styles are being used in the initial php page (html/css/js/php), where the results will be displayed.
Initially I thought the style in the results would be recognized because it is called in the exact same page where those style files are mentioned.
What am I doing wrong?
This it the result of the php script:
<h1 class="hero-header-otro">It works! dfgdfgdfg</h1>
As you can see, it has the class called inside of the h1
This is the javascript code that posts in the php script and displays the results in a specific div of the same page where this js code is, which is the php page mentioned all the way through this message:
jQuery(function($) {
$(".date").datepicker({
onSelect: function(dateText) {
display("Selected date: " + dateText + "; input's current value: " + this.value);
$(this).change();
}
}).on("change", function() {
display("Got change event from field");
$.ajax({
type: "POST",
url: 'events_script.php',
data: ({dates: this.value}),
success: function(data) {
$('.results-ajax').html(data);
alert(data);
}
});
});
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
The CSS:
.hero-content > h1.hero-header-otro {
font-size: 4rem;
margin-bottom: 20px;
font-weight: bold;
color: #ffffff;
}
Try using datatype html in ajax request:
$.ajax({
type: "POST",
url: 'events_script.php',
data: ({dates: this.value}),
dataType : 'html',
success: function(data) {
$('.results-ajax').html(data);
alert(data);
}
});
Got it fixed. This it the result of the php script:
<div class="tab-pane" role="tabpanel">
<div class="container day-events">
<div class="row event-list">
<div class="event-list-time col-md-3 col-sm-3 center" style="background-image: url(/lascruces_styles/img/events-img/event.jpg);">
<p class="event-list-start-time">2016-12-22 00:00:00</p>
<hr class="event-list-time-divider">
<p class="event-list-end-time">2016-12-22 00:00:00</p>
</div>
<div class="event-list-info col-md-9 col-sm-9">
<h2 class="event-list-name">dfgdfgdfg</h2>
<p>Organized by <span class="event-list-organizer">yyyyyyy</span></p>
<p class="event-list-description"><p>dffghfghgfhf</p></p>
<button type="button" class="btn more-info-list">More Information</button>
</div>
</div>
</div>
This is the javascript code that posts in the php script and displays the results in a specific div of the same page where this js code is, which is the php page mentioned all the way through this message:
jQuery(function($) {
$(".date").datepicker({
onSelect: function(dateText) {
display("Selected date: " + dateText + "; input's current value: " + this.value);
$(this).change();
}
}).on("change", function() {
display("Got change event from field");
$.ajax({
type: "POST",
url: 'events_script.php',
data: ({dates: this.value}),
dataType : 'html',
success: function(data) {
$('.results-ajax').html(data);
alert(data);
}
});
});
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
The PHP:
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<div class="tab-pane" role="tabpanel">
<div class="container day-events">
<div class="row event-list">
<div class="event-list-time col-md-3 col-sm-3 center" style="background-image: url(/lascruces_styles/img/events-img/event.jpg);">
<p class="event-list-start-time">'.$row['Start_Date'].'</p>
<hr class="event-list-time-divider">
<p class="event-list-end-time">'.$row['End_Date'].'</p>
</div>
<div class="event-list-info col-md-9 col-sm-9">
<h2 class="event-list-name">'.$row['Event_Name'].'</h2>
<p>Organized by <span class="event-list-organizer">'.$row['Company_Name'].'</span></p>
<p class="event-list-description">'.$row['Event_Description'].'</p>
<button type="button" class="btn more-info-list">More Information</button>
</div>
</div>
</div>
</div>';
}} else { echo 'No results found.'; }

Laravel 5 Paginate + Infinite Scroll jQuery

I am trying to use paginate() to achieve infinite scroll. I think the easiest way is using the 'infinite-scroll' to achieve this. If you have any other suggestion how to do it without infinite-scroll library, just using jQuery, I'd be happy to know..
I am returning the variable to view like this:
public function index()
{
$posts = Post::with('status' == 'verified')
->paginate(30);
return view ('show')->with(compact('posts'));
}
My View:
<div id="content" class="col-md-10">
#foreach (array_chunk($posts->all(), 3) as $row)
<div class="post row">
#foreach($row as $post)
<div class="item col-md-4">
<!-- SHOW POST -->
</div>
#endforeach
</div>
#endforeach
{!! $posts->render() !!}
</div>
Javascript Part:
$(document).ready(function() {
(function() {
var loading_options = {
finishedMsg: "<div class='end-msg'>End of content!</div>",
msgText: "<div class='center'>Loading news items...</div>",
img: "/assets/img/ajax-loader.gif"
};
$('#content').infinitescroll({
loading: loading_options,
navSelector: "ul.pagination",
nextSelector: "ul.pagination li:last a", // is this where it's failing?
itemSelector: "#content div.item"
});
});
});
However, this doesn't work. The ->render() part is working because I am getting [<[1]2]3]>] part. However, the infinite scroll doesn't work. I also don't get any errors in the console.
[<[1]2]3]>] is like this in the view:source:
<ul class="pagination">
<li class="disabled"><span>«</span> </li> // «
<li class="active"><span>1</span></li> // 1
<li>2</li> // 2
<li>3</li> // 3
<li>»</li> // »
</ul>
Easy and helpful is this tutorial - http://laraget.com/blog/implementing-infinite-scroll-pagination-using-laravel-and-jscroll
Final script could looks like this one
{!! HTML::script('assets/js/jscroll.js') !!}
<script>
$('.link-pagination').hide();
$(function () {
$('.infinite-scroll').jscroll({
autoTrigger: true,
loadingHtml: '<img class="center-block" src="/imgs/icons/loading.gif" alt="Loading..." />', // MAKE SURE THAT YOU PUT THE CORRECT IMG PATH
padding: 0,
nextSelector: '.pagination li.active + li a',
contentSelector: 'div.infinite-scroll',
callback: function() {
$('.link-pagination').remove();
}
});
});
</script>
You just need to use laravel's pagination
{!! $restaurants->links() !!}
You should be able to use the Pagination just fine as long as your call to get new posts is different than page load. So you'd have two Laravel calls:
1.) To provide the template of the page (including jQuery, CSS, and your max_page count variable -- view HTML)
2.) For the AJAX to call posts based on the page you give it.
This is how I got my infinity scroll to work...
HTML:
<!-- Your code hasn't changed-->
<div id="content" class="col-md-10">
#foreach (array_chunk($posts->all(), 3) as $row)
<div class="post row">
#foreach($row as $post)
<div class="item col-md-4">
<!-- SHOW POST -->
</div>
#endforeach
</div>
#endforeach
{!! $posts->render() !!}
</div>
<!-- Holds your page information!! -->
<input type="hidden" id="page" value="1" />
<input type="hidden" id="max_page" value="<?php echo $max_page ?>" />
<!-- Your End of page message. Hidden by default -->
<div id="end_of_page" class="center">
<hr/>
<span>You've reached the end of the feed.</span>
</div>
On page load, you will fill in the max_page variable (so do something like this: ceil(Post::with('status' == 'verified')->count() / 30);.
Next, your jQuery:
var outerPane = $('#content'),
didScroll = false;
$(window).scroll(function() { //watches scroll of the window
didScroll = true;
});
//Sets an interval so your window.scroll event doesn't fire constantly. This waits for the user to stop scrolling for not even a second and then fires the pageCountUpdate function (and then the getPost function)
setInterval(function() {
if (didScroll){
didScroll = false;
if(($(document).height()-$(window).height())-$(window).scrollTop() < 10){
pageCountUpdate();
}
}
}, 250);
//This function runs when user scrolls. It will call the new posts if the max_page isn't met and will fade in/fade out the end of page message
function pageCountUpdate(){
var page = parseInt($('#page').val());
var max_page = parseInt($('#max_page').val());
if(page < max_page){
$('#page').val(page+1);
getPosts();
$('#end_of_page').hide();
} else {
$('#end_of_page').fadeIn();
}
}
//Ajax call to get your new posts
function getPosts(){
$.ajax({
type: "POST",
url: "/load", // whatever your URL is
data: { page: page },
beforeSend: function(){ //This is your loading message ADD AN ID
$('#content').append("<div id='loading' class='center'>Loading news items...</div>");
},
complete: function(){ //remove the loading message
$('#loading').remove
},
success: function(html) { // success! YAY!! Add HTML to content container
$('#content').append(html);
}
});
} //end of getPosts function
There ya go! That's all. I was using Masonry with this code also so the animation worked wonderfully.

Ajax WordPress post popup with SimpleModal and jQuery

I tried to implement this mode here http://wordpressthemescollection.com/ajax-wordpress-post-popup-with-simplemodal-and-jquery-488.html but nothing seems to work.
This is what I do.
1 / Include in header
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="<?php bloginfo("template_url"); ?>/js/jquery.simplemodal.js"></script>`
The links are goods cause I checked them both.
2 / Include in header this script
<script>
jQuery(document).ready(function() {
jQuery('a.postpopup').live('click', function(){
var id = jQuery(this).attr('rel');
jQuery('<div id="ajax-popup"></div>').hide().appendTo('body').load('<?php bloginfo('url')?>/ajax/?id='+id).modal({
opacity:90,
position: ["0%"],
overlayClose:true
});
return false;
});
});
</script>
3 / Make a custom template with this code
<?php
/*
Template Name: Ajax
*/
?>
<?php
$post = get_post($_GET['id']);
?>
<?php if ($post) : ?>
<?php setup_postdata($post); ?>
<div class="whatever">
<h2 class="entry-title"><?php the_title() ?></h2>
<div class="entry-content">
<?php the_content(); ?>
</div>
</div>
<?php endif; ?>
And after that made a page named Ajax and assign the template Ajax.
4 / Implement a link
this link
If i click on the link nothing happens.
What did I do wrong cause I did not have a clue about it?
Thanks.
jQuery .load() is ajax and so you need to do any subsequent things in a callback like this:
var $ajax-div = jQuery('<div id="ajax-popup"></div>').hide().appendTo('body');
var url = '<?php bloginfo('url')?>/ajax/?id=' + id;
$ajax-div.load(url), function() {
// the callback
jQuery('#ajax-popup').modal({
opacity: 90,
position: ["0%"],
overlayClose:true
});
});
when you create an new post or page content on wordpress admin, select the "Ajax" template for your page

Categories

Resources