PHP Update using Javascript - php

I have my php file which contains my method to update the database. However, in Javascript how do I make it so every 5 seconds say it "visits" this page so it's contents gets updated.
Here is my update.php file:
<?php include('config.php') ?>
<?php
mysql_query("UPDATE paint SET paint_points='test'") or die(mysql_error());
echo "Updated";
?>
Sorry, I'm not familiar with the terminology.
Thanks

Use the setInterval function with an (a)jax request every 5 secs in javascript:
//syncronized jax:
function myjax() {
var oXhr = new XMLHttpRequest();
oXhr.open("POST", "yourphp.php", false);
oXhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
oXhr.send(null);
}
//set an interval each 5 seconds to call your myjax method
setInterval(function() { myjax(); }, 5000);
In this example the request is synchronous but it could be asynchronous if you wished so.

The simplest case is to reload the page with:
<script type="text/javascript">
setInterval(function() { location.reload(true); }, 5000);
</script>
You can get fancier if you use an ajax call to fetch the page.

Using jQuery:
(function() {
var updateAgain = arguments.callee;
$.get('/url/to/script.php', function() {
setTimeout(updateAgain, 5000);
});
})();
The advantage of this over setInterval is that it won't start counting to five seconds until the request is finished; this is important if the request takes more than a second or two. It will also stop if a request fails (which may or may not be an advantage).

Related

using ajax to fetch a result from php and reload page

So I have been working on this for hours now, I have read a bunch of StackOverflow posts and I am still having no luck.
I have a page that has 2 sections to it, depending on the int in the database will depend on which section is being displayed at which time.
My goal is to have the page look to see if the database status has changed from the current one and if it has then refresh the page, if not then do nothing but re-run every 10 seconds.
I run PHP at the top of my page that gets the int from the database
$online_status = Online_status::find_by_id(1);
I then use HTML to load the status into something that jquery can access
<input type="hidden" id="statusID" value="<?php echo $online_status->status; ?>">
<span id="result"></span>
So at the bottom of my page, I added some jquery and ajax
$(document).ready(function(){
$(function liveCheck(){
var search = $('#statusID').val();
$.ajax({
url:'check_live.php',
data:{search:search},
type:'POST',
success:function(data){
if(!data.error){
$newResult = $('#result').html(data);
window.setInterval(function(){
liveCheck();
}, 10000);
}
}
});
});
liveCheck();
});
this then goes to another PHP page that runs the following code
if(isset($_POST['search'])){
$current_status = $_POST['search'];
$online_status = Online_status::find_by_id(1);
if($current_status != $online_status->status){
echo "<script>location.reload()&semi;</script>";
}else{
}
}
the jquery then loads into the HTML section with the id of "result" as shown earlier. I know this is a very bad way to do this, and as a result, it will work at the beginning but the longer you leave it on the page the slower the page gets, till it just freezes.
If anyone is able to point me towards a proper method I would be very grateful.
Thank you!!
js:
(function(){
function liveCheck(){
var search = $('#statusID').val();
$.ajax({
url:'check_live.php',
data:{search:search},
type:'POST',
success:function(data){
if(data.trim() == ''){
location.reload();
}else{
$('#result').html(data);
window.setTimeout(function(){
liveCheck();
}, 10000);
}
}
});
}
$(function(){
liveCheck();
});
})(jQuery)
php:
<?php
if(isset($_POST['search'])){
$current_status = $_POST['search'];
$online_status = Online_status::find_by_id(1);
if($current_status != $online_status->status){
$data = '';
}else{
$data = 'some html';
}
echo $data;
}
Your page is slowing down because you are creating a new interval every time you call the liveCheck function. Over time, you have many intervals running and sending requests to your PHP file concurrently. You can verify this behavior by opening the developer console in your browser and monitoring the Network tab.
What you should do instead is set the interval once, and perform the $.ajax call inside that interval. Additionally, it's good practice to not send a new request if a current request is pending, by implementing a boolean state variable that is true while an request is pending and false when that request completes.
It looks like the intended behavior of your function is to just reload the page when the $online_status->status changes, is that correct? If so, change your PHP to just echo true or 1 (anything really) and rewrite your JS as:
function liveCheck() {
if (liveCheckPending == true)
return;
liveCheckPending = true;
var search = $('#statusID').val();
$.ajax({
url:'check_live.php',
data:{search:search},
type:'POST'
}).done(function(data){
if (!data.error)
location.reload();
}).always(function(data){
liveCheckPending = false;
});
}
var liveCheckPending = false;
setInterval(liveCheck, 10000);

Refresh php embedded in html [duplicate]

What i want to do is, to show a message based on certain condition.
So, i will read the database after a given time continuously, and accordingly, show the message to the user.
But i want the message, to be updated only on a part of the page(lets say a DIV).
Any help would be appreciated !
Thanks !
This is possible using setInterval() and jQuery.load()
The below example will refresh a div with ID result with the content of another file every 5 seconds:
setInterval(function(){
$('#result').load('test.html');
}, 5000);
You need a ajax solution if you want to load data from your database and show it on your currently loaded page without page loading.
<script type="text/javascript" language="javascript" src=" JQUERY LIBRARY FILE PATH"></script>
<script type="text/javascript" language="javascript">
var init;
$(document).ready(function(){
init = window.setInterval('call()',5000);// 5000 is milisecond
});
function call(){
$.ajax({
url:'your server file name',
type:'post',
dataType:'html',
success:function(msg){
$('div#xyz').html(msg);// #xyz id of your div in which you want place result
},
error:function(){
alert('Error in loading...');
}
});
}
</script>
You can use setInterval if you want to make the request for content periodically and update the contents of your DIV with the AJAX response e.g.
setInterval(makeRequestAndPopulateDiv, "5000"); // 5 seconds
The setInterval() method will continue calling the function until clearInterval() is called.
If you are using a JS library you can update the DIV very easily e.g. in Prototype you can use replace on your div e.g.
$('yourDiv').replace('your new content');
I'm not suggesting that my method is the best, but what I generally do to deal with dynamic stuff that needs access to the database is the following method :
1- A server-side script that gets a message according to a given context, let's call it "contextmsg.php".
<?php
$ctx = intval($_POST["ctx"]);
$msg = getMessageFromDatabase($ctx); // get the message according to $ctx number
echo $msg;
?>
2- in your client-side page, with jquery :
var DIV_ID = "div-message";
var INTERVAL_IN_SECONDS = 5;
setInterval(function() {
updateMessage(currentContext)
}, INTERVAL_IN_SECONDS*1000);
function updateMessage(ctx) {
_e(DIV_ID).innerHTML = getMessage(ctx);
}
function getMessage(ctx) {
var msg = null;
$.ajax({
type: "post",
url: "contextmsg.php",
data: {
"ctx": ctx
},
success: function(data) {
msg = data.responseText;
},
dataType: "json"
});
return msg;
}
function _e(id) {
return document.getElementById(id);
}
Hope this helps :)

JQuery SetTimeout before running code

I'm trying to run a function in JQuery that basically shuts down or starts up a server. The code I have so far is this -
$(".stopServer").click(function(){
$.post("controller.php",{stop: 'true', server: this.name});
$('#test'+this.name).load('controller.php?status=true&server='+this.name);
});
The problem is obviously it stops the server fine but it updates the status div ('#test'+this.name) straight away. This is no good because the server takes a period of time to shut down. I've been trying to get SetTimeout to work but can't figure it out... Any help would be appreciated.
Thanks guys, you're the best :)
UPDATE:
Full functions are here:
$(document).ready(function() {
$(".startServer").click(function(){
$.post("controller.php",{server: this.name});
setTimeout("showStatus('"+this.name+"')", 3000);
});
$(".stopServer").click(function(){
$.post("controller.php",{stop: 'true', server: this.name});
setTimeout("showStatus('"+this.name+"')", 3000);
});
function showStatus(name) {
alert(name);
$('#test'+name).load('controller.php?status=true&server='+name);
}
});
UPDATE
Given up on the idea of it, instead the status is polled for every second instead.
var refreshId = setInterval(function()
{
$('.status').each(function() {
var $name = $(this).attr('name');
$(this).load("controller.php?status=true&server=" + $name);
});
}, 1000);
I've added a quick sample of wrapping the function in a setTimeout
​$(document).ready(function(){
$('#test').click(function(){
var message = 'hello';
setTimeout(function(){ callback(message) },1000);
});
function callback(name){
alert(name);
}
});​
JSFiddle DEMO
I dont know if you will get a response from 'controller.php' when the server actually shuts down, in case you don't, try this...
$(".stopServer").click(function(){
$.post("controller.php",{stop: 'true', server: this.name});
setTimeout("showStatus('"+this.name+"')", 10000);
});
function showStatus(name) {
$command = $('#test'+name).load('controller.php?status=true&server='+name);
}
ajax calls are asynchronous. the $.post() call returns immediately and lets the actual post work be done in the background. either change it to a synchronous call (usually not a good idea), or put the subsequent code in the "success" part of the .post call, e.g.
$.post('controller.php', success: function(data) {
$command = etc....
});

jQuery animations don't work correctly if Ajax request is too fast

I've looked around a bit and haven't found an answer to this yet.
I have an ajax request that when you click the button it sends info to the server and hides the current div and loads a loading gif. I have it set so when the server responds it gets rid of loading gif and shows the content from the server.
code:
$("#submit").click(function(e){
e.preventDefault();
var $domain = $.fn.HTTP($('#domain').val());
if(!$.fn.ValidURL($domain)){
$('#domainerror').fadeIn(500);
return false;
}
if($('#domainerror').css('display')!=='none'){
$('#domainerror').fadeOut(350);
}
$('#question').hide(500, function(){
$('#waiting').show(350);
});
$.getJSON('http://localhost/file.php',
{
i: $domain
},
function(data){
$('#answer').html(data.message + $('#trybutton').html());
$('#waiting').hide(350, function(){
$('#answer').show(350);
});
});
});
The problem is jQuery receives the response from the server too fast and the loading gif doesn't disappear.
However if I tell the server to sleep for 3 seconds it works just fine. This is not the solution I want.
Any ideas?
Surely it's a good thing your users aren't having to see a loading animation because it's so fast?!
Anyway, the problem is that the animation is taking at least 500ms - animations are processed asynchronously, at the same time as your AJAX request. Instead of making the server sleep, which is arguably a waste of CPU, make the browser wait instead, before you send the AJAX request.
Put the call in a setTimeout() function, this example will make it wait 3 seconds:
setTimeout(function() {
$.getJSON('http://localhost/file.php',
{
i: $domain
},
function(data){
$('#answer').html(data.message + $('#trybutton').html());
$('#waiting').hide(350, function(){
$('#answer').show(350);
});
});
}, 3000);
The ideal solution however would be to not use animation effects and just use show() and hide().
Get rid of the delay in showing the waiting animation, so it's not still showing up when the request returned.
$('#question').hide() //was 500
$('#waiting').show(); //was 350
If you add all up that's almost a second later. By that time the ajax request may have returned in most systems, so it's not worth to be still animating by that point
Use Javascript's setTimeout. Code may look something (perhaps not exactly) like this:
setTimeout("getResponse()", 3000);
function getResponse() {
$.getJSON('http://localhost/file.php',
{
i: $domain
},
function(data){
$('#answer').html(data.message + $('#trybutton').html());
$('#waiting').hide(350, function(){
$('#answer').show(350);
});
});
}
That way you've got your AJAX request still sending your i variable to the server, processing the code in file.php and sending back data which you can handle. The only trick is to put this in a function (not required, but it certainly makes the setTimeout function look prettier) and call it after 3000 milliseconds.
Seems like the ajax callback is executed before the question hiding ends, and the $('#waiting').show(350); comes after $('#waiting').hide(350, ...). You have three possibilities to solve that:
If you'd show the #waiting img immidiately (not waiting for the question to fade out), this won't happen; the answer should then also not wait for #waiting to hide.
Or you use a variable to indicate that the answer is already fading in when the question has faded out, and show no animation then:
var answered = false,
waiting = false;
$('#question').hide(500, function(){
if (!answered) {
waiting = true;
$('#waiting').show(350);
}
});
$.getJSON('http://localhost/file.php', {
i: $domain
}, function(data){
$('#answer').html(data.message + $('#trybutton').html());
answered = true;
if (waiting) {
$('#waiting').stop().hide(350, function(){
$('#answer').show(350);
});
} else {
$('#answer').show(350);
}
});
If you want the four animations to show always and consecutively (at least 1550ms), you'd need to code them manually:
var showanswer = false;
$('#question').hide(500, function() {
$('#waiting').show(350, function() {
if (showanswer) // already loaded
showanswer(); // execute callback
else
showanswer = true; // mark as shown
});
});
$.getJSON('http://localhost/file.php', {
i: $domain
}, function(data){
$('#answer').html(data.message + $('#trybutton').html());
function animate() {
$('#waiting').hide(350, function(){
$('#answer').show(350);
});
}
if (showanswer) // waiting image shown
animate();
else
showanswer = animate; // set as callback
});

JavaScript functions do not work when jquery loads an external page

I have to make a div load an external file every minute. It does load the file but the JQuery functions don't work. Is there any other way I can load the file so that the JavaScript functions work?
My JQuery code-
emaild = $("#hidden").val();
var refresh = setInterval(function() {
$("#load").load('aposts.php?id='+emaild);
}, 60000);
$.ajaxSetup({ cache: false });
Sorry for the bad English :P
I see you defining emaid and referencing emaild
try this
var $div = $('#myDiv');
var timer = setInterval( function() {
$div.html( $("#load").load('aposts.php?id='+emaild) );
}, 5000);

Categories