Using jQuery Growl with PHP and MySQL - php

On my database I am planning to create a table storing messages to alert users of anything they need to do.
I am looking at using a jQuery growl like notification method but I'm confused at how I would begin building it.
The data would be added into the database using the standard MySQL insert method from a form but how would I select messages from the database to display using the jQuery growl.
Would this require the use of AJAX?
This is the JavaScript code I have so far, i was wondering how I would implement the PHP code alongside it so that I can pull out data from my tables to display as notifications:
<script type="text/javascript">
// In case you don't have firebug...
if (!window.console || !console.firebug) {
var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
window.console = {};
for (var i = 0; i < names.length; ++i) window.console[names[i]] = function() {};
}
(function($){
$(document).ready(function(){
// This specifies how many messages can be pooled out at any given time.
// If there are more notifications raised then the pool, the others are
// placed into queue and rendered after the other have disapeared.
$.jGrowl.defaults.pool = 5;
var i = 1;
var y = 1;
setInterval( function() {
if ( i < 3 ) {
$.jGrowl("Message " + i, {
sticky: true,
log: function() {
console.log("Creating message " + i + "...");
},
beforeOpen: function() {
console.log("Rendering message " + y + "...");
y++;
}
});
}
i++;
} , 1000 );
});
})(jQuery);
</script>
<p>
</span>
<p>

PHP is running on the server and JavaScript is running on the client.
So Yeah, you'll need AJAX.
Well, there would be other ways, but they are more work than simply setting up AJAX. Especially so since you work with jQuery which handles most of the AJAX stuff for you.
Let it call a small PHP script that fetches the Rows from the DB, outputs them in your preferred Way (XML or JSON) and exits.
The usual jQuery AJAX tutorials should cover exactly that.
If your App is Multi-User don't forget to send a UserID in the Request so PHP knows what Rows to pull.

Related

Retrieve data from PHP file by ajax

I found a script on the net, which makes two PHP files interact.
Specifically, the first file (details.php) shows some statistical data of a football match. If the match is in progress, I show the live score by running another PHP file (live_score.php). The two files interact thanks to the following script, present in the details.php file
$(document).ready(function(){
setInterval(function() {
var id=<?php echo"$id"?>;
var x = "<?php echo"$cod"?>";
$("#risultato").load("live_score.php", {var:id, x});
refresh();
}, 5000);
});
from details.php, I call live_score.php passing it some parameters.
These parameters are used by the live_score.php file to retrieve the score and other information in real time.
To print the result on the screen in details.php, I use a simple ECHO inside the live_score.php file, but I would like to retrieve this data and the others in a different way, via ajax if possible, but I don't know if it can be done and how....can you help me please? Thank you
I think you have already solved half of your problem. From your code , you should first remove the "refresh()" to stop reloading the page every 5 seconds.
then make sure that the the payload is correct, because the word "var" is a reserved keyword in JavaScript.
HTML
<div id="risultato"></div>
Javascript
$.ajax({
url: "live_score.php",
type: "POST",
data: { id, x},
success: function(response) {
//this response will be the data from "live_score.php"
//now assuming that
// 1. you use vanilla javascript with plain html + css
// 2. the returning reponse looks like this
// [{"teamName": "theTeam1", "score": 10}, {"teamName": "theTeam2", "score": 10}]
//Clear the current score
$("#risultato").empty();
// Now iterate through the response,
$.each(response, function(index, item) {
var teamName = item.teamName;
var score = item.score;
var html = "<p><strong>" + teamName + "</strong>: " + score + "</p>";
// this code will append (add to the end) the data iterated
$("#risultato").append(html);
});
},
error: function(xhr, status, error) {
//if your code or ajax call had any problems ,
//you can debug here and write error handling logic here, like
if(error){
alert("failed to fetch data");
console.log(error);
}
}
});

Run Php script constantly and if connected to internet as windows service which inserts data into xampp server

I am developing a desktop app which will store data offline but whenever the desktop gets a connection a php script should detect it (cron job) and upload it to the online server like this:
while(true){
if(connected == true){
// run code;
else{
// wait to get connection
}
}
Hi Zaki Muhammad Mulla,
I did some testing myself, and I came up with the following piece of code
Running the code snippets here won't work because this is a sandbox and there is no access to the localstorage here.
Make sure to include Jquery in your code
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous">
</script>
Then the actual function that will do the trick:
function processData(online){
if(online == true){
//My connection is online so I can execute code here
//If data is stored locally, read it and post it with an $.ajax POST
//I can loop through all the data and insert it per found row of data
for(var i=0, len=localStorage.length; i<len; i++) {
var key = localStorage.key(i);
var value = localStorage[key];
$.ajax({
type: 'POST',
url: 'PATH/TO/SCRIPT.php',
data: { column: key, value: value },
success: function(response) {
//The insert was succesful
content.html(response);
}
});
}
}else{
//Create your own loop here and fill data accordingly
for(i = 0; i < 12; i++){
localStorage.setItem("lastname" + i, "Smith");
localStorage.setItem("firstname" + i, "John");
localStorage.setItem("age" + i, "22");
localStorage.setItem("job" + i, "Developer");
}
}
}
And at last the window.setInterval() to run a function every x seconds (Keep in mind 1 second = 1000 in the settimeout)
<script>
window.setInterval(function(){
var online = navigator.onLine;
processData(online);
}, 1000);
</script>
Hope this may help you on your quest!
The sources I used:
https://medium.com/#Carmichaelize/checking-for-an-online-connection-with-javascript-5de1fdeac336
Ajax passing data to php script
https://www.w3schools.com/html/html5_webstorage.asp
https://www.taniarascia.com/how-to-use-local-storage-with-javascript/
Get HTML5 localStorage keys
HTML5 localStorage getting key from value
What's the easiest way to call a function every 5 seconds in jQuery?

jquery .load function running more than once

I'm trying to implement SEO friendly infinite scrolling in accordance with google's recommendations as seen here (http://scrollsample.appspot.com/items?page=7). I have a jquery function that sends a request to a php file, (which requests the data from the db) anytime someone scrolls to the bottom of the page, now everything is working fine except that when the user scrolls to the bottom of the page, the request function gets fired more than once. So duplicate entries of the data gets loaded into the page, now i know this isn't from my php file because i opened the page directly in my browser and everything was fine. Checkout the bug here http://devx.dx.am/haze/categor.php?artemis=foo&&page=1
I have already tried the solutions here (jQuery .load() callback function fires multiple times) and here ($(window).load() is executing 2 times?) and a few others as well.
$(window).bind('scroll', function() { //#cagorwrap is the div that should contain the data retrieved
if($(window).scrollTop() >= $('#cagorwrap').offset().top + $('#cagorwrap').outerHeight() - window.innerHeight) { //344.6
var queryParameters = {}, queryString = location.search.substring(1),
re = /([^&=]+)=([^&]*)/g, m;
while (m = re.exec(queryString)) {
queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
var url2 = "modules/paginate.php?numpages=set";
// #rc is a hidden div too
$("#rc").load(url2, function() {
var rc = $(this).html();
if (queryParameters['page'] < rc) {
queryParameters['page']++;
console.log(rc);
var stateObj = queryParameters['page'];
let cagh = $('#cagorwrap').height() + 344.6 - 75;
$("#cagorwrap").height(cagh);
history.pushState(null, null, "categor.php?artemis=cat&&page="+stateObj);
var url = "modules/paginate.php?artemis=cats&&page="+stateObj;
$("#obtainer").load(url, function () {
$("#cagorwrap").append($(this).html());
}); //#obtainer is a hidden div that receives the data at first before it is appended to #cagorwrap
} else{
//unbind scroll here
}
});
}
});
well if all else fails and you absolutely need a solution, you can add a
counter=1; on the start
and only fire the request function in the case below
counter++;
if (counter%2==0){//fire request}
It's not clean, but if you're loosing too much time with this and want to return to the problem later on...

simple chat using jQuery and PHP

I'm not so good at English but I will give it a try, feel free to edit and improve my post!
I'm trying to create a little chat, now I do not want to reload when there's no new data. It will receive the data from update.php, this works correctly.
I'm trying to do a little check (sample to show what I want to accomplish):
This is standard:
var ok = update.php
load ok(4000s);
What I am trying to accomplish here is:
var ok = update.php
function timer{
var new = update.php
if(new != ok){
ok = new;
},4000};
Of course this is fake code, it would never run, but it's the easiest way to explain what I mean.
$(document).ready(function() {
$("#chatbox").html('').load("update.php");
var refreshId = setInterval(function() {
var xx = $("#chatbox").html('').load("update.php");
$('#holder').load('update.php');
if( xx != "#holder"){
$("#chatbox").html('').load('update.php');
// $("#chatbox").html('').load('update.php')
$("#chatbox").scrollTop($("#chatbox")[0].scrollHeight);
}else{
alert)('nooope');
}
}, 4000);
$.ajaxSetup({ cache: false });
});
I tried everything, still getting nope.
(chatbox is a div, where de data gets loaded into.)
(holder is the same concept, only this one is hided trough css, so that the user won't notice.)

Refresh div, but only if there is new content from php file

Background Info
I'm fiddling around with some PHP and AJAX at the moment, to try and get the code working for an auto refreshing div (every 10 seconds), that contains comments.
Here is javascript code I am using to refresh the div..
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#content_main').load('/feed_main.php');
}, 5000);
});
// ]]></script>
The code that will populate the div called "content_main", which is in feed_main.php, essentially accesses the database and echo's out the latest comments ...
Question
Is it possible, to only load the div "content_main" if the data inside of it, hasn't changed since the last time it was loaded?
My logic
Because I'm relatively new to javascript and AJAX I don't quite know how to do this, but my logic is:
For the first time it is run..
load data from feed_main.php file
Create a unique value (perhaps a hash value? ) to identify say 3 unique comments
Every other time it is run...
load the data from feed_main.php file
create a NEW unique value
check this value with the previous one
if they're the same, don't refresh the div, just leave things as they are, but if they're different then refresh..
The reason why I want to do this is because the comments usually have pictures attached, and it is quite annoying to see the image reload every time.
Any help with this would be greatly appreciated.
I've faced similar problem not too long ago, i assume that you using mysql or something for your comments storage serverside ?
I solved my problem by first adding timestamp integer column to my mysql table, then when i added a new row, i'd just simply use time() to save the current time.
mysql row insert example:
$query = "INSERT INTO comments (name, text, timestamp) VALUES ('". $name ."', '". $text ."',". time() .");";
step two would be to json_encode the data you sending from serverside:
$output = array();
if ($html && $html !== '') { // do we have any script output ?
$output['payload'] = $html; // your current script output would go in this variable
}
$output['time'] = time(); // so we know when did we last check for payload update
$json = json_encode($output, ((int)JSON_NUMERIC_CHECK)); // jsonify the array
echo $json; // send it to the client
So, now instead of pure html, your serverside script returns something like this:
{
"payload":"<div class=\"name\">Derpin<\/div><div class=\"msg\">Foo Bar!<\/div>",
"time":1354167493
}
You can grab the data in javascript simply enough:
<script type="text/javascript"> // <![CDATA[
var lastcheck;
var content_main = $('#content_main');
pollTimer = setInterval(function() {
updateJson();
}, 10000);
function updateJson() {
var request = '/feed_main.php?timestamp='+ (lastcheck ? lastcheck : 0);
$.ajax({
url: request,
dataType: 'json',
async: false,
cache: false,
success: function(result) {
if (result.payload) { // new data
lastcheck = result.time; // update stored timestamp
content_main.html(result.payload + content_main.html()); // update html element
} else { // no new data, update only timestamp
lastcheck = result.time;
}
}
});
}
// ]]> </script>
that pretty much takes care of communication between server and client, now you just query your database something like this:
$timestamp = 0;
$where = '';
if (isset($_GET['timestamp'])) {
$timestamp = your_arg_sanitizer($_GET['timestamp']);
}
if ($timestamp) {
$where = ' WHERE timestamp >= '.$timestamp;
}
$query = 'SELECT * FROM comments'. $where .' ORDER BY timestamp DESC;';
The timestamps get passed back and forth, client always sending the timestamp returned by the server in previous query.
Your server only sends comments that were submitted since you checked last time, and you can prepend them to the end of the html like i did. (warning: i have not added any kind of sanity control to that, your comments could get extremely long)
Since you poll for new data every 10 seconds you might want to consider sending pure data across the ajax call to save substantial chunk bandwidth (json string with just timestamp in it, is only around 20 bytes).
You can then use javascript to generate the html, it also has the advantage of offloading lot of the work from your server to the client :). You will also get much finer control over how many comments you want to display at once.
I've made some fairly large assumptions, you will have to modify the code to suit your needs. If you use my code, and your cat|computer|house happens to explode, you get to keep all the pieces :)
How about this:
<script type="text/javascript">
// <![CDATA[
$(function () {
function reload (elem, interval) {
var $elem = $(elem);
// grab the original html
var $original = $elem.html();
$.ajax({
cache : false,
url : '/feed_main.php',
type : 'get',
success : function (data) {
// compare the result to the original
if ($original == data) {
// just start the timer if the data is the same
setTimeout(function () {
reload(elem, interval)
}, interval);
return;
}
// or update the html with new data
$elem.html(data);
// and start the timer
setTimeout(function () {
reload(elem, interval)
}, interval);
}
});
}
// call it the first time
reload('#content_main', 10000);
});
// ]]>
</script>
This is just an idea to get you going it doesn't deal with errors or timeouts.
Best And Easy Code
setInterval(function()
{
$.ajax({
type:"post",
url:"uourpage.php",
datatype:"html",
success:function(data)
{
$("#div").html(data);
}
});
}, 5000);//time in milliseconds

Categories