getJSON done callback - javascript

I have the function bellow called every 5 seconds to get data from the server, which is flask/python. My question is how can I adapt the getjson call to have callback when the data is successfully retrieved.
I know there's .done .fail and so on, but I was wondering if I can keep this structure and just add bellow it, but I don't know the syntax in this particular case, hope this isn't too confusing, thanks for reading, here's the code.
// get data from the server every getDataFromServerInterval milliseconds
var getDataFromServerInterval = 5000;
function getData(){
// request timesince table entries from server for user...
$.getJSON($SCRIPT_ROOT + '/_database', {
action: "getUserTable_timesince",
username: $('input[name="username"]').val()
}, function(data) { // do something with the response data
timesince_dataBuffer = data;
});
return false; // prevent get
}
// get data from the server every getDataFromServerInterval milliseconds
setInterval(getData, getDataFromServerInterval);

You could do something like this. Instead of processing the data in getData or using a callback, take advantage of the promise that $.getJSON returns. Have a separate function that is called by the timeout which calls for the data, then processes it. It neatly separates your code out into more managable functions.
var getDataFromServerInterval = 5000;
function getData() {
return $.getJSON($SCRIPT_ROOT + '/_database', {
action: "getUserTable_timesince",
username: $('input[name="username"]').val()
}
}
function wrangleData() {
getData().then(function (data) {
console.log(data);
});
}
setInterval(wrangleData, getDataFromServerInterval);

I found a partial solution, I realized that I can add a callback at the end of the function that handles the data received, which is somewhat equivalent to .done in a different getjson call structure, I'm not sure yet if the function gets called before or after the data is received.
// global timesince buffer, holds
var timesince_dataBuffer;
// get data from the server every getDataFromServerInterval milliseconds
var getDataFromServerInterval = 5000;
function getData(){
// request timesince table entries from server for user
$.getJSON($SCRIPT_ROOT + '/_database', {
action: "getUserTable_timesince",
username: $('input[name="username"]').val()
}, function(data) { // do something with the response data
timesince_dataBuffer = data;
updateEntryStruct(); // the hope is to call this when data is received
});
return false; // prevent get
}
// get data from the server every getDataFromServerInterval milliseconds
setInterval(getData, getDataFromServerInterval);

This is the solution I came up with.
var timesince_dataBuffer;
function getData(){
// gets user's entries from sql table
$.getJSON($SCRIPT_ROOT + '/_database', { // $SCRIPT_ROOT, root to the application
action: "getUserTable_timesince",
username: $('input[name="username"]').val()
}, function(data) { // if a response is sent, this function is called
timesince_dataBuffer = data;
updateEntryStruct(); // recreate the structure of each content, buttons etc
});
return false;
}
I get the data, put in a global variable, call another function which takes that data and re-creates a structure for each object received, this way I don't recreate parts of the structure which are static, most importantly the buttons.
Another function is called every 1 second, which updates the dynamic parts.
(formatted time) passed since
(event name)
Anyway, this is actually my final project in CS50, I started by communicating with the server via form submissions, refreshing the page each time the user pressed a button, then I did it by ajax, but I was sending requests to the server every 2 seconds, and having unresponsive buttons because I would keep re-creating the buttons themselves on a time interval.
And now the page feels responsive and efficient, it's been a great learning experience.
If anyone wants to check out the code, everything is here.
https://github.com/silvermirai/cs50-final-project
It's basically a bunch of random functionality that came to mind.
The application can be found here as of now.
http://ide502-silvermirai.cs50.io:8080/

Related

How do I simulate Database throttling in JavaScript?

Sometime ago I had a code question in a take home test. It was as follows:
Database Throttling
You are given an array userInfo of user data and a function updateDB that takes a single user data argument. updateDB makes an asynchronous call that parses the user data and inserts the parsed data into a database. The database throttles requests so to make sure all user data is added to the database we need a function addAllUserData that calls updateDB on each entry in userInfo making sure never to exceed 7 calls per second to prevent being throttled.
var userInfo = [{'name':'antonio', 'username':'antonio_pavicevac_ortiz'}], dataBase = [];
function updateDB(singleUserDataArgument, callback){
dataBase.push(callback(singleUserDataArgument));
}
function addAllUserInfo(data) {
var eachUserData;
setInterval(function(){
eachUserData = data.map(data)
}, 7000);
}
As you can see by my attempt I am having a hard time wrapping my head around this exercise. Could anyone also inject what is meant by throttling in regards to async calls?
Thanks in advance!
// contains times at which requests were made
var callTimes = [];
function doThrottle(){
// get the current time
var time - new Date().getTime();
// filter callTimes to only include requests this second
callTimes = callTimes.filter(function(t){
return t > time-1000;
});
// if there were more than 7 calls this second, do not make another one
if(callTimes.length > 7) return true;
else{
// safe, do not throttle
callTimes.push(time);
return false;
}
}
// use like this
function makeRequest(){
if(doThrottle()){ /* too many requests, throttle */ }
else{ /* it's safe, make the ajax call*/ }
}

Setting a cron job for a Meteor Method

I have this piece of code:
Meteor.methods({
GetTickerInfo: function(){
Future = Npm.require('fibers/future');
var myFuture = new Future();
kraken.api('Ticker', {"pair": 'ETHXBT'}, function(error, data) {
if(error) {
console.log(error);
}
else {
console.log(data.result);
console.log(data.result.XETHXXBT.a);
myFuture.return(data.result);
}
});
console.log("EHEHEHEHEHHEEH");
console.log(myFuture.wait());
return myFuture.wait();
}
});
What it does it calls an API, gets some data back and when it's done it returns the data to the client so I can visualise in the graph. For now its a MANUAL click button on the client side which calls the method, does the job, and returns the data.
I would like to schedule a cron to do that. So every 5 sec make a API call and return the data back to the client (because there is where I visualise it). All the cron jobs are working with specific functions but I can't access the this function GetTickerInfo because it is defined and in the scope of Meteor.methods.
How can I call it be a cron job, but also leave the occasional Meteor Call from the client side when I want to manualy refresh in the given moment?
Can anyone show how would they implement this with for e.g. CRON package: percolatestudio/meteor-synced-cron
You have to be outside of the methods scope and I would personally do:
SyncedCron.add({
name: 'GetTickerInfo cron',
schedule: function(parser) {
return parser.text('every 5 seconds');
},
job: function() {
Meteor.call('GetTickerInfo');
}
});
SyncedCron.start()

Jquery - Multiple function calls to one AJAX call

I have a page that should load after the initial page load a bit of data trough AJAX that is then used in a few functions.
So far I can only get it to work with loading the AJAX requests separately (which means the same request is called like 30 times)
What I need is the possibility to have a function that can be called multiple times, but only activates the AJAX call once and the other times gives the data back without having again the same AJAX call that already gave the data back running (cause that's redundant and not needed, the data doesn't change).
Now I could do that by simply making a call and store it in a global variable and just check if something is in this variable or not...
BUT! The "but" is the problem, that these around 20 calls that need the information the AJAX delivers happen right after the DOM is loaded, right together with the AJAX call.
And so I cannot do that, because the 20 requests happen before the first AJAX call even finished showing all data.
I tried to do some stuff with JQueries "deferred", but could only manage to do it with one call and not with multiple calls at almost the same time without that it triggers the AJAX call everytime.
But I'm sure that must be possible somehow! Nicely, without some sort of loops and timeout. I really like the idea of loading pages and parts of pages partially. Input field isn't loaded right from the start, but gets delivered as soon as it is ready, etc...
Is it? I really can't wrap my head around this one...
$(function(){
loadme1();
loadme2(); /* loaded from complete different parts in the code, so not possible to start loadme2 only after loadme1 has everything finished */
});
function getData(){
return $.get("/pathtogetthedata", {}, function(data){
});
}
function loadme1(){
getData().done(function(data){
var obj = $.parseJSON(data);
/* do something with obj */
}
}
function loadme2(){
getData().done(function(data){ //please just wait till the first call to the same method finished and give me that data or wait till it's in a global variable and I take it from there. Only make a call if there is no jquery "promise" waiting
var obj = $.parseJSON(data);
/* do something with obj */
}
}
You have to keep all the "callback" and then when the data ready, to call the callback you just saved for example:
var funcs = []
function exampleOfAjaxGetData(callback) {
funcs.push(callback)
if (funcs.length == 1) {
setTimeout(function() {
alert('This is need to be called once1')
while (funcs.length > 0)
funcs.pop()('The data return from ajax')
}, 2000)
}
}
exampleOfAjaxGetData(function(x) {
alert('I got the data:' + x)
})
exampleOfAjaxGetData(function(x) {
alert('I got the data:' + x)
})
jsFiddle: http://jsfiddle.net/yn5ayw30/
In the example I show you a function that takes 2 seconds to complete.
I called the function twice. But the "setTimeout" run only once. When setTimeout complete, it will run all the function that wait for answer.
var getDataCalled = false;
var deferred = $.Deferred();
function getData(){
if(!getDataCalled) {
getDataCalled = true;
return $.get("/", {} , function(data) {
deferred.resolve(data);
});
} else {
console.log("returning deferred");
return deferred;
}
}
How about you save when you first call your "getData" function. When it has already been called you return your own "deferred" object back and resolve it when your first ajax request is finished.
I hope this short code snippet speaks for itself and is easy to understand.
Calling getData() will now first make the ajax request and after that always return a deferred object you created yourself.
getData().done(function(data) {
console.log(data);
});
getData().done(function(data) {
console.log(data);
});
getData().done(function(data) {
console.log(data);
});
You will see there will only be one ajax request.
I can think of one solution here it is :
var adata = -1; // global variable data holder
function getdata()
{
//if ajaxx call is already done and completed then return data
if(adata != -1 && adata != -2)return adata;
if(adata == -1)
{
//function getting called first time
adata = -2; // now we change value of adata to -2
// we will use this -2 to check if ajaxx call is stil running
//do ajaxx $.get call
$.get( "url_goes_here", function( data ) {
adata = data;// assingh received data to adata, so -2 is changed now
});
//now code will move to while loop part even after first call as while loop part doesn't have condition
//thus waiting for ajaxx call to be completed even if its first call
}
while(adata == -2){
//just a loop to delay output until call finishes
}
return adata;
}
Now you can use getdata() function to achieve what you want

Stopping Javascript timers

I'm trying to dynamically create PDFs on a webserver using PHP/wkhtmltopdf, which involves sending the PDF-generation process to the background in order to prevent the page timing out.
To check whether the job has completed successfully, I've used Javascript (which I suck at) and more specifically jQuery/AJAX to continuously query the server looking to see if wkhtmltopdf's process has ended. If its still running, the PHP script returns nothing and simply exits. If the process has ended successfully, a html link to the PDF is generated and then dumped into a <div></div>.
All the server side code works flawlessly however I'm stuck on the Javascript component. The code below kinda works but instead of the timer stopping after a PDF has been generated, it continues to query the server. How do I get it to stop?
$('#pdfmodal').on('shown', function () {
pdf(); // fire PDF generation process function
(function worker() {
$.ajax({
url: 'pdfpidcheck.php',
success: function(data) {
if(data == ''){
// Schedule the next request if nothing returned (i.e. still running)
setTimeout(worker, 5000);
} else {
// dump link to pdf
$('.pdfmodal').html(data);
}
}
});
})();
})
To stop a timer, you just remember the returned value from setTimeout() and call clearTimeout() on it.
var id = setTimeout(fn, 5000);
// then some time later
clearTimeout(id);
In the code you've shown us, this should not be an issue unless you are calling worker() from some other place than what you show us or unless the .on() handler gets called a second time while a PDF is being created. Your current code doesn't look like it knows how to handler two PDFs being created at the same time or a second even triggered while the first one is still processing.
You could protect against multiple timers running like this:
$('#pdfmodal').on('shown', function () {
var modal = $(this);
pdf(); // fire PDF generation process function
(function worker() {
$.ajax({
url: 'pdfpidcheck.php',
success: function(data) {
var timer = modal.data(timer);
if(data == ''){
// make sure we never have more than one timer running
if (timer) clearTimeout(timer);
// Schedule the next request if nothing returned
// (i.e. server process still running)
timer = setTimeout(worker, 5000);
// save timer for later use
modal.data("timer", timer);
} else {
// clean up timer data
if (timer) clearTimeout(timer);
modal.removeData("timer");
// dump link to pdf
$('.pdfmodal').html(data);
}
}
});
})();
})

get all JSON entries over x amount of calls

I'm accessing a json file which has 50 entries per page over x amount of pages.
I have the total number of entries, say 500 - which amounts to 10 pages.
I get the data from json file for page 1, pass the data to an array and then repeat the function but this time for page 2.
I have created the function and it loops perfectly incrementing and fetching each page, but it doesn't wait for the json data to be parsed and passed to the array before looping again.
Basically I want to wait until the data has been processed and then continue on.
My code so far is roughly this:
function getJsonData(metroID){
currentPageNo = 0;
totalPages = 'x';
count = 0;
function jsonLoop(){
meroAreaSearchString = 'http://jsonurl'+currentPageNo;
$.getJSON(meroAreaSearchString,{},function( data ){
if(totalPages == 'x'){
var totalEntries = data.resultsPage.totalEntries;
var perPage = data.resultsPage.perPage;
totalPages = (totalEntries/perPage);
log(totalEntries+', '+perPage+', '+totalPages);
log(Math.round(totalPages));
}
$.each(data.resultsPage.results.event, function(i,item){
var name = item.displayName;
var type = item.type;
var valueToPush = new Array();
valueToPush[0] = name;
valueToPush[1] = type;
valueToPush[3] = count;
locations.push(valueToPush);
count++;
});
});
if(currentPageNo == totalPages){
log(locations);
alert('finished processing all results');
}else{
currentPageNo++;
jsonLoop();
}
currentPageNo++;
jsonLoop();
}
}
Have you tried making the request syncronous?
Just put this piece of code at the top of your function getJsonData
$.ajaxSetup({async:false});
You can specify the async option to be false to get a synchronous Ajax request. This will stop your function until the callback set some data.
The $.getJSON() function fires off an AJAX request, and calls it's callback function when the AJAX call resolves successfully, if that makes any sense.
Basically, that just means that given a call $.getJSON(url,data,callback);, jQuery will fire an AJAX request to url passing data along with it, and call callback when that call resolves. Clear cut straightforward.
The thing you're missing here is that an AJAX call is just that -- as its name implies, its asynchronous. This means that throughout the whole lifetime of the AJAX call, it lets the other logic in your application run instead of waiting for it to finish.
So something like this:
$.getJSON(url, data, callback);
alert('foo');
... will most probably result in an alert() call happening before your AJAX call completes. I hope that made sense.
To make sure that something happens after your AJAX call completes, you put that logic inside the callback. That's really what the callback is for.
$.getJSON(url, data, function (d) {
something_you_want_done_after_ajax_call();
});
In the context of your problem, you just have to put all that conditional recalling of jsonLoop() into your callback. It's not very obvious right now because of your indenting, but it's currently outside your callback.

Categories