1

I currently have some JQuery code, where I am trying to ensure one block of code is executed only after the AJAX calls in the first block have been completed. I'm having some problems, however - I have tried to use the JQuery Deferred method to do this (code below), but neither the first or second code blocks are running, so I assume I am on the wrong track.

I am new to the Deferred methods, so I'm hoping someone can point me in the right direction, or point out another (perhaps better) way of doing this.

function makeChains(){
    $('.chained_to_vehicle_make_selector').remoteChainedTo('.chained_parent_vehicle_make_selector', '/models.json');
    $('.chained_to_vehicle_model_selector').remoteChainedTo('.chained_parent_vehicle_model_selector', '/trims.json');
    $('.chained_to_vehicle_trim_selector').remoteChainedTo('.chained_parent_vehicle_trim_selector', '/model_years.json');
}

var chainCall = $.Deferred(function() {
    makeChains();
});

chainCall.done(function() { 
    $(".chzn-select").chosen();
    $(".chained_parent_vehicle_make_selector").chosen().change( function() {$(".chained_to_vehicle_make_selector").trigger("liszt:updated"); });
    $(".chained_parent_vehicle_model_selector").chosen().change( function() {$(".chained_to_vehicle_model_selector").trigger("liszt:updated"); });
    $(".chained_parent_vehicle_trim_selector").chosen().change( function() {$(".chained_to_vehicle_trim_selector").trigger("liszt:updated"); });
    $(".chained_child").chosen();
});

I have also tried adding chainCall.resolve(); to the end, but to no avail.

Can anyone assist?

EDIT: I've had a look at the solution here: Waiting for jQuery AJAX response(s) which seems like it would work, but I think the problem might be that remoteChainedTo doesn't seem to have a built-in callback? Would I need to modify the code to add a callback for this to work, or will JQuery be able to help me? The remoteChainedTo plugin is using getJSON to pull the data from the url.

EDIT 2: Not much love for this question - any further ideas?

Axel
  • 3,331
  • 11
  • 35
  • 58
Harry
  • 4,660
  • 7
  • 37
  • 65

1 Answers1

0

Considering the remoteChained method returns a jqXHR object (a deferred),you might want to try something like:

var dfds = [],
list = ['vehicle_make_selector','vehicle_model_selector','vehicle_trim_selector'],
urls = ['/models.json','trims.json','/model_years.json'];

for(var i=0;i<list.length;i++){
    dfds.push( $('chained_to_' + list[i]).remoteChainedTo('chained_parent',urls[i]);
}

$.when.apply($,dfds).done(function(){
     $(".chzn-select").chosen();
     //... rest of the code.
})
sbr
  • 4,735
  • 5
  • 43
  • 49