Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <h2>The main problem is that <code>getJSON</code> is asyncronous</h2> <p>Your <code>post</code> properties in <code>data</code> are <code>null</code> because there are two things you're doing wrong here:</p> <ol> <li><code>getJSON</code> is asyncronous so it gets your data after your <code>.each</code> is already executed</li> <li><code>getJSON</code> doesn't return data but rather <code>jqXHR</code> object</li> </ol> <p>Try changing it this way:</p> <pre><code>var data = []; // you likely want an array and not an object var counter = 0; $.get('xmlfile.xml', function(xml) { var oXML = $(xml); oxml.find('user').each(function(i) { var me = $(this); data.push({ name: me.attr('name'), pic: me.attr('pic'), post: null }); // increment counter counter++; $.getJSON(me.attr('post'), (function(index) { return function(data) { data[index].post = data; if (!--counter) // when it reaches ZERO { setTimeout(function() { // all JSONs have loaded now continue with your stuff }, 0); } }; })(i)); }); }); </code></pre> <p>Above code also detects when all JOSN objects have loaded so you can continue processing.</p> <p>But apart from that it works this way:</p> <ol> <li>it gets the XML</li> <li>when XML is received it iterates through <code>user</code> elements and prepares <code>data</code> objects and pushes them into array</li> <li>with each object it issues an Ajax call to get JSON data as well</li> <li>each successful call to JSON then populates correct <code>data</code> object's <code>post</code> property and decreases <code>counter</code></li> <li>when counter reaches zero an additional function is being queued where you can put code that should execute after everything's loaded and done.</li> </ol> <p>If your JSON requests can also fail, then I suggest to use <code>$.ajax</code> instead of <code>getJSON</code> so you can also provide <code>error</code> function inside of which you'd also decrement <code>counter</code>. Otherwise it wouldn't reach zero if only successes are being counted.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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