-1

I have a database with different link, I want to go fetch these link and put the inside an array.

I tried with the following code:

var amz=new Array();

function CreaArrayAmazon()
{$.ajax({
    url: "php/amazon_affiliate.php",
    success: function(data){
        var leanamazon = JSON.parse(data);
        for (i=0; i<leanamazon.length; i++)
            {amz[i]=leanamazon[i].Link
            }
        }
    })
}

I expect to find all the links in the "amz" array because it is a global variable, instead it saves links only when it is inside the AJAX function. If I insert an "alert" inside the AJAX function (ex. alert(amz[i])) I can correctly see the data, instead if I insert an alert outside that I can't see anything, infact the amz array results to be empity.

Can someone tell me out to take that data out of there?

  • 1
    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) – Robin Zigmond May 01 '19 at 21:27

1 Answers1

1

You might be misunderstanding what is going on here.

AJAX stands for Asynchronous Javascript and XML. Asynchronous means that your code doesn't always run in order.

In this case, your program functions like so../

function CreaArrayAmazon()
{
// Step 1: Make the Call
$.ajax({
    url: "php/amazon_affiliate.php",
    success: function(data){
        // Step 3: When the call succeeds, execute the rest of this inner function.
        var leanamazon = JSON.parse(data);
        for (i=0; i<leanamazon.length; i++)
            {amz[i]=leanamazon[i].Link
            }
        }
    })
// Step 2: Continue Processing....
}

Step 2 happens far before Step 3. By the time your AJAX call finished, Javascript has already finished executing your CreaArrayAmazon call.

Instead, you need to have your inner function (Step 3) call an outside function to react to the new data you've received.

Tyler Carter
  • 60,743
  • 20
  • 130
  • 150