Showing Multiple Noty Notifications With a Delay - php

I'm using noty to display notifications using the 'top right' alerts setting. I'm really new to jquery but know php and mysql enough to get most things i want done.
What i want to do is use mySQL to get the data to see if a user needs to be shown any notifications (done). Then show that notification on page load, which I've also done, although I'm sure there's a more elegant way to show multiple notifications other than repeating the code?
Then i want to put a delay of say 1 second for each notification to appear so they don't all pop up at once, and disappear at the same time. I've looked into .delay() but without knowing jQuery a little better it's pretty useless to me.
My code:
$(document).ready(function() {
var noty_id = noty({"text":"a message","layout":"topRight","type":"inormation","animateOpen":{"height":"toggle"},"animateClose":{"height":"toggle"},"speed":1000,"timeout":5000,"closeButton":false,"closeOnSelfClick":true,"closeOnSelfOver":false,"modal":false});
var noty_id = noty({"text":"a message","layout":"topRight","type":"inormation","animateOpen":{"height":"toggle"},"animateClose":{"height":"toggle"},"speed":1000,"timeout":5000,"closeButton":false,"closeOnSelfClick":true,"closeOnSelfOver":false,"modal":false});
});

You could just use the setTimeout() native Javascript function. This will queue up an action after a given timeout period (milliseconds).
$(document).ready(function() {
var noty_id = noty({"text":"a message","layout":"topRight","type":"inormation","animateOpen":{"height":"toggle"},"animateClose":{"height":"toggle"},"speed":1000,"timeout":5000,"closeButton":false,"closeOnSelfClick":true,"closeOnSelfOver":false,"modal":false});
setTimeout(function() { var noty_id = noty({"text":"a message","layout":"topRight","type":"inormation","animateOpen":{"height":"toggle"},"animateClose":{"height":"toggle"},"speed":1000,"timeout":5000,"closeButton":false,"closeOnSelfClick":true,"closeOnSelfOver":false,"modal":false}); }, 5000)
});
You may find jQuery Pines a better notification system for queuing up multiple notifications.

Related

How to display a 'live' count of total files uploaded?

I am looking to display the total number of files in a database. To clarify, say I had a website where people could upload pictures of their cars, and I wanted to display a live number of how many pictures there are, what would be the best way to do this? Javascript, php? A mix? I envision a div with a number saying "Total Pictures: x" and where x would be whatever the live total is. I plan on using MySQL to store all the data on the website. Is this even recommended to have something communicate with the server this much? Is there a name for displaying a live number? Thanks!
If you are thinking to use the AngularJS way, you could create a Poller service which polls every second (assuming your /counter.php returns json):
app.factory('Poller', function($http, $timeout) {
var data = { response: {}};
var poller = function() {
$http.get('/counter.php').then(function(r) {
data.response = r.data;
$timeout(poller, 1000);
});
};
poller();
return {
data: data
};
});
Then your controller:
app.controller('CounterCtrl', function(Poller, $scope){
$scope.counter = Poller.data;
});
And finally in your view:
{{counter.response}}
You can read more about $http
Set up a PHP script that queries the database and returns the total file upload count. After that, you can use JavaScript on the page to periodically call the server in a specified interval of time and fetch the count data from your PHP script. Using jQuery and GET, you can do something like this:
jQuery(function($){
setInterval(function(){
$.get( '/counter.php', function(fileUploadCount){
$('#counter').html( fileUploadCount );
});
},20000); // 20 seconds
});
In your HTML:
<p><span id='counter'>xx</span> files have been uploaded so far!</p>
Hope this helps!
How live do you want it to be? Just whenever someone updates the site it's going to have the new value or do you actually want it to update in near real-time?
If it's the latter you have to use Javascript against some kind of API that returns the amount of files in the database. I can't help you with that bit since you are using PHP, but it shouldn't be too hard. Just return some JSON looking something like
{ fileCount: 45020 }
Client-side you have a few options. You have the different javascript frameworks like AngularJS and EmberJS (and many more), as well as just 'plain old' javascript and frameworks like jQuery
The keyword is really AJAX, even if that is just a sort of buzzword for using javascript to make websites dynamic.
I am a fan of using AngularJS because it's easy, but I'll try to give you some pointers for using jQuery first. Note that I have not used jQuery in years now.
The jQuery way
jQuery has a function called jQuery.getJSON(), and according to the documentation you can use that function something like this:
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON( "http://example.com/api/fileCount.json")
.done(function(data) { console.log(data) })
.fail(function() { console.log( "error" ); })
.always(function() { console.log( "complete" ); });
So this means we can call an endpoint and fetch some data using jQuery.
Here is a link to a tutorial about the basics of jQuery by the way.
jQuery makes us able to do things like this:
<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>
When that is executed the div with id "divTest1" will contain the text 'Hello, world!'.
That sounds like something we could use here!
Javascript also has this really nice function called setTimeout(), which allows us to make it call a function later.
This describes how to use jQuery with setTimeout()
As you can see it also shows us jQuery.documentReady(), which is an event that fires when the website is finished loading, so it is a good place to put code we want executed.
The example below shows how to use jQuery to hide a div with id=div after 3 seconds.
jQuery(document).ready(function () {
setTimeout( "jQuery('#div').hide();",3000 ); //hide a div after 3 seconds
});
Combining these things you should be able to make a repeating call that fetches data from your server and then updates a div or another element with the data you have fetched.
Just create a function which uses jQuery.getJSON() to fetch data, and then at the bottom of that add a setTimeout call to run itself in X seconds (however often you want it to update).
In jQuery.documentReady() you call that function the first time the document loads.
And in the .done() bit of the getJSON() call you add the data you got from the server to your div with whatever html you want. I showed you how to use $("#divTest1").text(), but there is also a .html() which acts the same but you should use it to add html to a element.
The angular way would be to use AngularJS's $http to do the same thing, but I wouldn't recommend learning AngularJS until you have a bit of a better grasp on Javascript.
When you do though, I highly recommend it. It's a much better approach than using jQuery.
You can read about AngularJS here
I hope this helps!

Google Docs style Autosave using TinyMCE

I have a form using the TinyMCE Editor running on a LAMP system. I wish to create an autosave feature similar to Google Docs. I have thought of two scenarios however, both will produce an overhead on the server.
Post an Ajax request on keyup
Post an Ajax request every 60s
Obviously the first point is not feasible. Can anyone suggest a better solution to point two?
Edit 1
Ok, so a third option could be a combination of Thariama's answer and my second point.
3) Post an Ajax request every 60s if there is signifcant change eg 10 chars or more
Any advances on this would be much appreciated.
Edit 2
Ok I have prototyped my solution based on point 3. In case anyone is interested my code flows like this:
I am using JQuery. I have a form with a textarea with TinyMCE attached to it and a hidden field to store a count of keystrokes.
tinyMCE.init({
...
// Callback for counting keystrokes in TinyMCE
handle_event_callback : "keyCount"
});
$(function() {
autoSaveContent();
});
// Callback function - Get count, increment it and then set it
function keyCount(e) {
if(e.type == "keypress") {
var count = parseInt($("#keyCount").val());
count++;
$("#keyCount").val(count);
}
}
// Autosave every 10s if there have been over 30 keystrokes
function autoSaveContent() {
var keyCount = parseInt($("#keyCount").val());
if(keyCount > 30) {
tinyMCE.triggerSave();
var formData = $("#programmedItineraryForm").serialize();
$.post("/path/to/save.php", formData, function(data,textStatus) {
if(data.success) {
$("#keyCount").val(0);
}
});
}
setTimeout('autoSaveContent()',10000);
}
Hmm, there are many options.
Point 1 is indeed a bit too expensive.
I think it would be a good idea to send a request based on the number of new characters entered in the editor. For example send a request every 5-10 new characters.
You can increment a counter onKeyDown or onKeyUp and reset that counter when a request gets send.
tinymce.init({
plugins: "autosave"
});

Auto Update Stats From SQL Database

I'm trying to get an effect like the http://www.minecraft.net page where it auto updates sales from a database, I've been researching this for two months now and no luck.
I have a php file which finds how many results are in a database and displays them as a number, works fine http://tzeale.com/sandbox/stats/pull.php
What I'm trying to do is get the effect like minecraft.net where it auto updates without refreshing the page. Could anyone guide me on what to do? I don't know what else to try.
Thanks.
hYou need to use AJAX.
setTimeout, alongside a AJAX call to that pull.php
If you are using jQuery, here is a good example on how to achieve what you want.
Added a simple logic to see if the server is dead, and eventually stop.
var failed = 0;
var limit_failed = 5;
(function updateSales( waitTime ){
waitTime = waitTime || 1000; // Set to 1 second by default
setTimeout(function(){
$.ajax({
url: 'pull.php',
success: function( response ){
// Update something with your response
alert ("sales are now at: "+ response);
updateSales(); // Recursion
},
error: function(){
// Error handling - not necessary
// If the request failed more then (limit_failed) times, you might want to stop it from checking after (limit_failed) times,
// and in the meanwhile icnrease the wait time, so the server has more time to get back online.
if( ++failed < limit_failed ){
waitTime += 1000;
updateSales( waitTime );
}
}
});
}, waitTime);
})();
You would use setTimeout and Ajax. setTimeout would get the data every 1000 ms (or however you set it) using Ajax to get the data.
You would wrap your display count in your html like this for example:
<span id="mycount"></span>
Then your jQuery code would look something like this:
setTimeout(function(){
$.get("/sandbox/stats/pull.php",function(data){
$("#mycount").html(data);
});
},1000);
1000 is one second, you can change it if you'd like. I don't know how to make it animate like that, but it would go inside your $.get() function once you retreive the data. Also this must be on the same domain as http://tzeale.com/ for the Ajax to work due to same origin policy
HOWEVER, After reviewing te minecraft.net site, I noticed they are loading this data into their page one time, instead of getting it every 1 second:
<script>
var justLoggedIn = false;
var totalUsers = 33652552;
var paidUsers = 6495707;
var totalUsersRate = 1.2166667;
var paidUsersRate = 0.15;
</script>
Then they are not getting live data with this. They are just getting the current amount, then keep adding 1 to it.
They make it animate using this plugin: http://timeago.yarp.com/
And still using setTimeout() to keep adding 1 to it every second. I don't think this is real users, just a counter starting at the var totalUsers

How do I make jQuery notify like Twitter search?

I don't know what it's call. Example
http://search.twitter.com/search?q=%23idontbelieveyou
When you click link above wait a few seconds. Then you will see a notify like this
102 more results since you started searching. Refresh to see them.
There any tutorial for this? Let me know how to make something like that
It's really simple, logically:
A piece of Javascript checks back with the server every n seconds with a timestamp of the latest result it has.
The server checks if any results are available newer than this timestamp and reports back how many there are.
The Javascript displays this notification in the browser.
It would just sent an XHR to the server to see if any more tweets match the query.
If there are new matches, it will return the count and JavaScript updates the DOM to suit.
It is simply polling a script via jquery or Ajax (same thing really)
// Untested, written here without syntax.
var timeSinceUpdate = <?php echo(time()); ?>;
$(document).ready(function(){
setInterval(function(){
$.get('queriesSince.php?searched=idontbelieveyou&timesinceupdate=' + timeSinceUpdate , function(data){
alert(data);
if(confirm('Add new Data to screen?'))
{
//Add Stuff to DOM and update the timeSinceUpdate from the data recieved.
}
});
}, 3000);
});

Use AJAX to check for a new message

Quite simply, I need to alert the end user when they have a new private message.
From a combination of research and other opinion, I realise I need to use AJAX for this.
The mysql query would be
SELECT id FROM tbl_messages WHERE to_viewed = 1
So when someone sends a message, I want an alert to popup on the screen to inform the user without a page reload.
I have absolutely no idea what I am doing, but know what I want.
Really need help with this, AJAX is definitely something I want to improve as it opens up greater possibilities!
Thanks
Using jQuery for brevity, if you don't have any JavaScript experience I recommend learning.
var check;
function checkForMessages() {
$.get("/newMessages.php", function(data) {
if(data == 1) {
//There are new messages
clearInterval(check);
alert("You have new mail!");
}
});
}
check = setInterval(checkForMessages, 60000);
The above JavaScript will ping the server every 60 seconds. The script "newMessages.php" should return '1' if there are new messages. You have the query already written so I think you can figure it out.
You have two options on the client side:
Polling via Ajax: Every X seconds, send a request to the server to check for messages.
Server-push via Comet: Open a connection to the server and wait for the server to respond with the message.
There are numerous client side libraries available. For Ajax, you can use JQuery. For Comet, look into Dojo, but your server/platform must support Comet. I know it's possible with Java using Jetty, but I'm not sure about other platforms.

Categories