Loading data in an asynchronous way AJAX

I am creating graphs using data pulled from my server that connects to an API to get the data. The user can add various things to the graph. When they add something, the graph must be updated with the selected thing on the graph. This seems be very slow if I had to do this asynchronously (As in, when the user clicks something I have to request the same data set from the API, and the send it to the client with the new addition, which takes about 4-5 seconds). So, I decided to do this synchronously like so:

function getData() {
    $.post("/data", { serverData: serverData }, function(data, success){ 
    return data;

Then the user can add things to the graph using the data from getData(), which is stored in a global.

function updateGraph(dataFromServer) {
    //create the addition using the data.

Updating the graph with new things is now instant, because I have the data.
The issue is that there are about five different data sets (and it seems that in this project this number is expected to grow) that can be used to create graphs. When a new data set is selected, the old graph is replaced by the new graph made with the selected data set. I currently have a dropdown menu that the user can use to select different data sets, so when they currently click on a different data set the dropdown menu bar freezes, because the getData() call is synchronous, until the new data loads.

Because I have to go through their API, this delay is about 4-5 seconds which looks terrible. Is there a way to get the data asynchronously and still be able to load the user additions asynchronously as well? I currently think it would like this:

function getDataAndUpdateGraph() {
    $.post("/data", { serverData: serverData }, function(data, success){ 
        updateGraph(data); //the function in the previous code snippet.

And like I said, this won’t work if I have to call this with every new thing the user adds to the graph. Tell me if I simply have to live with the delay here, as the priority is the graph additions, which are made instant with the synchronous function.

Source: ajax

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.