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);
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 :)
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'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....
});
I'm working on a system using jQuery UI that opens a dialog which basically loads a continually refreshing tail of a log file. It works great, but the problem is that when you close it, it doesn't kill off the dialog, so it still continues to send traffic to you with the tail of the file. Obviously it is not a good practice.
Anyway, the code I have so far to try and tackle the problem is as follows.
var $console = $('<div title=" Server Console"></div>')
.dialog({
height: 720,
width: 1000,
resizable: false,
autoOpen: false
});
$(".consoleOpen").click(function(){
$console.dialog('open').load("console.php?console="+this.name);
});
$console.bind('dialogclose', function(event) {
$console.remove();
});
This is the refresh function in console.php:
(function($)
{
$(document).ready(function()
{
var $container = $("#responsecontainer");
$container.load("console_class.php?console=<?php echo $console; ?>");
var refreshId = setInterval(function()
{
$container.load('console_class.php?console=<?php echo $console; ?>');
}, <?php echo $consoleRefresh;?>);
});
})(jQuery);
Look at the API function destroy()
$console.bind('dialogclose', function(event) {
$console.dialog('destroy').remove();
});
You also need to use clearInterval or else it will keep running as long as the page is open.
$console.bind('dialogclose', function(event) {
$console.dialog('destroy').remove();
clearInterval(refreshID);
});
Try this:
$console.bind('dialogclose', function(event) {
$console.dialog( "destroy" );
});
or read this jQuery Dialog
You mentioned it already
$console.dialog("destroy");
The dialog is not the issue here - it's the interval that's making the call.
Where you declare refreshId do it like this...
var window.refreshId = setInterval(function()
Then where you remove the dialog, add a clearInterval...
$console.bind('dialogclose', function(event) {
$console.remove();
clearInterval(window.refreshId);
});
That makes the variable refreshId global so that it can be accessed elsewhere in your code. You can then use it to clear the interval that is making the repeated call.
I've had this same problem...
See:
jQuery UI dialog close doesn't clear dialog (Stack Overflow question)
Creating dialogs on demand (blog entry)
You need to call $('#dialog_id').dialog("destroy");.