I have jQuery jGrowl loaded into my theme and I am able to display a notification like this:
jQuery.jGrowl('This is a notification', { life: 10000});
However, I have a function that reloads every 30 seconds and i've put the jGrow notification into it like this:
setInterval(function() {
jQuery.jGrowl('This is a notification', { life: 10000});
}, 30000);
I want the notifications dynamic based on what information a php file sends back. The php file basically returns back a list of new messages and I want jGrowl to display a notification for each one of these new messages. Not sure what the best way to get the php file to output the data so that jGrowl can understand it and how this can be done.
Any suggestions would be great.
Thanks
You need to use something like jQuery's $.ajax() method to poll an endpoint with your data. I suggest returning it in JSON, and then you loop over it and pass that as a message to the $.jGrowl method.
You can try something like the following example:
index.html
<!doctype>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-jgrowl/1.4.3/jquery.jgrowl.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-jgrowl/1.4.3/jquery.jgrowl.min.js"></script>
<script>
$(function(){
$('form').submit(function(e){
e.preventDefault();
$.ajax({
type: 'get',
url: $('form').attr('action'),
data: $('form').serialize(),
success: function() {
$('input[type=text]').val('');
}
});
});
setInterval(function(){
$.ajax({
dataType: 'json',
url: 'messages.php',
success: function(messages) {
$.each(messages, function(message){
$.jGrowl('This is a notification', { life: 10000});
});
}
});
}, 5000);
});
</script>
<body>
<form method="get" action="addMessage.php">
<input type="text" name="message" placeholder="New message" />
<input type="submit"/>
</form>
</body>
</html>
addMessage.php
<?php
session_start();
if (!isset($_SESSION['messages'])) {
$_SESSION['messages'] = array();
}
if (isset($_GET['message']) && !empty($_GET['message'])) {
$_SESSION['messages'][] = strip_tags($_GET['message']);
}
print json_encode($_SESSION['messages']);
messages.php
<?php
session_start();
if (!isset($_SESSION['messages'])) {
$_SESSION['messages'] = array();
}
print json_encode($_SESSION['messages']);
I don't recommend using this in production, you'll want to do a better job of controlling and sanitizing your messages, but this should give you a general idea of how to poll for messages and pass them to jGrowl.