Restrictions of Multiple AJAX Calls? - javascript

Context:
I have a javascript file, within i have an AJAX function calling a php file returning the data and performing a function with it(an sql query returning records for a set date, then plotting it on a map using the google maps API). Lets call this Data A
Question:
What i need is to be able to get the next days data and storing it in an array (Lets call it Data B) and comparing it with the first set of data(Data A).
From my understanding i need another ajax call within this one, iv tried it but it seems i cannot get the data, i may have a misunderstanding of the core workings of ajax. For example:
var data_a;
var data_b;
$.ajax({
type: "POST",
url: scriptday,
data: $("#dayForm").serialize(),
error: function( data ) {
console.log("Error: "+ data );
},
success: function( json ) {
data_a = json
//start of inner ajax call
$.ajax({
type: "POST",
url: scriptday2,
data: $("#dayForm").serialize(),
error: function( data ) {
console.log("Error: "+ data );
},
success: function( json ) {
data_b = json
// access data_a here
}
}
});
//end of inner ajax call
}
});
EDIT:
Correct way of doing this was to store inner ajax call in a function that takes data_a inside.
function innerAjax(data_a){
$.ajax({
.....
//data_a can now be used here
})
}
and to call it inside the first ajax as
innerAjax(data_a);
this way using AJAX in a synchronous way :)
thanks to those who contributed!

No, restrictions of multiple AJAX calls do not exist, if you use async ajax (and looks like you do).
For you problem - perhaps you need to wait correctly for result of both ajax calls, to store the results and then process them.

Related

Display Flask JSON datas with Jquery

I'm trying to display json data coming from my flask function.
I can use getJson method to get those datas but getJSon work with action like click or change.
getJSon return data but i can't use use them out of the function.
For example
$.getJSON('../admin/graphe_1', {
}, function(data) {
chart.data = data
console.log(data)
});
console.log(chart.data)
The first console log display data but the second one display nothing.
How can I do to get this data out of the function ?
Reason is getJSON function is asynchronous. So your second console.log prints the data before actually loaded into your app. So it prints null probably. The first console.log is in the function which executed right after completing loading data successfully. So it should print correct data. If you want to do stuff after loading data successfully do it in the done function which contains your first console.log. if you want synchronous execution use,
$.ajax({
dataType: "json",
url: url,
async: false,
data: data,
success: function (data){
chart.data=data;
}
});
console.log(chart.data); // data should be loaded
This is not recommend since it blocks UI thread.

Aborting / canceling running AJAX calls before execute new AJAX in JS

I've never done this type of manipulation of AJAX calls (to stop/abort/cancel or ignore? already running AJAX calls before the execution of a new one) before so I really don't understand how to do that and would appreciate some direction.
I have a page in my app where I make a number of AJAX calls to fill dynamically the data in my table (Object Name, Object Fit, Object Progress) when the page loads. For example, there are 5 rows in the table. So I call
$.post("/getFit", {objectId: objectId}, function (result) { manipulation with result }
and
$.post("/getProgress", {objectId: objectId}, function (result) { manipulation with result }
5 times each in the loop -- one for each of the objects.
The first column of my table has links to more detail on the object, and clicking on them I call another AJAX:
$(document).off('click', '.js_object').on('click', '.js_object', function (e) {
var objectId = $(this).attr("id")
$.post("/viewObject", {objectId: objectId}, function (result) {document.getElementById("main_window_content").innerHTML = result; });
})
The problem is that the browser will not render the results of the last AJAX call (/viewObject) until it has received the results of all of the previous calls (/getFit x5 and /getProgress x5).
As a result, a user that wants to drill into the detail on an object needs to wait until the AJAX calls for the other objects are complete before they see anything.
So I struggle with how to stop/abort/cancel (or ignore?) "/getProgress" and "/getFit" so we can fully execute "/viewObject" and view the results of it.
I would very much appreciate your help.
Use xhr.abort() to kill the xhr requests as shown in the below code in JS. I believe there is ajax.abort(); in JQuery
var xhr = $.ajax({
type: "POST",
url: "XXX.php",
data: "name=marry&location=London",
success: function(msg){
alert( "The Data Saved: " + msg );
}
});
//kill the request
xhr.abort()
If you want execute one ajax after another, and you need all requests to work to show the final result, you can use .done():
$.ajax({
url:'/getFit',
data:{objectId:objectId}
})
.done(function(data){
//do something with the results then call /getProgress
$.ajax({
url:'/getProgress',
data:{objectId:objectId}
})
.done(function(data){
//do something with the results then call /viewObject
$.post("/viewObject"....
})
});
That way you only show /viewObject if the others calls were successfull

Asynchronous Lazy Loading

currently, we are using the SAP HANA Database. To get data, we will use a Node.JS-API, which we will call via AJAX, to get the advantages by async. So here is the problem:
We have many pages where we need the same data (e.g. customer data). To do so, I wanted to create a Library, which does the actual data calls, so that i just need to call db.getCustomer([ID]). In order to get a return value from AJAX, I have to set async: false within the AJAX call.
My question is now, is it possible to create a data-call-library asynchronously? Is it a good practice to encapsulate the databinding (using so called DAO)?
I'm a bit confused, because another dev told me to just use the same AJAX-call over and over again, to not loose the async and it is a better practice anyway.
Here is my actual AJAX-call as an example:
getCustomer: function( CID ) {
var aUrl = 'http://example.com/api/customer/' + CID,
returnData
;
jQuery.ajax({
url: aUrl,
method: 'GET',
dataType: 'json',
contentType: "application/json",
async: false,
success: function(data) {
returnData = data;
}
});
return returnData;
},
// other ajax calls
// to get the data via 1-liner
thank you for clarification!
Actually, it makes no sense to return data from a callback in a synchronous function; normally, you would store the returned callback data into your model, so your view/controller gets automatically updated.
If you really need your method to return async data, have a look at Deferred or Promises

Using JSONP and I have 'ReferenceError: data not defined'

I've got a problem with displaying JSON data called via JSONP. I've got a complex JSON file delivered cross domain via a URL and I'm quite the novice at JSON and ajax. I followed a JSONP article here at https://learn.jquery.com/ajax/working-with-jsonp/ and that worked a treat. Now I am trying to iterate through the JSON object and display data in the HTML page after following this question How do I iterate through this JSON object in jQuery? and I'm not going anywhere. The data is not defined and I'm not sure what I am doing wrong:
// Using LibCal and JSONP
$.ajax({
url: "https://api2.libcal.com/1.0/room_bookings_nickname/?iid=3356&group_id=12306&key=92a47e5c854dee620cca071648c3fc41",
// The name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// Tell jQuery we're expecting JSONP
dataType: "jsonp",
// Tell LibCal what we want and that we want JSON
data: {
q: "select Room name,booked timeslots,booking name from LibCal room bookings",
format: "json"
},
// Work with the response
success: function( response ) {
console.log( response ); // server response
}
});
$.each(data.bookings, function(index, element) {
alert(element.timeslots.room_name);
});
I hope it's an obvious fix to a more advanced user our there :)
Thats because your data object doesn't exist. The data key you're referring to is a on the object you're passing to the $.ajax method.
You need to execute your function inside the success callback in order for it make any sense.
$.ajax({
...
// keep all your original stuff
...
success: function( response ) {
var data = response;
$.each(data.bookings, function(index, element) {
alert(element.timeslots.room_name);
});
}
});
I did the request like this. You need to go one level more to access the array to loop.
var json_url = "https://api2.libcal.com/1.0/room_bookings_nickname/?iid=3356&group_id=12306&key=92a47e5c854dee620cca071648c3fc41"
$.ajax({
url: json_url,
crossDomain:true,
dataType:"jsonp"
}).done(function(response) {
// at the end of request
//Yours --->response.bookings
//Mine --->response.bookings.timeslots
//access the array to loop
var rooms = response.bookings.timeslots;
$.each(rooms, function(index, element) {
create_elem(element.room_name, index);
});
});
Here is a working version in jsFiddle - https://jsfiddle.net/9e746pkh/
Hope this helps.

how to access input data submitted to ajax request (NOT return data) via jQuery

I'm trying to retrieve the data I submitted to an asynchronous ajax request should the back-end fail in some way. The data in 'myJSONData' is actually pulled off a queue (array) in memory and I need to put it back into the queue if any kind of error occurs.
e.g.
var myJSONData = {"parm1":"value1","parm2":"value"};
$.ajax({
type: "POST",
url: "/postData.ajax",
dataType: "json",
data: myJSONData,
success: function(jsonReply) {
// I need to refer to the posted data here (i.e. myJSONData)
},
error: function(xhr,ajaxOptions,thrownError) {
// I need to refer to the posted data here (i.e. myJSONData)
}
});
My code fires off a number of calls at various times, the trouble is that if I refer to myJSONData within the success or error blocks it contains the most recent value of that variable in memory, and not what was in the variable at the time of the ajax call.
Is there some other way to access the data associated with the particular instance of ajax call - something like $.ajax.data ?
You should be able to access it in your success and error functions :
success: function(jsonReply) {
var p1 = myJSONData.param1;
}

Categories