I need and Advice here.
I have this situation, trying to get some JSON Data, thought the AJAX (using jQuery).
The idea is it, I need more data then 1 or 2 Ajax Call to get all data what I need.
So, I need to make multi Ajax Calls and I try to find out the best way to do that (The best practice).
One idea which came first in my head is something like this (it can have some syntax erros or even something worse, looking for a logic for now):
var dataArr = {
page:0,
pageSize : 1000
};
var StoreData = [];
var getSomeData = function () {
$.ajax({
type : "GET",
url : URL,
data : dataArr,
dataType : "json",
error : OnLoadError,
success :function(data, status){
StoreData.push[data];
if(data.length){
dataArr.page = dataArr.page + 1
getSomeData();
}
}
});
};
Additional info:
It can be around 4-9 Ajax call to gett all data which is (4000-9000 items).
I tested pageSize : 1000
and works fine so I can get for sure 1000 items per call.
So if you can help me with some advice, some changes in existing one or another better way to do that, or even some example, I really appreciate
Thanks Everyone !
You could set a flag at the serverside when finished and put that into your status parameter for the success function. That would clean up your code. Otherwise you could simply add a while loop, define your calls as synchronous and check if its finished within the loop condition.
First of all, you need to optimize page size. Defining it as 1000 is the easy way. If performance of the application is not important, don't read the rest of this answer :)
I suggest a trial-and-error based approach. Make a for loop, try different numbers for page-size (like 20, 50, 100, 500, 1000, 1500 etc). Then log number of requests for each page size, and total time for all requests. Compare those numbers, and select your page size wisely.
Secondly, if you are able to count the number of elements coming from server, then you may not have to send the unnecessary request at last. Assume you are getting 4650 data. You get 1000, + 1000, +1000, +1000 and +650. If you somehow figure out you are getting less than 1000, you wouldn't send the last request, would you? Suppose the response format is something like:
<li class='item'>XXX</li>
// All list items
<li class='item'>YYY</li>
Then count the number of li's with jquery, and if it is less than your page size, it means that you get all the data you need.
Lastly, if you know your total data has length more than 4000, you may want to send the first 4 requests asynchronously.