jqplot external data with async call? - ajax

Is there a way to load external data into jqplot with async call?
I want a live graph that updates every minute, but with async:false the page freezez every time when the data is recieving from server.

The reason it was done that way in the example was for simplicity's sake. The following is an async reworking of this:
var plot2 = null;
function fetchAjaxData(url, success) {
$.ajax({
url: url,
dataType:"json",
success: function(data) {
success(data);
console.log('loaded');
}
});
}
function createPlot(url) {
fetchAjaxData(url, function(data) {
if (plot2 == null) {
plot2 = $.jqplot('chart2', data, {
title: "AJAX JSON Data Renderer"
});
} else {
plot2.replot({data: data});
console.log('replotting');
}
});
}
$(document).ready(function(){
var jsonurl = "./jsondata.txt";
//Regenerate the plot on button click.
$('#ajax-button').click(function() {
createPlot(jsonurl);
});
//Generate the plot first time through.
createPlot(jsonurl);
});
And with HTML:
<div id="chart2" style="height:300px; width:500px;"></div>
<button id="ajax-button">Ajax retrieve</button>
So what this does is asynchronously fetch the data and plot it when the Ajax call succeeds. To keep it simple I am just reloading that same text file, though this could easily be adapted to scenarios where you are plotting a live data stream.

Related

Ajax wait on success before next iteration in .each loop

I have an ajax call inside a .each loop wrapped in a setInterval function.
This handles updating of many divs on a dashboard with just a few lines of code on the html page.
I am worried about server lag vs client side speed. What will happen if the server has not responded with the data before the loop moves on to the next iteration?
So, my question is, can the loop be paused until the success is executed?
Ajax call:
setInterval(function() {
$(".ajax_update").each(function(){
$.ajax({
type: "POST",
dataType: "json",
url: "ajax/automated_update/confirmed_appointments.php",
data: "clinic_id=<? echo $clinic_id ?>&tomorrow=<? echo $tomorrow ?>&"+$(this).data('stored'), // serializes the form's elements.
success: function(data)
{
$(data[0]).html(data[1]);
}
});
});
}, 5000); //5 seconds*
</script>
I have looked into .ajaxComplete() but I dont see how to apply this as a solution.
I have also looked at turning the loop into something that calls itself like:
function doLoop() {
if (i >= options.length) {
return;
}
$.ajax({
success: function(data) {
i++;
doLoop();
}
});
}
But would that not interfere with .each? I dont understand how that would play nice with .each and looping based on my div class.
I just cant figure it out! Any help would be appreciated.
I was able to get .when working with the ajax call, but I dont understand how to make .when do what I need (stop the loop until the ajax call is done).
$(".ajax_update").each(function(){
$.ajax({
type: "POST",
dataType: "json",
url: "ajax/automated_update/confirmed_appointments.php",
data: "clinic_id=<? echo $clinic_id ?>&tomorrow=<? echo $tomorrow ?>&"+$(this).data('stored'), // serializes the form's elements.
success: function(data)
{
$(data[0]).html(data[1]);
}
});
$.when( $.ajax() ).done(function() {
alert("Finished it");
});
});
After thinking about your question a bit, perhaps a good solution would be to put an event in place that would trigger a new set of updates with a minimum time between your dashboard updates. This would ensure that all your updates process, that we do wait a minimum time between updates and then trigger the update cycle once again. Thus if you DO encounter any delayed ajax responses you do not try another until the previous one has all completed.
I have not fully tested this code but is should do what I describe:
//create a dashboard object to handle the update deferred
var dashboard = {
update: function (myquery) {
var dfr = $.Deferred();
$.ajax({
type: "POST",
dataType: "json",
url: "ajax/automated_update/confirmed_appointments.php",
data: "clinic_id=<? echo $clinic_id ?>&tomorrow=<? echo $tomorrow ?>&" + myquery,
success: dfr.resolve
});
return dfr.promise();
}
};
//create a simple deferred wait timer
$.wait = function (time) {
return $.Deferred(function (dfd) {
setTimeout(dfd.resolve, time);
});
};
// use map instead of your .each to better manage the deferreds
var mydeferred = $(".ajax_update").map(function (i, elem) {
return dashboard.update($(this).data('stored')).then(function (data, textStatus, jqXHR) {
$(data[0]).html(data[1]);
});
});
//where I hang my dashboardupdate event on and then trigger it
var mydiv = $('#mydiv');
var minimumDashboardUpdate = 5000;
$('#mydiv').on('dashboardupdate', function () {
$.when.apply($, mydeferred.get())
.then(function () {
$.when($.wait(minimumDashboardUpdate)).then(function () {
mydiv.trigger('dashboardupdate');
});
});
});
mydiv.trigger('dashboardupdate');

Call ajax inside a custom method and return ajax result to called method

in my JSP I have link and button, for both I want to call Ajax action and use with result.
I am creating events for both link and button and calls Ajax. I need to return the result to the calling method.
//event for button
$(document).on('click', ".addComponent", function(){
var htmlContent=$(this).html();
$('.addComponent').html('Loading...').fadeIn();
var urlAction=$(this).attr("id");
var dataFields=$(this).data('val');
var data=callActionUsingAjax(urlAction, dataFields); //data not returning from ajax
var ajaxActionResult=ajaxResult(data);
$('.addComponent').html(htmlContent).fadeIn();
$('#popUpForm').html(ajaxActionResult);
$('#popUpForm').dialog("open");
return false;
});
//event for link
$(document).on('click', "#dimComponentList >TBODY > TR > TD > a", function(){
$("body").css("cursor", "progress");
var urlAction=$(this).attr("href");
var dataFields="";
var data=callActionUsingAjax(urlAction, dataFields);
var ajaxActionResult=ajaxResult(data); //ajax not returning data
$("body").css("cursor", "auto");
$('#applicationList').html(ajaxActionResult);
return false;
});
Here is my method to call Ajax
function callActionUsingAjax(urlAction,datafields)
{
$.ajax({
type: "post",
url: urlAction,
data: datafields,
success: function (data) {
return data;
}
});
}
I tried this link but I don't know how to use call back on my custom method like that. There are some other events also I need to call this Ajax. That's why I used Ajax inside a custom method.
Can anyone give me a solution?
The Ajax call is asynchronous and takes its time to complete, while the execution goes on and that's why you don't have any data in the "return".
You need to pass a callback function to your callActionUsingAjax and call it in your success handler (or complete or error that depends on the logic.
Like this:
$(document).on('click', ".addComponent", function(){
//... other stuff
callActionUsingAjax(urlAction, dataFields, function (data) { //this is tha callback (third argument)
var ajaxActionResult=ajaxResult(data);
$('.addComponent').html(htmlContent).fadeIn();
$('#popUpForm').html(ajaxActionResult);
$('#popUpForm').dialog("open");
// all of the above happens when ajax completes, not immediately.
});
return false;
});
function callActionUsingAjax(urlAction, datafields, callback)
{
$.ajax({
type: "post",
url: urlAction,
data: datafields,
success: function (data) {
callback(data);
}
});
}

if .get() data same on setInterval do nothing if different reload data

I have a DIV which is populated from $.get data on doc ready, I then call setInterval every 5 seconds. What im trying to do is on success of the setInterval $.get if the html data for #are_friends is the same as before do nothing but if its different then load the data to #are_friends again.
Does anybody have any idea how I would do this or a better way than Im trying to implement.
<div id="are_friends"></div>
<script type="text/javascript">
$(document).ready(function() {
$.get('<?php echo $siteUrl ?>are_friends.php?userid=<?php echo $userid; ?>', function(data) {
$("#are_friends").html(data);
});
var auto_refresh = setInterval(
function ()
{
$.ajax({
url: "<?php echo $siteUrl ?>are_friends.php?userid=<?php echo $userid; ?>",
success: function(newdata){
var oldcontent = $("#are_friends").html();
if(oldcontent != newdata) {
$("#are_friends").html(newdata);
}
}
});
}, 5000); // refresh every 5000 milliseconds
});
</script>
At least, you could reuse the function getting the data like this:
function getData(callback)
{
$.ajax({
url: "<?php echo $siteUrl ?>are_friends.php?userid=<?php echo $userid; ?>",
success: function(newdata){
callback(newdata);
}
});
}
$(document).ready(function()
{
getData(function(data)
{
$("#are_friends").html(data);
});
var auto_refresh = setInterval(function ()
{
getData(function(newdata)
{
if($("#are_friends").html() != newdata) {
$("#are_friends").html(newdata);
}
});
}, 5000);
});
Practically, the initial call and the subsequent call is the same, so why don't reuse it?
That is related a lot to data you are workign with. Right now you are just producing a lot of useless trafic. I would recommend to send also some marker of current state when you are requesting are_friends.php. PHP will check if something changed using that marker and return "no changes" or updated HTML. Here you should lower server load during if nothing is changed and less trafic(suppose most request will return "no changes"). But again. It depends on what you are doing in are_friends.php, what data do you need etc.

How to populate array with data returned from ajax call?

I'm making a call to an app to fetch data (routes), then looping through that data to fetch additional data about each individual route. The final data will show up in console.log without a problem, but I can't get it into an array.
$.getJSON('http://example-app/api/routes/?callback=?', function(data) {
var routes = [];
$(data).each(function(i){
routes.push(data[i]._id);
});
function getRouteData(route, callback) {
$.ajax({
url: 'http://example-app/api/routes/'+route+'?callback=?',
dataType: 'json',
success: function(data) {
callback(data);
}
});
}
var route_data = [];
$(routes).each(function(i) {
getRouteData(routes[i], function(data) {
console.log(data); // this shows me the 13 objects
route_data.push(data);
});
});
console.log(route_data); // this is empty
});
nnnnnn's right, you have to use Deferreds/promises to ensure that route_data is populated before sending it to the console.
It's not immediately obvious how to do this, with particular regard to the fact that $.when() accepts a series of discrete arguments, not an array.
Another issue is that any individual ajax failure should not scupper the whole enterprise. It is maybe less than obvious how to overcome this.
I'm not 100% certain but something along the following lines should work :
$.getJSON('http://example-app/api/routes/?callback=?', function(data) {
var route_promises = [];
var route_data = [];
function getRouteData(route) {
var dfrd = $.Deferred();
$.ajax({
url: 'http://example-app/api/routes/'+route+'?callback=?',
dataType: 'json'
}).done(function(data) {
//console.log(data); // this shows me the 13 objects
route_data.push(data);
}).fail(function() {
route_data.push("ajax error");
}).then(function() {
dfrd.resolve();
});
return dfrd.promise();//By returning a promise derived from a Deferred that is fully under our control (as opposed to the $.ajax method's jqXHR object), we can guarantee resolution even if the ajax fails. Thus any number of ajax failures will not cause the whole route_promises collection to fail.
}
$(data).each(function(i, route) {
route_promises.push( getRouteData(route) );
});
//$.when doesn't accept an array, but we should be able to use $.when.apply($, ...), where the first parameter, `$`, is arbitrary.
$.when.apply($, route_promises).done(function() {
console.log(route_data);
});
});
untested
See comments in code.

jQuery.ajax() sequential calls

Hey. I need some help with jQuery Ajax calls. In javascript I have to generste ajax calls to the controller, which retrieves a value from the model. I am then checking the value that is returned and making further ajax calls if necessary, say if the value reaches a particular threshold I can stop the ajax calls.
This requires ajax calls that need to be processes one after the other. I tried using async:false, but it freezes up the browser and any jQuery changes i make at the frontend are not reflected. Is there any way around this??
Thanks in advance.
You should make the next ajax call after the first one has finished like this for example:
function getResult(value) {
$.ajax({
url: 'server/url',
data: { value: value },
success: function(data) {
getResult(data.newValue);
}
});
}
I used array of steps and callback function to continue executing where async started. Works perfect for me.
var tasks = [];
for(i=0;i<20;i++){
tasks.push(i); //can be replaced with list of steps, url and so on
}
var current = 0;
function doAjax(callback) {
//check to make sure there are more requests to make
if (current < tasks.length -1 ) {
var uploadURL ="http://localhost/someSequentialToDo";
//and
var myData = tasks[current];
current++;
//make the AJAX request with the given data
$.ajax({
type: 'GET',
url : uploadURL,
data: {index: current},
dataType : 'json',
success : function (serverResponse) {
doAjax(callback);
}
});
}
else
{
callback();
console.log("this is end");
}
}
function sth(){
var datum = Date();
doAjax( function(){
console.log(datum); //displays time when ajax started
console.log(Date()); //when ajax finished
});
}
console.log("start");
sth();
In the success callback function, just make another $.ajax request if necessary. (Setting async: false causes the browser to run the request as the same thread as everything else; that's why it freezes up.)
Use a callback function, there are two: success and error.
From the jQuery ajax page:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
// Do processing, call function for next ajax
}
});
A (very) simplified example:
function doAjax() {
// get url and parameters
var myurl = /* somethingsomething */;
$.ajax({
url: myurl,
context: document.body,
success: function(data){
if(data < threshold) {
doAjax();
}
}
});
}
Try using $.when() (available since 1.5) you can have a single callback that triggers once all calls are made, its cleaner and much more elegant. It ends up looking something like this:
$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1, a2){
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively
var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
alert( jqXHR.responseText )
});

Resources