Note that there are some explanatory texts on larger screens.

plurals
  1. POIterate on array, calling $.ajax for each element. Return array with all ajax results
    text
    copied!<p>I've just started working with JavaScript for non-trivial things, so this is probably straightforward...</p> <p>What I'm trying to accomplish: iterate on an array of product references, fetch the JSON for each reference, and return an array of all the product information (with a hash-like structure indexed by reference).</p> <p>What I've tried:</p> <pre><code>function fetchProductData(references){ var product_data = new Object(); references.forEach(function(ref){ $.ajax({ url: "http://localhost:3000/products/find.js?reference=" + ref, dataType: "jsonp", type: "GET", processData: false, contentType: "application/json", success: function(data) { product_data[ref] = data; } }); }); alert('before return: ' + product_data); return product_data; }; $(document).ready(function(){ var products = fetchProductData(references); alert('products : ' + products); }); </code></pre> <p>Here's what I don't understand: the first time I call <code>alert</code> to display the array contents, the array is empty. However, on the second call, the array is populated with the data I want.</p> <p>In other words, the "products :" <code>alert</code> displays the data I want in the code above. But if I comment the "before return: " <code>alert</code>, it no longer does. Why is this?</p> <p>So my question is: how can I have jQuery make several $.ajax call to fetch product information, collect that information in an array, and return that array so I can use it elsewhere in my code?</p> <p>Also, why is the data in the variable magically accessible after it is referenced in an <code>alert</code>?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload