Note that there are some explanatory texts on larger screens.

plurals
  1. POJquery promise wait to ajax end
    text
    copied!<p>I'm getting predefined values, which i have to insert into two selects:</p> <pre><code>&lt;div id="wrapper"&gt; &lt;select id="first"&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;option value="3"&gt;3&lt;/option&gt; &lt;/select&gt; &lt;select id="second"&gt;&lt;/select&gt; &lt;/div&gt; </code></pre> <p>Options inside <code>#second</code> depends on selected value in <code>#first</code>. This options are loaded via ajax:</p> <pre><code>$('#first').change( function() { $.ajax({ url: "giveMeValues.phpOrWhatever" }).done(function() { // just simulating data from ajax call $('#second').append( '&lt;option value="a"&gt;a&lt;/option&gt;'+ '&lt;option value="b"&gt;b&lt;/option&gt;'+ '&lt;option value="c"&gt;c&lt;/option&gt;' ); }); }); </code></pre> <p>The problem is, I can set value of <code>#second</code> <strong>after</strong> ajax data will be loaded. So following code will of course not work:</p> <pre><code>$('#first').val('2').change(); $('#second').val('b').change(); </code></pre> <p>So i tried to use <code>.promise()</code> to wait untill ajax call inside <code>change</code> handler will be completed:</p> <pre><code>$('#first').val('2').change(); $('#wrapper').promise().then( function() { $('#second').val('b'); console.log('setting value...'); }); </code></pre> <p>But it doesn't work. My question is: how i can wait to end of ajax call, and then set <code>#second</code> value?</p> <p>Here you have fiddle for this problem: <a href="http://jsfiddle.net/W2nVd/" rel="nofollow">http://jsfiddle.net/W2nVd/</a></p> <p>Thanks for your time.</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