Daniel Robinson
Daniel Robinson

Reputation: 653

Trigger a second ajax function when the first has completed

Ok so im trying to start an ajax call after the first call has completed. I have a form with 3 drop down menus. The first menu onload runs the script to bring back values. I then want to feed the vale into the second script and run the script to populate the second 3rd menu.

the second dropdown is populated onChange of the first. This works great. I then want the result of that feed into to third drop down. I know my external queries are right I just think the ajax is wrong. Here is my Ajax calls....

<script type="text/javascript" charset="utf-8">

jQuery(document).ready(function() {
jQuery('#networks').trigger('change');
});




function get_cities(networks)
{
$.ajax({
   type: "POST",
   url: "select.php", 
   beforeSend:  function () {
  $("#folder").html("<option>Loading ...</option>");
    },
   data: "idnetworks="+networks +"&par="+ <?php echo $row_rs_doc['parentid']; ?>,


   success: function(msg){
     $("#folder").html(msg);
   }



   });



} 
</script>
<script type="text/javascript" charset="utf-8">

jQuery(document).ready(function() {  
jQuery('#folder').trigger('change');
});

function get_sub(folder)
{
$.ajax({
   type: "POST",
   url: "select2.php", 
   beforeSend:  function () {
  $("#subfolder").html("<option>Loading ...</option>");
    },
   data: "iddocs="+folder,


   success: function(msg){
     $("#subfolder").html(msg);
   }



   });



} 
</script> 

ok here are the form fields

<select name="networks" id="networks" onChange='get_cities($(this).val())'>
   <?php create(network, networkid, netname);?>
  </select>

<select name="folder" id="folder" onChange='get_sub($(this).val())'>


</select>

<select name="subfolder" id="subfolder">


</select>

Upvotes: 0

Views: 309

Answers (2)

Alnitak
Alnitak

Reputation: 339816

You can use deferred objects, which will allow you to initiate additional actions without having to rewrite your existing event handler, and without nesting your code too much:

var req1 = $.ajax(...);

req1.done(function() { ... } );  // start your second request

Upvotes: 0

Itay Moav -Malimovka
Itay Moav -Malimovka

Reputation: 53605

KISS it. Just put the second ajax call inside the success of the first one

Upvotes: 1

Related Questions