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....
});
Related
I've started using ajax requests recently. I am making a mobile web application where I am to the request for data on PHP side server script. The javascript function is to automatically execute when the user navigates to the page. But the script seems not to run until I refresh the page, here is my javascript code.
<script>
$( document ).ready(function(){
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString();
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
function requestContent() {
var date = new Date();
$.ajax({
type:'POST',
url:'php/app/adminTimeline.php',
data:{
date: date.yyyymmdd()
},
success: function(data) {
if (data == '') {
alert("No data found!");
} else {
// $("#loading_spinner").css({"display":"none"});
$('#timeline-content').prepend(data);
}
},
error: function(data) {
// $("#loading_spinner").css({"display":"none"});
alert("Something went Wrong!");
}
});
}
window.onload = requestContent();
});
</script>
The document.onready method and window.onload the method seems not to be working too.
Ps: I have the Jquery library linked in the header too.
Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
https://learn.jquery.com/using-jquery-core/document-ready/
Also you're calling requestContent()
window.onload must be function, not returning value.
$(document).ready(function(){
// here you ajax
}
https://jsfiddle.net/cqfq5on5/1/
The code window.onload=requestContent(); will execute when the window loads, not necessarily when the entire document has loaded.
However where you create the date object, uses this, which executes after the document is fully loaded
$(document).ready(function(){
//Code
});
This means, that the POST request will be made once the window loads, which is before the document is fully loaded, thus, that date object will not exist until the page is refreshed, at which point the Javascript was likely cached. Also another answer (#sagid) pointed out, window.onload cannot be a returning value but must be a function.
i.e.
window.onload=function(){
//Code
};
This means, your solution is to change window.onload=requestContent(); to
$(document).ready(function(){
requestContent();
});
Good luck!
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 :)
If NewMessage changes, I want an alert. I have tried live and change on and bind change, but nothing works.
Relevant PHP:
$message=6;
$myReturnData["Message"] = $message;
//JSON-encode and return
print json_encode($myReturnData);
Relevant jQuery:
setInterval(function(){
$.getJSON("foo.php", function(data){
var NewMessage=(data.Message);
if(NewMessage>0){
document.title= NewMessage + ' pm';}
$(NewMessage).live("change", function() {
alert(NewMessage);
});
});
}, 3000);
'change' is not doing what you think it should be. You should store the original message in a variable, then compare it to the new message you're getting. Like this:
var currentMessage = '';
setInterval(function(){
$.getJSON("foo.php", function(data){
var NewMessage=(data.Message);
if(NewMessage>0){
document.title= NewMessage + ' pm';
if (currentMessage !== NewMessage) {
alert(NewMessage);
currentMessage = NewMessage;
}
}
});
}, 3000);
Assuming you want function X to run when a variable controlled by the server changes. To that means you are using a polling mechanism.
So if you want your code to know when it receives a different message, you must store the previous message somewhere outside the scope of your callback function.
Most easy way:
var lastMessage = 'the server will never ever forever ever return this message';
setInterval(function(){
$.getJSON("foo.php", function(data){
// .. arbitrary code
if (lastMessage != data.Message)
{
alert('it changed');
lastMessage = data.Message;
}
// .. more arbitrary code
});
}, 3000);
i don't think the following code makes any sense or would even remotely work, because the NewMessage is not a DOM element, is it?
$(NewMessage).live("change", function() {
alert(NewMessage);
});
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).
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
});