Back to Home

Using the jQuery.ajax result outside the call function or you can do without cron

jQuery.ajax · json · cron

Using the jQuery.ajax result outside the call function or you can do without cron

Not so long ago I started using jQuery.ajax. In the process of writing one script, I discovered that you can not immediately use the response ajax request. In my case, the request is transmitted to the server script, which in turn fills the json file from a third-party domain. Firebug filling is tracked from 12 to 20 seconds, which is long enough by my standards (you can’t make people wait so long). I came up with the following way out of the situation:

We introduce a global variable (date, exchange rate to ruble):
var jscurr = jQuery.parseJSON('{"data":"2012-01-22","USD":31.9344,"EUR":40.3842,"UAH":3.98135}')

Our request to an external server: Upon complete, open the old json file, enable the user to start working with yesterday's data: 20 seconds after the start of proxy.php, until json will not be completely updated, we read it again, we give people relevant data, we do all this by success:
jQuery(document).ready(function() {
jQuery.ajax({
type: "GET",
url: "proxy.php",
dataType: "script",
cashe: false,
complete: curencesjson(),
success: curencesjsonT()
});
});//конец onLoad



function curencesjson() {
jQuery.ajax({
url: 'curences.json',
dataType: "json",
cache: false,
success: function(jscur) {
jsreturn(jscur);
}
});

//обновление глобальной переменной по success
function jsreturn(jscur){
jscurr = jscur;
}
}



function curencesjsonT() {
setTimeout(function(){
jQuery.ajax({
url: 'curences.json',
dataType: "json",
cache: false,
success: function(jscur) {
jsreturn(jscur);
}
});
}, 20000);
}

//по success естественно опять происходит обновление глобальной переменной


Thus, it was possible to start updating json data without cron. Also, the result of an ajax request is available outside the call function.
In the server-side script, a check by date is organized, the update will occur only once, with the arrival of the first visitor to the page with the script on each new day.

It might have been easier, but this is only the beginning of my experience.

Read Next