I have an issue here: I am creating a project that involves planning. A user plans a specific program for a particular time and submit into the database, MySQL, using PHP.
I want the system to raise an alert when the time planned has reached or when it is a few minutes to the time.
Something like
if ($selectedDate==CURDATE() $$ selectedTime==CURTIME()){
// some ajax to provide popup
}
I will appreciate useful help. Thank you.
You will need to create a global variable to store your list of events, not sure what type you would want to use. You will fill the variable from an ajax call (so you can do it on every page of your app), and then iterate over the events to prompt the user.
On page load, you will want to grab the events from your database.
$(function()
{
retrieveEvents();
promptEvents();
});
Create a function that can be called to get the events, and store them to a global variable.
function retrieveEvents()
{
// Make ajax call to get all events
// Wait 1 minute, calls the function again to get new events
setTimeout( "retrieveEvents()" , 60000 ); //60000 = 1 minute
}
You will then want a function to then prompt the events
function promptEvents()
{
// At this point you will iterate the global variable of events
// You can check if the event is 2 minutes away, or 5 seconds away
// In those cases, you would then show a modal or alert box.
// Wait 5 seconds, call this method again
setTimeout( "promptEvents()" , 5000 ); //5000 = 5 seconds
}
You could try to run a repeating ajax call (using javascript setTimeout) and on your second page run a query on the database to retrieve their stored "plan time" and test against current time. If it is nearing (e.g. 2 minutes away or something) then your ajax call will return a warning.
Use javascript's setInterval function to check whether the time is closer. Example:
setInterval(function() {
// ajax request and alert action goes here
}, 1000);
The ajax check in the above example will execute in every 1 second (1000 milliseconds). You can change the interval as you like, say 5000 (5 seconds).
Related
I want to notify a person a count of the jobs available in a table in my database. In a table I have a list of 8 jobs and they have their avilability. I've done the count with a PHP query with SELECT COUNT(*) AS jobs... and created this ajax script which shows the count with an interval.
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#divToRefresh').load('notification.php'); //this contains the query
}, 30000);
});
However, I am not sure how I can make it so when the user sees the notifcation alert, they will close it and it doesn't appear again until there's a new available job.
I can't find anything on the good ol google either.
Your jQuery function is running in 30 seconds intervals polling data from server. notification.php returns pre-rendered HTML containing (I assume among other things) the number of jobs available.
Check the number of available jobs and show notification based on that:
setInterval(function() {
var oldNumberOfJobs = newNumberOfJobs = 0;
$('#divToRefresh').load('notification.php'); //this contains the query
newNumberOfJobs = $('#divWithJobsCount').text;
if (newNumberOfJobs > oldNumberOfJobs) {
// show notification to the user
}
oldNumberOfJobs = newNumberOfJobs;
}, 30000);
To be more specific (showing/hiding notifications), I need to see your HTML.
This solution feels bulky. The whole pre-rendered HTML is being reloaded again and again. A nicer approach would be to only return the number of jobs available and only update that number using jQuery.
Also, it might be a good idea to return the latest job_id as well as the total number of jobs available. This way, you could check if the latest job_id that is already stored in the front end matches the newly received job_id. And only if they don't match you would update the counter and show new notification.
update
Here is a jsfiddle.js which covers your case. Jobs counter is simulated with current number of minutes. The function checks every 15 seconds if the number of minutes has changed. Once it happens, an alert notification is shown (but only if the old one was closed).
setInterval in jsfiddle is written using a mock object so that it is testable in the browser without AJAX requests. In your code use the following form:
setInterval(function() {
$.get('notification.php', checkJobsCounter); // returns jobs count in plain text
}, 30000);
Well you need to make an AJAX call and the response of it should be the number of new notifications. Now check if num>0 then just do $("#notification").fadeIn(); which is a by default hidden div having text You have new notification (or whatever) and a close button.
$(doument).ready(function(){
setInterval(function(){
$.get("notification.php", function(data){
if(data>0)
{
$("#div").fadeIn();
}
});
},1000);
});
Once user closes this you can create a cookie in the browser of the user and then check if cookie is set dont make ajax request, This was you dont have to update the db and every user will be able to see the notification.
I have a database table called "mytable" with 1 column called col1.
This column takes values 0 and 1 and it's updated every 15 minutes.
I want a working example with a PHP page that will make an ajax call to this table and show image1 if value is 0 and image2 if value is 1.
This ajax called must be fired automatically every minute. Is it posisble?
thanks for the help
It is possible. More research would show you how but here is how you can do it;
First build a function that does an ajax call;
function call()
{
return data; // Ajax here
}
then call it with an interval;
window.setInterval(function(){
call();
}, 5000);
This will call it every 5 seconds. For the PHP part, you will need to do more research. You can simply create a page called Data.php and post to that page with jquery post or ajax then simply retrieve the data and parse it.
I have a website which serves around 20 - 50 widgets per second and I wanted to create a chart that automatically gets data from the server and then updates the chart and I want the chart to run from right to left as more data is added and remove the old values and add the new values. I would like a javascript and php solution.
I have tried google and cannot find any solutions for this and I found a tutorial once but now I have lost that link :( So any kind of help in form of a link, piece of code or what to look for will help.
One thing that I wanted was having the widget start with a delay of fetch data but start displaying the data after 5 seconds of the intial fetch and then fetch data every 2 seconds, however load data second by second. This would ease the load on the server while also generating smooth graphs.
Any help would be appreciated....
Something Like this for php
http://support.nevron.com/KB/a175/implement-real-time-chart-in-aspnet-application-using-ajax.aspx
So you just need two functions running at different intervals that have access to the same variable where all the data will be stored
function runChart() {
var dataObject = [];
fetchFromServer = function() {
//Make your Ajax call here
//and then update 'dataObject'
}
//set fetchFromServer to fire every 5 seconds
setInterval( function () { fetchFromServer() }, 5000 );
loadToChart = function() {
//In here keep track of what was the last data you added to the chart
//pull data-points from 'dataObject'
//and display the next data-point on the graph
}
//set loadToChart to fire every second
setInterval( function () { loadToChart() } ,1000);
}
I have finished a facebook app that uses php and ajax to get statisicts about friends and find best match. The app is using tabs and is working fine, however sometimes when I click on one tab to send ajax request and loading icon shows I do not get any response back and the loading icon keeps showing. Is there a way that I can count how many seconds an ajax call is taking so I redirect the user to an altertanive html page after x number of seconds?
To achieve what you'd like to obtain, you could call (after X seconds, using setTimeout()) a function that checks if the ajax response has been loaded.
For example:
var responseLoaded = false;
function checkIt(){
if(!responseLoaded)
window.location = "%http://alternative-page%";
}
setTimeout(checkIt,10000) //after 10 seconds
responseLoaded could be a global variable that can be set to true at the end of the ajax response.
Or, alternatively, you could check if some DOM element or JS var is present (i.e. created by AJAX call) at that time (when the function has been called through setTimeout)
Then, You could use
Date.getTime()
To obtain the current timestamp. You can compare the timestamp at the beginning with the one at the end of the ajax response to see the total time it takes. (just if you want to check the average ajax loading time)
Another option would be to set the timeout parameter of the of the xmlhttprequest object. In jQuery it's the timeout option in the options object.
$.ajax ({
timeout: 1000,
success: successCallback,
error: function (req, error, errorStatus) {
if (error == 'timeout') {
//send them to other page....
}
}
});
You would probably want to put in some more error handlers though... also, since the xmlhttpobject2 has on timeout function callback, this process might be more streamlined now...
Don't quote me exactly on the syntax either. I'm writing this on my phone from memory....
I have an application that rates a large set of items and outputs a score for each one.
In my php script I'm using ob_start and ob_flush to handle the output of data for each rating. This works great if I directly load the script. But when I try to use .get via jquery, the entire content loads and then is placed into a container, instead of incrementally adding.
I'm wondering the following
Is there a way to initiate data placement before the get has completed?
Do I need to continually poll the script until the process is complete?
Is there a more efficient way to display the data instead of get?
For this kind of problems, I will have this approach:
Keep the old script that using ob_start() and ob_flush() for a user that disable javascript in their browser.
For a user that have javascript enable, load the predefined number content one at a time. To differentiate between js enable user and not, I'm thinking of 2 page. In first page you display a link to old script. Then put a jquery code in this page to intercept click on the link to old script, so click on that link will display (or create) a div, then load the content into that div.
You can use a setTimeout to call AJAX code continuously, then after a certain condition reached (Ex, empty response), you can remove the setTimeout using clearTimeout. Each AJAX request will need to have an offset param, so it will fetch content from last AJAX call. After receive response, increment the offset for the next AJAX call. You can use global variable for this.
You can use a simple global variable to prevent an AJAX request run while the last AJAX still waiting response, to prevent race condition. Example code:
//lock variable
var is_running = FALSE;
//offset start with 0
var offset = 0;
function load_content($) {
//check lock
if (! is_running) {
//lock
is_running = true;
//do AJAX
$.get(URL,
{ PARAM },
function(resp){
//put data to 'div'
//...
//if empty, then call clearTimeout
//...
//increase offset here
offset = offset + NUM_ITEM_FETCHED
//release lock
is_running = false;
});
}
}
The point you must pay attention that using AJAX call, you must determine the response manually, since ob_start and ob_flush will have no effect in this scenario.
I hope this will help you create your own code.
Jquery will receive a success status from the ajax call when the complete page has finished loading .. so whatever you do in the php will not get returned to the calling page until the whole process has finished .. (ajax is a one-send/one-receive system)
You would need to complicate your system to do what you want..
example..
your php updates an external file of progress, and your jquery polls this file in some interval and displays progress..
You would initiate the interval polling on ajax submit, and on ajax success terminate it..
I had a similar problem awhile back where I wanted a php script to send a series of emails and update the jquery page to say something like "Sending 23/50".
What I ended up doing was setting up the php script to handle one item at a time. This might also work in your case. Could you have jquery pass an item identifier of some sort to a php script that handles just that one item? Then in the callback, you could place the data for that item in the page as well as creating a new ajax request for the next item. In other words, each callback would create a new request for the next item until the entire list of items has been looped through.
What do you think?
-DLH