0

I am starter at programming and i'm stuck at the moment. Let's take a look my code:

        $.ajax({
            url: "http://example.com/mydataset.json?example1="+variable1,
            type: "GET",
            data: {
              "$limit" : 5000
            }
        }).done(function(data) {
                console.log(data.options);
                variable2 = data.options;
            });
            return variable2; /////////// Until here it's working perfect
        });
        $.ajax({
            "http://example.com/mydataset2.json?example2="+variable2,
            // The error is in this link, the variable is undefined.
            type: "GET",
            data: {
              "$limit" : 5000
            }           
        }).done(function(data) {                
            console.log(data);
        });     

What is wrong with my code can someone explain that?

OtoTheZ
  • 1
  • 5
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – tkausl Jan 16 '19 at 01:04
  • No got more calls in ajax and they all work fine, it's all about that variable it looks like the url call is before the value added to the second variable to get the data – OtoTheZ Jan 16 '19 at 01:06
  • nobody???????????? – OtoTheZ Jan 16 '19 at 01:14
  • 1
    Check the link. Your second call starts before the first one finishes. – tkausl Jan 16 '19 at 01:15

1 Answers1

0

You need to wait until the first ajax call is finished before calling the second ajax. Try this.

async function callAjax() {
    let res1, res2;

    res1 = await $.ajax({
        url: "http://example.com/mydataset.json?example1="+variable1,
        type: "GET",
        data: {"$limit" : 5000}
    });

    let variable2 = res1.options;


    res2 = await $.ajax({
        "http://example.com/mydataset2.json?example2=" + variable2,
        // The error is in this link, the variable is undefined.
        type: "GET",
        data: {
        "$limit" : 5000
        }           
    });

    console.log(res2);
}

Resources:

https://javascript.info/async-await

Adis Azhar
  • 1,022
  • 1
  • 18
  • 37