I am currently trying to get my AJAX to work when the document loads and runs every 20 seconds. How do i go about doing this? I have got it to work for every 20 seconds but cant get it to work when the document loads. Any help would be brilliant.
<script type="text/javascript" language="javascript">
window.setInterval(function(){
var jobid = $('#jobid').text();
var filename = $('#filename').text();
$.ajax({
url: "../progress_bar.php",
type:'POST',
data: {"value1": jobid, "value2": filename},
dataType: 'json',
success: function(responce){
$("#progress").html(responce);
} // End of success function of ajax form
}); // End of ajax call
}, 20000);
</script>
Thanks
For ajax requests one should always use recursive timeouts instead of intervals ( cause the request may last longer then the interval, so there are multiple requests done at a time ) , which also solves the main problem:
//may wrap the whole thing into an onload listener
(function update(){
$.ajax({
url: "../progress_bar.php",
type:'POST',
data: {"value1": jobid, "value2": filename},
dataType: 'json',
success: function(responce){
$("#progress").html(responce);
//update again in 20secs:
setTimeout(update, 20000);
}
});
})(); //start immeadiately
A small demo:
console.log("load");
(function next(){
console.log("run");
setTimeout( next, 1000);
})()
Related
I am attempting to run some code that is hammering my web host's memory and I/O usage. I am unsure how I can clean up or fix this code, as this is the first time I've tried using the AJAX technology.
The JS simply needs to return the value of the PHP script it is calling every 20 seconds and display it in an empty <div> tag. I am very new with AJAX and I am not sure where my problem is and how to fix it.
Here is my Javascript:
<script type="text/javascript">
$(document).ready(function() {
function update() {
$.ajax({
type: 'POST',
url: 'time_hash.php',
dataType: 'text',
timeout: 20000,
success: function(data) {
$(".dispKey").html(data);
setInterval(update, 20000);
}
});// End ajax call
}// End function update()
update();
});
</script>
And my PHP script being called:
// Modify the server time to round down to the nearest 20 seconds
$modTime = (time() - (time() % 20));
// Create one-way hash from modified time
$hashToken = md5($modTime);
// Truncate hash to the first 6 characters
$dispToken = strtoupper(substr($hashToken, 0, 6));
// Display the 'generated key' -- uppercase.
echo $dispToken;
Any help would be greatly appreciated.
You are creating the interval inside your success callback, so every time your success function runs you are creating a new interval other than the one you already had and so on, so you end up with infinite intervals.
try creating the interval outside your ajax call
function update() {
$.ajax({
type: 'POST',
url: 'time_hash.php',
dataType: 'text',
timeout: 20000,
success: function(data) {
$(".dispKey").html(data);
}
});// End ajax call
}// End function update()
setInterval(update, 20000);
Try moving the "setInterval(update, 20000);" from success. That should help.
I currently have the below function which updates the data in a div when the page is refreshed and this works fine however i want to edit the function to make it constantly update say every 2 seconds without having to refresh the page. How would i go about doing this?
<script>
$(document).ready(function ajaxLoop() {
//-----------------------------------------------------------------------
// Send a http request with AJAX Jquery
//-----------------------------------------------------------------------
$.ajax({
url: 'getOrderStatus.php', // Url of Php file to run sql
data: "",
dataType: 'json', //data format
success: function ajaxLoop(data) //on reciept of reply
{
var OrdersSubmitted = data[0].SUBMITTED; //get Orders Submitted Count
var OrdersFulfilled = data[0].FULFILLED; //get Orders Fulfilled count
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#OrdersSubmitted').html("SUBMITTED:" + OrdersSubmitted);
$('#OrdersFulfilled').html("FULFILLED:" + OrdersFulfilled); //Set output html divs
}
});
});
</script>
You can chain setTimeout calls to achieve this:
$(document).ready(function() {
function updateOrders() {
$.ajax({
url: 'getOrderStatus.php',
dataType: 'json',
success: function ajaxLoop(data) {
var OrdersSubmitted = data[0].SUBMITTED;
var OrdersFulfilled = data[0].FULFILLED;
$('#OrdersSubmitted').html("SUBMITTED:"+ OrdersSubmitted);
$('#OrdersFulfilled').html("FULFILLED:"+ OrdersFulfilled);
setTimeout(updateOrders, 2000);
}
});
});
The alternative is setInterval(), however if the requests slow down this can lead to calls being queued, which will eventually lead to memory issues.
You need to add a repeating event to call your updateOrders function. Like:
function startUpdateOrdersTimes() {
setInterval(function() {
updateOrders();
}, 2000);
//Call now (otherwise waits for first call)
updateOrders();
}
Using "window.setInterval" (https://developer.mozilla.org/en/docs/Web/API/window.setInterval) you can repeatedly execute a function at a specified time interval.
function SomeFunction()
{
$.ajax({...});
}
window.setInterval(SomeFunction,2000);
This would execute SomeFunction every 2 seconds
Hope this helps
timerupdateorders = setInterval(function() {
ajaxLoop();
}, 2000);
You may use
clearInterval(timerupdateorders);
to end the timer
I am having some trouble with the timing of javascript events. The problem I am having is that one part of the code seems to be executing before another part of the code completes. I need to ensure that the first code finishes before the latter code begins. Here is the initial code:
function(){
myLoop(); //this needs to complete before the call to myMethod below
$.ajax({
url: sURL + "myController/myMethod",
success: function() {
$.msg("My Success Message",{live:10000});
error: function(){
$.msg("My Error Message",{live:10000});
});
}
And here is the code that loops and inserts records into a db:
function myLoop(){
$('input[name=c_maybe].c_box').each(function(){
if( $(this).prop('checked') ){
var rn = $(this).prop('value');
$.ajax({
url: sURL + 'myController/myInsert',
type:"POST",
dataType: 'text',
data: {'rn': rn},
success: function(data) {
//not sure what to do on success.
}
});
}
});
}
The problem that seems to be happening is that the call to myController\myMethod is happening before myLoop completes inserting all the records into the database.
Can someone suggest a way for me to redesign this code so that I can ensure that myController\myMethod is not called until myLoop has completely finished?
Thanks.
function myLoop() {
var jqxhrs = [];
if( $(this).prop('checked') ){
var rn = $(this).prop('value');
jqxhrs.push($.ajax({...
}
return jqxhrs;
}
function () {
$.when.apply(undefined, myLoop()).done(function () {
$.ajax({
url: sURL + "myController/myMethod",
...
});
}
$.when.apply is used to call $.when on the array of ajax requests, so .done is not called until they are all complete.
You can use the $.when function that has been added to jQuery.
It goes something like this:
$.when(ajaxFunction1(), ajaxFunction1()).done(function(response1, response2){
// when the function calls are done this code here will be executed -> the response will be passed as parameters corresponding to the functions -> response1, response2
});
Or you can try to use "beforeSend" within the ajax function:
$.ajax({
beforeSend: function(){
alert("doing stuff before the ajax call ...");
},
success: function(){
alert("Whoa!");
}
});
You can make the ajax call synchronous. That way, the execution will be blocked till ajax call returns:
$.ajax({
url: sURL + 'myController/myInsert',
type:"POST",
dataType: 'text',
data: {'rn': rn},
async: false,
success: function(data) {
//not sure what to do on success.
}
});
I am using jQuery getJSON() function. This function getting data with no problem. But sometimes waiting, waiting waiting... And my loading bar showing loading loading loadin at center of page.
So jQuery ajax() function have an timeout variable. But i want to use getJSON function. And i think that i can use ajaxStart() and ajaxStop() functions. But how?
$('.loadingDiv')
.hide()
.ajaxStart(function() {
$(this).fadeIn();
setTimeout("throw '';",15000) //i used this but didn't work
setTimeout("return;",15000) //i used this but didn't work
setTimeout("abort();",15000) //i used this but didn't work.(Abort all ajax events)
})
.ajaxStop(function() {
$(this).fadeOut();
});
getJSON() returns a promise on which you can call the abort function :
var p = $.getJSON(..., function(){ alert('success');});
setTimeout(function(){ p.abort(); }, 2000);
EDIT : but if your goal is just to abort if it takes too much time, then lethal-guitar's answer is better.
getJSON() is just a shorthand for the following:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
So you could use $.ajax() and specify the timeout option as desired. See also: http://api.jquery.com/jQuery.getJSON/
As lethal-guitar mentioned getJSON() function is just an shorthand for $.ajax(). If you want to detect if a timeout has occurred rather than an actual error use the code below.
var request = $.ajax({
dataType: "json",
url: url,
data: data,
success: function( ) { },
timeout: 2000
}).fail( function( xhr, status ) {
if( status == "timeout" ) {
// do stuff in case of timeout
}
});
There's always the nuclear route as well:
//Set AJAX timeout to 10 seconds
$.ajaxSetup({
timeout: 10*1000
});
This will set all the AJAX requests your program makes (even via $.getJSON) to have a time out of 10 seconds (or what have you).
the setTimeout function executes a set of code after a specified number of milisecons in the global scope.
The getJSON function (per the jQuery documentation here http://api.jquery.com/jQuery.getJSON/) is shorthand for:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
so you would want to make your call like so:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success,
timeout: 15000
});
$('.loadingDiv')
.hide()
.ajaxStart(function() {
$(this).fadeIn();
})
.ajaxStop(function() {
$(this).fadeOut();
});
I don't think any of these answers are ideal. I know this is years late, but what you want to do is use the success/error callback options of the .ajax(); method when receiving a JSONP response.
Example of how I would structure this:
// Call
$.ajax({
// URL you want to get
url: 'http://example.com/json?callback=?',
// Set a realistic time in milliseconds
timeout: 3000,
// Put in success callback function here, this example
// shows you the data you got back from the call
success: function(data) {
console.log(data);
},
// Put in an error handling function, just an alert in this case
error: function(badData) {
alert('The call was unsuccessful');
},
type: 'POST'
});
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
jQuery Ajax request every 30 seconds
I know we can load a part of page on some event. I also know we can load whole web page every specified time, but I wanted to know how to load a part of page every 30 seconds.
function refreshPage() {
$.ajax({
url: 'ajax/test.html',
dataType: 'html',
success: function(data) {
$('.result').html(data);
},
complete: function() {
window.setTimeout(refreshPage, 30000);
}
});
}
window.setTimeout(refreshPage, 30000);
Using setTimeout has the advantage that if the connection hangs for some time you will not get tons of pending requests since a new one will only be sent after the previous one finished.
function load_content(){
setTimeout(function(){
$.ajax({
url: 'ajax/example.html',
dataType: 'html',
success: function(data) {
$('.result').html(data);
load_content();
}
});dataType: 'html',
},30000);
}
load_content();
jQuery has already a build in functionality to replace a element's content by a remote file, called load(). With load() you can use this oneliner:
window.setTimeout($('#refresh').load('/remote/content.html'), 30000);
#refresh is the id of the element to refresh, /remote/content.html is the remote content.
$(function() {
setInterval(function() {
getData(); // call to function
}, 30000 ); // 30 seconds
});
// define your function here
function getData() {
var url ="/mypage.php?type=load_data";
var httpobj = $.ajax({url:url,async:false}); // send request
var response = httpobj.responseText.trim(); //get response
$('#myDiv').html(response); // display data
}
If you are using jQuery you can use the load() method
setInterval(function(){
$('#some-kinda-container').load('/some/kinda/url.html #bit-you-need');
}, 30000);