How to make ajax success callback data available globally? - javascript

So i'have some data returned from a rails backend, and i would like to make those data available globally, i have read about windows.variable = success callback data but i have to set async:false on ajax request which is now deprecated and does not work.
Is there a new workaround on that?
here is my ajax code
function retrieve(date_partial) {
var jsondata = {
events: {
month: date_partial,
}
}
$.ajax({
cache: false,
type: "POST",
url: "/events/find",
data: jsondata,
success: function(data) {
for (var i = 0; i < data.events.length; i++) {
var day = data.events[i].date.substring(0, 2);
$("td[data-day='" + day + "']").addClass('added');
}
},
error: function(xhr) {
alert("The error code is: " + xhr.statusText);
}
});
}

i have read about windows.variable
That's exactly how you make a value available globally in JavaScript, setting it on the window object. Something like this:
window.someVariable = someValue;
but i have to set async:false on ajax request
You absolutely should not do that. It also has nothing to do with what you're asking. The window object is always available, that's what makes it global:
success: function(data) {
window.someVariable = data.someValue;
}
Once the callback runs, window.someVariable would contain the value and would be available to any other code on the page.

Related

Why is my Ajax callback being processed too soon?

I have a general ajax function which I'm calling from loads of places in my code. It's pretty standard except for some extra debugging stuff I've recently added (to try to solve this issue), with a global 'ajaxworking' variable:
rideData.myAjax = function (url, type, data, successfunc) {
var dataJson = JSON.stringify(data),
thisurl = quilkinUrlBase() + url;
if (ajaxworking.length > 0) {
console.log(thisurl + ": concurrent Ajax call with: " + ajaxworking);
}
ajaxworking = thisurl;
$.ajax({
type: type,
data: dataJson,
url: thisurl,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (response) {
ajaxworking = '';
successfunc(response);
},
error: webRequestFailed
});
};
Now, there's one section of my code where a second ajax call is made depending on the result of the first:
getWebRides = function (date) {
var rideIDs = [];
var intdays = bleTime.toIntDays(date);
rideData.myAjax("GetRidesForDate", "POST", intdays, function (response) {
rides = response;
if (rides.length === 0) {
$('#ridelist').empty(); // this will also remove any handlers
qPopup.Alert("No rides found for " + bleTime.DateString(date));
return null;
}
$.each(rides, function (index) {
rideIDs.push(rides[index].rideID);
});
GetParticipants(rideIDs);
});
},
'GetParticipants' (which also calls 'myAjax') works fine - most of the time. But in another part of my code, 'GetWebRides' is itself called directly after another ajax call - i.e. there are 3 calls, each successive one depending on the previous. The 'top-level' call is as follows:
rideData.myAjax("SaveRide", "POST", ride, function (response) {
// if successful, response should be just a new ID
if (response.length < 5) {
// document re-arrangement code snipped here for brevity
getWebRides(date);
}
else {
qPopup.Alert(response);
}
});
so, only when there are three successive calls like this, I'm getting the 'concurrent' catch in the third one:
GetParticipants: concurrent call with GetRidesForDate
and (if allowed to proceed) this causes a nasty probem at the server with datareaders already being open. But why is this only occurring when GetParticipants is called as the third in the chain?
I see, after some research. that there are now other ways of arranging async calls, e.g. using 'Promises', but I'd like to understand what's going on here.
Solved this.
Part of the 'document re-arrangement code' that I had commented out for this post, was in fact calling another Ajax call indirectly (very indirectly, hence it took a long time to find).

How to create callback function using Ajax?

I am working on the jquery to call a function to get the return value that I want to store for the variable email_number when I refresh on a page.
When I try this:
function get_emailno(emailid, mailfolder) {
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
email_number = data;
}
});
return email_number;
}
I will get the return value as 6 as only when I use alert(email_number) after the email_number = data;, but I am unable to get the value outside of a function.
Here is the full code:
var email_number = '';
// check if page refreshed or reloaded
if (performance.navigation.type == 1) {
var hash = window.location.hash;
var mailfolder = hash.split('/')[0].replace('#', '');
var emailid = 'SUJmaWg4RTFRQkViS1RlUzV3K1NPdz09';
get_emailno(emailid, mailfolder);
}
function get_emailno(emailid, mailfolder) {
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
email_number = data;
}
});
return email_number;
}
However, I have been researching and it stated that I would need to use callback via ajax but I have got no idea how to do this.
I have tried this and I still don't get a return value outside of the get_emailno function.
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
async: true,
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
email_number = data;
}
});
I am getting frustrated as I am unable to find the solution so I need your help with this. What I am trying to do is I want to call on a get_emailno function to get the return value to store in the email_number variable.
Can you please show me an example how I could use a callback function on ajax to get the return value where I can be able to store the value in the email_number variable?
Thank you.
From the jquery documentation, the $.ajax() method returns a jqXHR object (this reads fully as jquery XMLHttpRequest object).
When you return data from the server in another function like this
function get_emailno(emailid, mailfolder) {
$.ajax({
// ajax settings
});
return email_number;
}
Note that $.ajax ({...}) call is asynchronous. Hence, the code within it doesn't necessarily execute before the last return statement. In other words, the $.ajax () call is deferred to execute at some time in the future, while the return statement executes immediately.
Consequently, jquery specifies that you handle (or respond to) the execution of ajax requests using callbacks and not return statements.
There are two ways you can define callbacks.
1. Define them within the jquery ajax request settings like this:
$.ajax({
// other ajax settings
success: function(data) {},
error: function() {},
complete: function() {},
});
2. Or chain the callbacks to the returned jqXHR object like this:
$.ajax({
// other ajax settings
}).done(function(data) {}).fail(function() {}).always(function() {});
The two methods are equivalent. success: is equivalent to done(), error: is equivalent to fail() and complete: is equivalent to always().
On when it is appropriate to use which function: use success: to handle the case where the returned data is what you expect; use error: if something went wrong during the request and finally use complete: when the request is finished (regardless of whether it was successful or not).
With this knowledge, you can better write your code to catch the data returned from the server at the right time.
var email_number = '';
// check if page refreshed or reloaded
if (performance.navigation.type == 1) {
var hash = window.location.hash;
var mailfolder = hash.split('/')[0].replace('#', '');
var emailid = 'SUJmaWg4RTFRQkViS1RlUzV3K1NPdz09';
get_emailno(emailid, mailfolder);
}
function get_emailno(emailid, mailfolder) {
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
// sufficient to get returned data
email_number = data;
// use email_number here
alert(email_number); // alert it
console.log(email_number); // or log it
$('body').html(email_number); // or append to DOM
}
});
}

I need to return value from ajax

I need to return value from ajax but it filled 0 every time and didn't wait for ajax process finished
var itemId=0; as global value
getitemIDbyProductID(productId,getitemIDbyProductID_success);
alert(itemID + "itemgeted")
I did this
function getitemIDbyProductID(productId, callback) {
$.ajax({
type: "POST",
url: "Cot.aspx/getitemIDbyProductID",
data: JSON.stringify({ productId: productId }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var value = 0;
value = JSON.parse(result.d);
itemID=callback(value)
callback(value);
},
error: function (msg) { }
});
}
function getitemIDbyProductID_success(total_percentage) {
alert(total_percentage +"fds"+itemID);
}
but it didn't wait the ajax finished and gives me the itemId = undefiend
You're successfully setting the value here:
function getitemIDbyProductID_success(total_percentage) {
itemID = total_percentage;
alert(total_percentage +"fds"+itemID);
}
But then, in the code which calls this, you're successfully setting it again:
itemID=callback(value)
Since your getitemIDbyProductID_success doesn't return anything, the return value is undefined. So basically you're unsetting itemID immediately after setting it.
Just invoke the callback, don't use its (non-extant) return value:
callback(value);
Additionally, this isn't going to do what you think:
getitemIDbyProductID(productId,getitemIDbyProductID_success);
alert(itemID + "itemgeted");
Because getitemIDbyProductID performs an asynchronous operation. Even once the above errors are corrected, this error still remains. And this one is a duplicate of a very popular question (with answers far better than I can provide) here.
You can do something like this:
getitemIDbyProductID(productId,function(val){
itemID = val;
alert(itemID + "itemgeted");
});
Basically, you have to wait before the itemID gets assigned right value.

Parallel Ajax Calls in Javascript/jQuery

I am completely new to Javascript/jquery world and need some help. Right now, I am writing one html page where I have to make 5 different Ajax calls to get the data to plot graphs. Right now, I am calling these 5 ajax calls like this:
$(document).ready(function() {
area0Obj = $.parseJSON($.ajax({
url : url0,
async : false,
dataType : 'json'
}).responseText);
area1Obj = $.parseJSON($.ajax({
url : url1,
async : false,
dataType : 'json'
}).responseText);
.
.
.
area4Obj = $.parseJSON($.ajax({
url : url4,
async : false,
dataType : 'json'
}).responseText);
// some code for generating graphs
)} // closing the document ready function
My problem is that in above scenario, all the ajax calls are going serially. That is, after 1 call is complete 2 starts, when 2 completes 3 starts and so on .. Each Ajax call is taking roughly around 5 - 6 sec to get the data, which makes the over all page to be loaded in around 30 sec.
I tried making the async type as true but in that case I dont get the data immediately to plot the graph which defeats my purpose.
My question is:
How can I make these calls parallel, so that I start getting all this data parallely and my page could be loaded in less time?
Thanks in advance.
Using jQuery.when (deferreds):
$.when( $.ajax("/req1"), $.ajax("/req2"), $.ajax("/req3") ).then(function(resp1, resp2, resp3){
// plot graph using data from resp1, resp2 & resp3
});
callback function only called when all 3 ajax calls are completed.
You can't do that using async: false - the code executes synchronously, as you already know (i.e. an operation won't start until the previous one has finished).
You will want to set async: true (or just omit it - by default it's true). Then define a callback function for each AJAX call. Inside each callback, add the received data to an array. Then, check whether all the data has been loaded (arrayOfJsonObjects.length == 5). If it has, call a function to do whatever you want with the data.
Let's try to do it in this way:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
var area0Obj = {responseText:''};
var area1Obj = {responseText:''};
var area2Obj = {responseText:''};
var url0 = 'http://someurl/url0/';
var url1 = 'http://someurl/url1/';
var url2 = 'http://someurl/url2/';
var getData = function(someURL, place) {
$.ajax({
type : 'POST',
dataType : 'json',
url : someURL,
success : function(data) {
place.responseText = data;
console.log(place);
}
});
}
getData(url0, area0Obj);
getData(url1, area1Obj);
getData(url2, area2Obj);
});
</script>
if server side will be smth. like this:
public function url0() {
$answer = array(
array('smth' => 1, 'ope' => 'one'),
array('smth' => 8, 'ope' => 'two'),
array('smth' => 5, 'ope' => 'three')
);
die(json_encode($answer));
}
public function url1() {
$answer = array('one','two','three');
die(json_encode($answer));
}
public function url2() {
$answer = 'one ,two, three';
die(json_encode($answer));
}
So there, as you can see, created one function getData() for getting data from server and than it called 3 times. Results will be received in asynchronous way so, for example, first can get answer for third call and last for first call.
Console answer will be:
[{"smth":1,"ope":"one"},{"smth":8,"ope":"two"},{"smth":5,"ope":"three"}]
["one","two","three"]
"one ,two, three"
PS. please read this: http://api.jquery.com/jQuery.ajax/ there you can clearly see info about async. There default async param value = true.
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active...
The following worked for me - I had multiple ajax calls with the need to pass a serialised object:
var args1 = {
"table": "users",
"order": " ORDER BY id DESC ",
"local_domain":""
}
var args2 = {
"table": "parts",
"order": " ORDER BY date DESC ",
"local_domain":""
}
$.when(
$.ajax({
url: args1.local_domain + '/my/restful',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
type: "POST",
dataType : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(args1),
error: function(err1) {
alert('(Call 1)An error just happened...' + JSON.stringify(err1));
}
}),
$.ajax({
url: args2.local_domain + '/my/restful',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
type: "POST",
dataType : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(args2),
error: function(err2) {
calert('(Call 2)An error just happened...' + JSON.stringify(err2));
}
})
).then(function( data1, data2 ) {
data1 = cleanDataString(data1);
data2 = cleanDataString(data2);
data1.forEach(function(e){
console.log("ids" + e.id)
});
data2.forEach(function(e){
console.log("dates" + e.date)
});
})
function cleanDataString(data){
data = decodeURIComponent(data);
// next if statement was only used because I got additional object on the back of my JSON object
// parsed it out while serialised and then added back closing 2 brackets
if(data !== undefined && data.toString().includes('}],success,')){
temp = data.toString().split('}],success,');
data = temp[0] + '}]';
}
data = JSON.parse(data);
return data; // return parsed object
}
In jQuery.ajax you should provide a callback method as below:
j.ajax({
url : url0,
async : true,
dataType : 'json',
success:function(data){
console.log(data);
}
}
or you can directly use
jQuery.getJSON(url0, function(data){
console.log(data);
});
reference
You won't be able to handle it like your example. Setting to async uses another thread to make the request on and lets your application continue.
In this case you should utilize a new function that will plot an area out, then use the callback functions of the ajax request to pass the data to that function.
For example:
$(document).ready(function() {
function plotArea(data, status, jqXHR) {
// access the graph object and apply the data.
var area_data = $.parseJSON(data);
}
$.ajax({
url : url0,
async : false,
dataType : 'json',
success: poltArea
});
$.ajax({
url : url1,
async : false,
dataType : 'json',
success: poltArea
});
$.ajax({
url : url4,
async : false,
dataType : 'json',
success: poltArea
});
// some code for generating graphs
}); // closing the document ready function
It looks like you need to dispatch your request asynchronously and define a callback function to get the response.
The way you did, it'll wait until the variable is successfully assigned (meaning: the response has just arrived) until it proceeds to dispatch the next request. Just use something like this.
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(data) {
area0Obj = data;
}
});
This should do the trick.
Here's a solution to your issue: http://jsfiddle.net/YZuD9/
you may combine all the functionality of the different ajax functions into 1 ajax function, or from 1 ajax function, call the other functions (they would be private/controller side in this case) and then return the result. Ajax calls do stall a bit, so minimizing them is the way to go.
you can also make the ajax functions asynchronous (which then would behave like normal functions), then you can render the graph at the end, after all the functions return their data.

Wait for AJAX before continuing through separate function

Alright... at 2am, this is where I draw the line. Help... before my laptop ends up going out the window. :)
I've tried using setTimer, callbacks, and everything else I can think of (along with a few other Stackoverflow hints of course). I've stripped out everything so I'm leaving just the base code.
What I'm looking to do is call parseRow() and before it saves the record at the end, I need to grab the associated Category (via AJAX); however, it blows right past it so category is always "undefined".
function parseRow(row){
var rowArray = row.trim().split(",");
var date = rowArray[0];
var checknum = rowArray[1];
var payee = rowArray[2];
var memo = rowArray[3];
var amount = rowArray[4];
//ERROR: blows right past this one and sets the category variable BEFORE ajax returns
var category = autoSelectCategory(payee);
saveRecord(date, checkNum, payee, memo, category, payment, deposit);
}
function autoSelectCategory(payee) {
var data;
$.ajax({
async: false,
url: "autoselectcategory",
dataType: "json",
data: {
string: payee
},
success: function (returnedData) {
data = returnedData;
}
});
return data;
}
AJAX stands for asynchronous. That means that in your original code, saveRecord will be executed before the client will receive the response from the server (and, depending on the $.ajax implementation, it might be before the client will send the request to the server).
Additionally, you seem to misunderstand how functions work in JS. var category = autoSelectCategory(payee); will set the category to the return value of autoSelectCategory; but the autoSelectCategory function in your code returns nothing.
From the other side, the data return value of your anonymous function could only be used by $.ajax function (and $.ajax likely ignores the success parameter return value).
Here is the code that should work:
function parseRow(row){
var rowArray = row.trim().split(",");
var date = rowArray[0];
var checknum = rowArray[1];
var payee = rowArray[2];
var memo = rowArray[3];
var amount = rowArray[4];
autoSelectCategory(payee, function (category) {
saveRecord(date, checkNum, payee, memo, category, payment, deposit);
});
}
function autoSelectCategory(payee, callback) {
$.ajax({
async: false,
url: "autoselectcategory",
dataType: "json",
data: {
string: payee
},
success: callback
});
}
Do not use async: false option. It's a pure evil (blocks all scripts in browser and even other tabs!) and it's deprecated since jQuery 1.8. You should use callbacks as it was always meant to be.
function parseRow(row) {
/* the other code */
autoSelectCategory(payee, function() {
saveRecord(date, checkNum, payee, memo, category, payment, deposit);
});
}
function autoSelectCategory(payee, callback) { // <---- note the additional arg
$.ajax({
url: "autoselectcategory",
dataType: "json",
data: {
string: payee
},
success: function(res) {
/* the other code */
callback();
}
});
}

Categories

Resources