Ajax Calls to database table - php

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.

Related

Jquery - How to call a function only if a new row is inserted in database

I have a div which contains comments for a post ... when user add a comment the div containing comments get updated immediately ( i have set a function which is called when user press enter )
Here Is my code for that :
$(document).on('keydown','.addComment',function(e){
var id = $(this).attr('id').match(/\d+/);
var p_id = Number(id);
var comment_box = '#comment_box_'+id;
var content = $(comment_box).text();
if (e.which === 13 && e.shiftKey !== true) {
content = content.replace(/\s\s+/g, ' ').replace(/\n/g, '<br>');
if (content.length > 0 ) {
$.ajax({
type : 'POST',
url : 'update.php',
data: ({
content: content,
id: p_id,
act: "add_cmnt"
}),
success : function()
{
update_ca("comment_area_"+id, true);
}
}); //End of Ajax
}
return false;
}
});
but a user logged in from another account must have to refresh the page to see new comments ... now what i want to do is that all users see the latest comments without refreshing the page i.e when ever a new comment is posted by any user the div containing comments should be updated ... now one way is to do this is that a function is called out after every 10 seconds which refreshes the div via ajax
Here is code :
setInterval(function(){update_comment_area();}, 10000);
this line of code refreshes the comment area after every 10 seconds but i want this function to be called only if a new row ( comment ) is inserted into a database
can anyone help me that how this can be done ??
Create a function that checks for a new row in the database i.e checkNew().
Then try:
if (checkNew()) {
refreshAjax();
}
Note: for the checkNew(), if a new record has been inputted, return true;
Else return false;
Here is a way to implement the checkNow():
Let it retrieve the value gotten from a PHP page that performs the SQL: SELECT lastupdated FROM commentTable ORDER BY id DESC LIMIT 1.
What that does is that it retrieves the last value in the commentTable which would obviously be the last inserted comment. Then update your page with intervals. The comment will continue to change as long as more comments are being added
Since it sounds like you already have an event for the submission of a comment, and assuming you're using javascript to push the comment to the server:
You can just use a callback and have it refresh then. Of course, that would only show up for the user that submitted the comment.
Example for that: JQuery Ajax calls with callbacks
Since you haven't mentioned your back-end coding language or database structure there are only a limited amount of suggestions I can give. However, one that would work would be to use AngularJS, or Socket.io to establish 2-way binding.
UPDATE:
Based on your code and how you're calling it I'm going to assume that update.php has the ability to know whether the record (comment) was added successfully. Once it's been added, have update.php set a global javascript variable to a new value (increment it, use a random number, doesn't matter as long as the value changes)
Then setup an object.watch() that will do your ajax call to update the comments when that variable changes. This is probably the simplest way to do it without using something like socket.io or angular.
How to use object.watch in javascript

AJAX Updating Javascript Variable from PHP page?

I am not a developer so this is new to me, but I am a long time sys admin so please forgive me if I am asking stupid questions!
Basically, I have a PHP script that parses some XML and echo's a single number formatted to 1 dp.
I am using some Javascript Wijmo widgets, in particular a dial that takes it input from a javascript variable. Lets say "resultvalue".
I want to populate "result value" every 5 seconds with the results of my php script that exists as /xmlparse.php. The wijmo widget apparently responds dynamically to a changing variable so this will produce a dial with a moving needle without having to refresh the whole page.
All I need to achieve is getting this javascript variable to update every 5 secs.
I am already doing something similar with AJAX on a html page by just populating a DIV with the results of /xmlparse.php and it works great using the set interval command.
But how can I get my javascript variable updating every 5 secs with the result of that script?
An example would be a great help!
Code Here
Regards
Tom
window.setInterval(function(){
jQuery.ajax({
url:'/xmlparse.php'
}).done(function(response) {
resultvalue=response;
});
},5000);
You'll probably need to parse the result. Perhaps xmlparse should format it with json_encode so your ajax request could grab it as an object.
Edit:
Looking at your source, I see that the radial gauge doesn't actually monitor the resultvalue variable to detect when it's changed. You'll have to update it yourself. In this case:
window.setInterval(function(){
jQuery.ajax({
url:'/xmlparse.php'
}).done(function(response) {
resultvalue=response;
$("#gauge").wijradialgauge({value:resultvalue});
});
},5000);
You can set a global variable and set it as value returned from xmlparse.php;
var resultValue;
// load at page load first
$(document).ready(function() {
updatevalue();
});
setInterval("updatevalue()", 5000);
function updatevalue(){
$.get("xmlparse.php", function(response) {
resultValue = response;
})
}
This is for test
setInterval("test()", 4000);
function test() {
console.log("Result is: " + resultValue);
}

Ajax time alert using PHP

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).

Live updating ajax charts

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);
}

Incremental Output - Jquery and PHP

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

Categories