📜 ⬆️ ⬇️

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

Recently I started using jQuery.ajax. In the process of writing a single script, I found that you cannot immediately use the ajax response of the request. In my case, the request is sent to the server script, which in turn from a third-party domain fills the json file. Firebug filling is tracked from 12 to 20 seconds, which is long enough by my standards (you can’t keep people waiting so much). I came up with the following way out:

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

Our request for an external server:
jQuery(document).ready(function() {
jQuery.ajax({
type: "GET",
url: "proxy.php",
dataType: "script",
cashe: false,
complete: curencesjson(),
success: curencesjsonT()
});
});// onLoad


By complete, open the old json file, give the user the opportunity to start working with yesterday's data:
function curencesjson() {
jQuery.ajax({
url: 'curences.json',
dataType: "json",
cache: false,
success: function(jscur) {
jsreturn(jscur);
}
});

// success
function jsreturn(jscur){
jscurr = jscur;
}
}


20 seconds after the start of proxy.php, until json is fully updated, we read it again, give out actual data to people, we do all this with success:
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 the ajax request is available outside the call function.
In the server script, of course, 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.
')
Maybe it could have been easier, but this is only the beginning of my experience.

Source: https://habr.com/ru/post/139060/


All Articles