I am making multiple Ajax calls to retrieve insurance quotes from different providers with the intention of aggregating and sorting the results. My simplified code looks like this:
for (var i = 0; i < providerList.length; i++) {
$.ajax({
url : "quote-request/"+ providerList[i] +".php",
type: "GET",
data : formData,
dataType:"json",
success: function(results) {
$.each(results, function(index, value) {
$("#results").append("<div>" + value["provider-name"] + value["policy-name"] + value["grand-total"] + "</div>");
})
}
});
}
Which produces:
<div id="results">
<div>ProviderA Policy1 12.34</div>
<div>ProviderA Policy2 9.50</div>
<div>ProviderB Policy1 22.76</div>
</div>
However I would like the results to be ordered in ascending order of grand-total as each Ajax call finishes so each new result is automatically inserted in the correct place:
<div id="results">
<div>ProviderA Policy2 9.50</div>
<div>ProviderA Policy1 12.34</div>
<div>ProviderB Policy1 22.76</div>
</div>
The only way I can think of doing this is to save each result to an array after every Ajax call, then sort the array and output the results but it seems slightly redundant to keep building and outputting the same array every time a new quote is retrieved. Is there a better way of doing this?
To clarify, the final script will make around 10 Ajax calls and load around 40 results so we are not talking huge datasets here. Also it is possible that one or more quotes will have the same grand-total, in which case it is not important which comes first. Each quote will also have a unique identifier, policy-id if this is useful here.