I'm trying to figure out a way to have jQuery update a div the moment a table in mysql is updated. I've spent a vigorous amount of hours searching online for an answer, and so far, nothing. Can anyone help me out with this problem?
Well the steps you should probably take are:
Have a piece of AJAX code that queries the server for a change (like row count changing or something along those lines). Using jQuery you can do that:
function checkUpdates()
{
$.ajax({
type: "POST",
url: 'hasDataChanged.php', // a webservice or other URL that queries the database
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
// return a JSON string like { "hasChanged" : "true" } or something
if (data.hasChanged) {
// data has changed, do something
}
}
});
}
Then you can use the Javascript method setInterval to call the code every few seconds. It is unrealistic to do it instantly.
$(document).ready(function() {
setInterval("checkUpdates()", 3000); // Calls the function every 3 seconds
});
You'll have to poll the database via ajax and php every (couple of) second(s) and check if the data has changed. if so, update the div.
i don't think there's a way of detecting the exact moment the db is updated.
Useful links on polling. It attempts to make server send data to browser:
http://onepixelahead.com/2010/04/30/html5-web-sockets-example/
http://en.wikipedia.org/wiki/Comet_(programming))
Related
This question already has an answer here:
Wordpress: call to plugin php file via ajax
(1 answer)
Closed 6 years ago.
So I'm making a Wordpress site and want to send data (css styles dynamically created by jQuery) to PHP. The reason for this (not fully relevant to this question) is to write the data as a .css file that is loaded at the beginning of every page--making it so there's no visible 'change' of styles when js executes (well, only the first time the page is loaded). I'm sure there's probably a better way to do this.
But back to the main part (sending data from jQuery to a .php). I'm executing a js script (on "front-page.php") that does this:
jQuery(function($){
$(window).on("load", function() {
$.ajax({
type: "POST",
url: "create-style.php",
data: { style : styleString },
dataType: "json",
success: function () {
console.log("success");
}
});
});
});
The console says 'success', so I assume data is getting passed to create-style.php.
create-style.php's write function does this
$file = 'new-style.css';
$style = $_POST['style'];
file_put_contents($file, $style, LOCK_EX);
Now the first thing I tried was having the function included in Wordpress's functions.php. I don't know a lot about Wordpress or web development in general, but it seems intuitive that this wouldn't work since probably the php files get executed before the js (so how could it get the data?)
In an attempt to solve this I rewrite the create-style.php as a cron using wp_schedule_single_event to fire when someone visits the site, with a slight delay:
add_action('write_style_cron', function(){
// the above writing function
});
wp_schedule_single_event(time() + 10, 'write_style_cron'); // give it a slight delay to make sure jQuery happens
However, no $_POST data gets written to the file and doing any tests shows it's empty. I've done a lot of tests and know that:
cron functionality is basically working
the writing function works with test values
$_POST is showing as completely empty and I get an "Undefined index" error in the /wp-cron.php?doing_wp_cron
$.ajax is firing success
there are no other php / js errors
Thanks for reading this very long post. Been searching the internet all day for solutions and decided it might be best to just ask. I'd much appreciate any ideas.
Try using this code:
jQuery(function(){
$('#yourFormName').on('submit', function (e) { //on submit function
e.preventDefault();
$.ajax({
type: 'post', //method POST
url: 'create-style.php', //URL of page where to pass values
data: $('#yourFormName').serialize(), //seriallize is passing all inputs values of form
success: function(){
console.log("success");
},
});
}
});
I have been staring at this problem for the past 2 hours and can't seem to fathom it, even after validating that everything loads correctly when scouring the console.
I basically have two sliders on my page which will eventually populate results in a table, every time I change my slider I send an array of two values to my AJAX script:
function update_results(values)
{
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php",
data: { query : values },
cache: false,
success: function(data) {
// eventually some success callback
}
});
}
The browser successfully finds update_results.php but it does not perform the logic on the page ( I assume it has found the page as the 404 error does not appear in my console. )
At this point in time the script is extremely bare-bones as I'm obviously trying to establish communication between both files:
<?php
$vals = $_GET['values'];
echo $vals;
In this case $vals is never echoed to the page, am I missing something in my AJAX? I know the values enter the function as alerted them out before attaching the PHP script.
Ajax Calls are suffering from Browser Cache. If your browser thinks, that he already knows the content of update.php, he will return the cached content, and not trigger the script. Therefore your
modified code might simply not get executed. (Therefore your insert query wasn't executed)
To ensure this is not happening in your case, it is always a good idea to pass a parameter (timestamp) to the script, so your browser thinks it's another outcome:
function update_results(values)
{
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php?random_parameter=" + (new Date().getTime());
data: { query : values },
cache: false,
success: function(data) {
// eventually some success callback
}
});
}
This will ensure that - at least - the browser cache is refreshed once per second for update_results.php, no matter what browser cache-settings or server-side cache advices are telling.
when Ajax is done, the success callback is triggered and the output of you php script is saved in data.
you can handle the data like this:
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php",
data: { query : values },
cache: false,
dataType: "text",
success: function(data) {
document.write( data )
}
});
PHP, running at server, is unaware of what happening at the front-end browser and it simply respond to ajax request as any other normal http request. So the failure of SQL query has nothing to do with javascript, which only responsible for sending ajax request and receiving and handling the response. I guess there's some errors in your php script.
EDIT : Found the solution to my problem below. See it here -> IE must close for event with jQuery to work
I've been asking around, trying to figure this one out. If there are any other way to do a mySql query in PHP by an event .. other than $.get.
I've previously posted this one other problem just in case somebody could help out ->
$.get not working in IE
Now I'm trying to find a way around the problem I previously posted cause if $.get is not going to happen in IE for me then there has to be another way with this. Maybe not with jQuery
Perhaps you could try the longhand syntax (as $.get is a shorthand alias of $.ajax)
function getbillinfo(tbl) {
$.ajax({
type: "POST",
url: "getbillno.php",
data: "tbl=" + tbl,
success: function(bill){
$("#billno").val(bill); });
}
});
}
See http://api.jquery.com/jQuery.ajax/
Edit: with regard to your problems with IE, there could be a couple of reasons
Possibility One
IE caches the results of Ajax calls to the same resource even if you
tell it not to in your HTTP headers. So if you make a request to
getbillinof.php?tbl=table over and over again, IE will make the
request once and then stop making it in the future and simply return
the result of the first request. To circumvent this you can call getbillinof.php?tbl=table&random_string_here
It may also be worth setting cache: false in the ajax() options and having a look into the isModified option.
Possibility Two
A Race Condition is causing the IE render action to run before
any data was returned. This however is unlikely as the success()
function is only supposed to run once the data has been received. A
race condition becomes far more likely if you're doing something like
function getbillinfo(tbl) {
$.ajax({
type: "POST",
url: "getbillno.php",
data: "tbl=" + tbl,
success: function(bill){
var mydata = bill;
}
});
$("#billno").val(mydata);
}
I'm looking to display data from a table in a mysql database using PHP, however, I want the data to automatically update itself and retrieve current values every 5 seconds.. WITHOUT having to refresh the page. Is this possible? Maybe with JQuery/ AJAX? If so, please explain how it can be done / point me to a resource where I can find such information
Thanks
If you use window.setInterval() and jQuery's .load() you should be able to do what you want. The PHP script should return the HTML that needs to replace the previous one.
Javascript:
function refreshData()
{
// Load the content of "path/to/script.php" into an element with ID "#container".
$('#container').load('path/to/script.php');
}
// Execute every 5 seconds
window.setInterval(refreshData, 5000);
A really basic example:
function poll(){
$.ajax({
type: "GET",
url: "your/php/script/",
success: function(data){
// do something with data
}
});
};
setInterval(poll, 5000);
jQuery is a good option. Here are the docs for ajax.
You will want to make this call with setInterval
Something like this might get your started.
setIntervla(updateFromDb,5000);
function updateFromDb(){
$.ajax({
url: "getUpdates.php",
success: function(){
$(this).addClass("done");
}
});
};
What you are describing is exactly the type of the AJAX is used for, AJAX allows for asynchronous requests to be made to your server.
For learning I would suggest using a framework like Jquery and look into the AJAX api.
Basicly you will need a PHP script that query the database and responds the results the way you want them. A suggestion would be to JSON encode them.
In JavaScript on the client you will need to you things like:
var poll = setInterval(function(){
$.ajax({
type:"GET",
url: "yourpage.php",
success: function(data){
//HANDLE DATA
// use JSON.parse(data); if your JSON encoding your data
}
});
},5000)
Just go to the documentation of jQuery:
http://api.jquery.com/category/ajax/
Use the command "jQuery.get()" or better "jQuery.getJson()" to make a http request to the server. Use JSON to get a better communication between server and client. Return from server side a json string and convert this on the client to an javascript object. (the function jQuery.getJson already do this for you) so you can easily access the key and values in the data array.
Just an example:
SERVER Part with PHP:
<?
$data = array('key'=>'value');
return json_encode($data, true);
CLIENT Part:
$.getJSON('myurl.php', function(data) {
// THIS ONE IS CALLED with your PHP data
alert(data.key);
});
$(function(){
window.setInterval(function(){
$.post("filename.php",{'field1':field1,'field2':field2,'field3':field3},function(data){
//callbackfunction(data)
})
},30000);//millisecs
});
And have your php file do all your sql
I have a single page that I need to on occasion asynchronously check the server to see if the status of the page is current (basically, Live or Offline). You will see I have a function with a var live that is set when the page initially loads. I then do an ajax request to the server to retrieve whether the status of live is true or false. I compare the initial live variable with the newly returned data json object. If they're the same I do nothing, but if there different I apply some css classes. I recursively run it with setTimeout (Is there a better way to recursively do this?).
My Problem:
data.live doesn't change from it's initial time it runs even when it has changed in the db. I know my mysql is working because it returs the right value on the initial load. It seems like a caching issue.
Any help is greatly appreciated.
function checkLive() {
var live = <?=$result["live"]?>;
$.ajax({
type: 'get',
url: '/live/live.php',
dataType: 'json',
success: function(data) {
console.log('checking for updates... current:' + data.live);
if (data.live == live) {
return;
} else {
var elems = $('div.player_meta, object, h3.offline_message');
if (data.live == '1') {
elems.removeClass('offline').addClass('live');
} else {
elems.addClass('live').addClass('offline');
}
}
}
});
setTimeout(function() { checkLive() } ,15000);
}
checkLive();
Use the cache option of $.ajax() to append a cache breaker to the URL, like this:
$.ajax({
type: 'get',
url: '/live/live.php',
dataType: 'json',
cache: false,
//success, etc.
});
If that doesn't resolve it...look at firebug, see if a request is being made (it should be after this for sure), if it's still getting an old value, the issue is in PHP, not JavaScript.
Unrelated to the issue, just a side tip: If you need no parameters, you can skip the anonymous function call, this:
setTimeout(function() { checkLive() } ,15000);
can just be:
setTimeout(checkLive, 15000);
You can check if it's a caching issue by adding unique ID to the url:
change url: '/live/live.php', to url: '/live/live.php?'+new Date().getTime(),
Cheers
G.
I think Nick Craver has the right response.
For the other point of the question which is you SetTimeout , you could use SetInterval() and avoid the recursive call. But in fact I would stay with a setTimeout() and add a factor on the 15000 time. set that factor as a parameter of checklive. Then you will have a check which will be delayed progressively in time. This will avoid a LOT of HTTp requests from the guy which his still on your page since 48 hours.
Chances are that most of the time users will check for new pages in a regular manner, but someone staying for a very long time on a page is maybe not really there. Here's a piece of code I had doing that stuff.
function checkLive(settings) {
(...) //HERE ajax STUFF
setTimeout(function() {
if ( (settings.reload <2000000000) && (settings.growingfactor > 1) ) {
checkLive(settings);
settings = jQuery.extend(settings,{reload:parseInt(settings.reload*settings.growingfactor,10)});
}
},settings.reload);
}