I’m using jQuery and countdown (jQuery plugin). I want the countdown to run for x seconds, where x is an integer from serverTime.php.
Problem – I can’t figure out how to return the responseText in function getTime(), so that it could be used in Timer function.
At first I tried using pure js (without jQuery), and I found similar topics:
- why-can-i-not-return-responsetext-from-an-ajax-function
- in-ajax-how-to-retrive-variable-from-inside-of-onreadystatechange-function
- how-to-return-variable-from-the-function-called-by-onreadystatechange-function
- and others…
Some ideas/possible solutions I’ve come across:
- using synchronous call and a global variable for storing response. I
tried this and don’t consider it an option, because it freezes the
user screen (and is considered bad practice as well, in most cases) - helper function .
–
Timer function:
$(function (){
var time = getTime(); // time is an integer
$('#defaultCountdown').countdown({until: time, format: 'S', onExpiry: action});
});
getTime() checks serverTime.php and should return the content, which will be an integer.
Alert(html) works, while return html does not work. I know it’s because the call is asynchronous.
function getTime()
{
$.ajax({
url: "serverTime.php",
cache: false,
async: true,
success: function(html)
{
alert(html);
helperFunction(html);
return html;
}
});
}
helperFunction. Unfortunately, I don’t know how to pass the result to timer function.
function helperFunction(response)
{
return response;
}
serverTime.php
echo 30; // 30 seconds, just an example
I’ve tried to explain my problem and show that I’ve put some time into it. If you need additional information, just ask. Maybe I’m just thinking in the wrong direction.
Your code doesn’t show where the
timevariable is actually being used.Ultimately, you can’t return the AJAX response from the
getTime()function because the AJAX is asynchronous, sogetTime()will always return before the response is received.You’d do better to pass whatever code you want into the
getTime()function……or call another function from inside the
:successcallback, passing it the response……or simply hardcode the proper code into the
:successcallback…EDIT:
I now see where you want to use
time. You could use my second example above. Just be sure that the function you create is in a variable scope that is accessible to yourgetTime()function.Like this: