AJAX/PHP Auto Display Updated Value - php

I have a simple question, I'm sure. I just don't know what I should be searching for on google. It'd probably be easier for me to explain:
For example I have a mysql field with the value 'Yes'
How do I with AJAX/PHP keeping querying the field for when the value changes to 'No'?
Could someone explain, in simple terms please

There are two function that will help.
setTimeout ( expression, timeout );
setInterval ( expression, interval );
Where expression is a function and timeout and interval are integers in milliseconds. setTimeout runs the timer once and runs the expression once whereas setInterval will run the expression every time the interval passes.
So in your case it would work something like this:
setInterval(function() {
//call $.ajax here
$.ajax({
url : URL,
data : passData,
dataType : 'json', //or html or xml
beforeSend : function()
{
//this will execute before request is send
},
success : function(response)
{
//check for response if( response ) { } else { }
}
});
}, 5000); //5 seconds
Now the backend php file.
<?php
$passedVar = $_REQUEST['passedData']; //get data that were passed in ajax call
//database connection
//query to check for status
if(query return true)
{
echo json_encode(true);
exit;
}
else
{
echo json_encode(false);
exit;
}

first create a JavaScript function which will execute ajax call then put that function on setInterval()
function ajaxcall(){
// you ajax call;
}
setInterval(ajaxcall, 10000);// change time by replacing 10000(time is in millisecond)
Here ajaxcall will be called in every 10 second.You can do anything inside ajaxcall function I mean checking your database value by ajax.

Related

ajax firing multiple times after database becomes unlocked

I'm having a problem with an ajax call.
I have some code set up to run a function every 2 seconds which looks to see if the content has been updated or not with WordPress ajax, does some work with php, then updates a database:
window.setInterval( "updateContent()", 2000 );
function updateContent(){
if($('#needcontent').hasClass('yes')){
CONTENT.updateContent( 'monitor' , ids );
}
}
$(function() {
CONTENT= {
updateContent: function(callback, data){
data = {
action: 'myplugin_do_ajax',
callback: callback,
data: data
};
$.post(ajaxurl, data, function(response){
switch(data.callback){
case 'monitor' :
data_returned = eval("(" + response + ")");
if(data_returned.completed == 'true'){
//Adjust the DOM because there was a content update, and remove the class "yes" from #needcontent to stop the check until next time
}
else{
//Do nothing because no content was found, let the Interval run again
}
break;
}
}
}
}
The problem I'm finding is that sometimes the content is quite large, and ends up locking the table while php updates the database. The ajax call runs once, runs into a database lock, and doens't return anything until the database is unlocked again. The database could be locked for a 10 second period, resulting in 1 run and 4 not-run calls.
UPDATE:
It's not the database locking, it's the php function taking longer than 2 seconds to return, causing the Interval to loop again and again without a response.
What's happening is those 4 not-run ajax calls then begin to fire one right after the other like they are trying to catch up or something.
I've tried increasing the Interval time to 10 seconds, but that doesn't solve the problem because if the database is locked for 11 seconds it'll still fire twice.
I've tried using global variables in Javascript (yuck) to stop the Interval from calling the function, but that doesn't seem to work either.
UPDATE 2:
I answered my own question below to what worked for me.
try this:
window.updateCheck= window.setInterval( "updateContent()", 2000 );
function updateContent(){
if($('#needcontent').hasClass('yes')){
CONTENT.updateContent( 'monitor' , ids );
clearInterval(window.updateCheck);
}
}
$(function() {
CONTENT= {
updateContent: function(callback, data){
data = {
action: 'myplugin_do_ajax',
callback: callback,
data: data
};
if(window.ajaxCall) window.ajaxCall.abort();
window.ajaxCall= $.post(ajaxurl, data, function(response){
window.updateCheck= window.setInterval( "updateContent()", 2000 );
switch(data.callback){
case 'monitor' :
data_returned = eval("(" + response + ")");
if(data_returned.completed == 'true'){
//Adjust the DOM because there was a content update, and remove the class "yes" from #needcontent to stop the check until next time
}
else{
//Do nothing because no content was found, let the Interval run again
}
break;
}
}
}
}
what we did here was to put the interval in a global variable, and also the ajax call ($.post() call actually), then when the conditions of updating is checked, we stop the interval, kill all the other active or queued request and send the ajax request to the server.
while the request is being sent to the server the update checks are stopped, then as soon as the server responds to the request we start the update check again!
charlietfl's comment on my OP got me thinking about the difference between setInterval and setTimeout, and I realized that:
a) setInterval would continuously run, regardless if a result is returned or not. In my case, using ajax, the function was being call asynchronously so the setInterval wouldn't care if a result was returned.
b) If I changed the code to use setTimeout, I could control the outcome more.
This is what I did.
Firstly, remove the setInterval function completely, it's not needed.
Then I changed my switch case to this:
case 'monitor' :
var monitor = false;
data_returned = eval("(" + response + ")");
if(data_returned.completed == 'true'){
//Adjust the DOM because there was a content update, and remove the class "yes" from #needcontent to stop the check until next time
}
else{
//Run the monitor after a 2 second timeout.
var ids = j('.contentDiv').attr('id');
window.setTimeout(CONTENT.updateContent( 'monitor' , ids ) , 2000);
}
break;

How do I insert a chunk of code every time my while loops fetches some data from my database

I have a table in my database. I use a while loop to traverse them. and make a HTML div with that fetched data. I used LIMIT 10 because entries in posts will keep changing as users will keep inserting posts into the table
$get_ids=mysql_query("SELECT * FROM posts ORDER BY id LIMIT 10");
while($row = mysql_fetch_array($get_ids)){
$sm=$row['message'];
echo "<div>".$sm"</div>";
}
What i want to know is how do i use jquery to make this script insert these 10 divs into my DOM every 1 second or so. Help please URGENT!!!!
Try to google for some jquery & php webservice examples. Basically you should do something like this:
//Javascript function which fetches the single data as J.D.Smith suggested
function getHtml()
{
$.get({
'url': 'Address of your php webservice',
'success': function(data) {
$("#content").html($("#content").html() + data); //Append html to your page
}
});
}
//Call the function every 10 sec, place it in $(document).ready() or anything else you use
window.setTimeout(function () {
getHtml();
}, 10000);
This code is more to be illustrative sample than working code
You'd put that code in a separate file (for example: divfill.php) and then use something like this
$.get({
'url': 'divfill.php',
'success': function(data) {
$("#content").html($("#content").html() + data);
}
});
In my case, I have added the following method in my js file,
//call the target function after 250 ms
function async(targetFn, callback) {
setTimeout(function () {
targetFn();
callback();
}, 250);
}
And, I call this function as shown below,
async(BindValuesInLookup, function () {
BuildGrid()
GetInfo();
});
BindValuesInLookup is the target function. It gets fired after 250ms. Once it is done, the callback functons will be executed. So you can use this functionality in the loop and increase the timeout to 1000 (1 sec).
Thanks,
Vim

Real time data updates with comet and PHP?

I'm looking to implement real time notification updates on my social networking website. I have done some research on comet and i'm really fascinated by it.
From what I understand, this is the basic flow of what happens on a comet server.
Webpage:
Sends an ajax request to server when the document is ready.
Server:
Queries the database every x amount of seconds and returns a json string containing results if any are found.
Webpage:
Receives the result of the json string from the server and sends out another ajax request to do the above process again.
By understanding the flow of how comet works, I've written some PHP and Javascript code.
The JavaScript code uses the jQuery library and sends an ajax request out to the server with the current time in a unix timestamp format as a GET parameter.
$(document).ready(function(){
var timestamp = Math.round(new Date().getTime() / 1000);
function comet2(){
$.ajax({
type : 'GET',
url : 'comet.activities.php?timestamp=' + timestamp,
async : true,
cache : false,
success : function(data) {
alert("current timestamp "+timestamp)
var json = JSON.parse(data);
if(json !== null){
alert(data);
}
timestamp = json[0].timestamp;
setTimeout('comet2()', 1000);
},
error : function(XMLHttpRequest, textstatus, error) {
setTimeout('comet2()', 15000);
}
});
}
//call the comet function because the page has loaded.
comet2();
});
The PHP code will query for new activities by searching the database for new rows by using a timestamp paramater (in this case, a unix timestamp in a query). For this example, I have limited the amount of results to 1.
<?php
set_time_limit(0);
include("models/config.php");
global $mysqli,$db_table_prefix;
$last = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$results = null;
$flag=true;
$stmt = $mysqli->prepare("SELECT id,timestamp FROM uc_user_activity WHERE timestamp > ? ORDER BY timestamp DESC LIMIT 0,1");
$stmt->bind_param("i", $last);
$stmt->bind_result($id,$timestamp);
while($flag){
$stmt -> execute();
while ($row = $stmt->fetch()){
$flag = false;
$results[] = array(
"id" => $id,
"timestamp" => $timestamp
);
}
$stmt -> close();
usleep(100000);
clearstatcache();
}
echo json_encode($results);
?>
The code above doesn't actually 'work' The problem is that if a user posts a new comment, it will fail to add to the database when the comet script is running. This means that the comet script will never return any json result because the statement in the sql query is never met (no new activities are added with a newer timestamp). My ajax code for posting new comments is working 100%, so I know that isn't the problem. Simply 'nothing happens', that is - nothing (no errors) are alerted or outputted to the browser console.
Edit number 3:
I'm seriously struggling to explain what I mean by 'nothing is happening', so I have uploaded an image showing that the database insert fails when the comet script is being called from jquery (notice how the textbox is disabled whilst the comment is being posted via ajax).
What can I do about this? I've spent hours searching the internet trying to fix this/find a similar working example with no avail.
If I change the query in my PHP code to be:
$stmt = $mysqli->prepare("SELECT id,timestamp FROM uc_user_activity WHERE timestamp **<** ? ORDER BY timestamp DESC LIMIT 0,1");
instead of:
$stmt = $mysqli->prepare("SELECT id,timestamp FROM uc_user_activity WHERE timestamp > ? ORDER BY timestamp DESC LIMIT 0,1");
results are instantly alerted to the browser window, comments can be posted again and the script is called again and new posts are displayed. This shows that my code 'is working' fine afterall and it looks like the query is causing the problem...
Can anyone see what is going on here? I have edited this question 7 times now and any guidance would be great as I'm just getting nowhere.
Just so this doesn't get closed, here is my question to round up what I have discussed above:
Are there any better ways of implementing a comet server? I'm not the
most experienced guy ever, but I would really like to learn how to do
this. It seems StackOverflow has this functionality and it works
perfectly - how are they doing it?
I can't possibly write my post in any further detail than this and I would REALLY appreciate some guidance from you awesome people. A suggestion as to why my code 'isn't working' or links to any tutorials explaining how to implement this would be amazing! Thanks in advance and apologies for this monster of a question and all of the edits!
My hunch is that the timestamp value which you are passing returns no results. You get the current time through Javascript. The query queries for all posts after this timestamp.
Can you try to print the query and run the same query manually to ensure that it retrieves data from the DB?
So, for the best available tutorial for Comet with PHP is here.
http://www.zeitoun.net/articles/comet_and_php/start
Like it, if it helps :)
For those who want to use the simple chat solution above in the link with jQuery here is the solution.
<script type="text/javascript">
var Comet = {};
Comet.jquery = {
timestamp: 0,
url: './backend.php',
noerror: true,
initialize: function () {
},
connect: function ()
{
this.ajax = $.ajax({
type: "get",
url: this.url,
data: {timestamp: this.timestamp},
success: function (data) {
// handle the server response
var response = JSON.parse(data);
console.log(response);
//alert(response.timestamp);
Comet.jquery.timestamp = response.timestamp;
Comet.jquery.handleResponse(response);
Comet.jquery.noerror = true;
},
complete: function (data) {
// send a new ajax request when this request is finished
if (!Comet.jquery.noerror) {
// if a connection problem occurs, try to reconnect each 5 seconds
setTimeout(function () {
Comet.jquery.connect()
}, 5000);
}
else {
Comet.jquery.connect();
}
Comet.jquery.noerror = false;
}
});
},
disconnect: function ()
{
},
handleResponse: function (response)
{
$('#content').append('<div>' + response.msg + '</div>');
},
doRequest: function (request)
{
$.ajax({
type: "get",
url: this.url,
data: {'msg': request}
});
}
}
</script>

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

Returning post data [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
$.post("../js.php", {state: state},
function(data) {
return data;
});
Here's my jquery code. Like you can see it sends a post request to js.php.
Here's the code for js.php.
{...}
$query = "SELECT * FROM table WHERE x='" . $y . "'";
$result = $mysqli->query($query);
$num_rows = $result->num_rows;
echo $num_rows ? $num_rows : 0;
Now, when I alert the "data" back in the js file then it displays fine. But when trying to return it or assign it to a variable it does not work. The console tells me that the variable that has been assigned the value of data is undefined.
Any thoughts?
Updated code:
var data = null;
$.post("../js.php", {state: state},
function(response) {
data = response;
});
console.log(data);
Still not working. :(
the function in the post is a callback function, you cannot return anything from it since there is no one to return it to.
You need to use the data retuened inside the callback, for example:
$.post("../js.php", {state: state},
function(data) {
$('.someClass').html(data);
});
The callback you pass to asynchronous methods such as $.post are executed some time in the future, once the async call has returned. The JavaScript execution has moved on and is now somewhere else, so there is nowhere for your callback to return to.
Imagine it like this:
//Some code... executed as you would expect
var data; //Currently undefined
$.post("../js.php", {state: state}, function(response) {
//Callback is executed later, once server responds
data = response; //No good, since we already executed the following code
return response; //Return to where? We have already executed the following code
});
/* More code... we carry on to this point straight away. We don't wait for
the callback to be executed. That happens asynchronously some time in
the future */
console.log(data); //Still undefined, callback hasn't been executed yet
If you need to work with the data returned by the async call, do so in the callback.
var data = null;
$(...).click(function(e) {
$.post("../js.php", {state: state},
function(response) {
data = response;
});
});
After that just access data variable. Keep in mind that its value will be null unless the post request is done.
The example you posted will do nothing EVERY TIME because AJAX calls like this are ASYNCHRONOUS (that's what the A in AJAX stands for).
If you want to be able to use the value of the output, add a hidden element to your page with a unique ID that contains the value. Then you can access that element through javascript.
Thats because, the ajax call is asynchronous. You should never return a value from a callback function. Do the job in the callback or trigger an event.

Categories