tags:

views:

137

answers:

2

I'm learning jquery and wrote this so I can do two seperate $.GET to a php file, retrieve some info and do some calculations on it. I understand I could create one specific php file that does everything and returns the value I need, but I thought it would make more sense to reuse this php file any time I need to retrieve info.

I have this in a function and I wasn't sure how to do the first $.GET, wait for it to finish, attach it to a variable, then execute the second $.GET pass the variable to it and do the calculation. Instead I nested them together which I don't think is right. Here is the code.

    $.get("selectdb.php", { 'id':nsname, 'q':'basecomplexity','table':'switchers'  }, function(data)
    {

        $('#switchtotal'+lastIndex).html(data); //sets data to #switchtotal

        $.get("selectdb.php", { 'id':nsname, 'q':'sources','table':'switchers'  }, function(data)
        {
            var val1 = $('#switchtotal'+lastIndex).html();
            var answer = ((parseFloat(nszones)*parseFloat(data))+parseFloat(val1))*parseFloat(nsquant);
            $('#switchtotal'+lastIndex).html(answer.toFixed(2)); //calculates formula and displays

        });


    });

Is there an easier way to do this?

+1  A: 

You have to nest them at some level.

Due to the asynchronous nature of Ajax ( The A = Asynchronous ) , there's no way to really just stop the code1. So you have to do the processing in the callback.

The best you can get is by implementing a function that gets called in the callbacks instead, so they're not nested, but the logic is still nested.

jQuery(function($){ 

function dbselect( opts, callback ){ 
   $.get("select.php", opts, callback ); 
}

function  handle_sources( data ){ 
   var val1 = $('#switchtotal'+lastIndex).html();
   var answer = ((parseFloat(nszones)*parseFloat(data))+parseFloat(val1))*parseFloat(nsquant);
   $('#switchtotal'+lastIndex).html(answer.toFixed(2)); //calculates formula and displays
}
function handle_basecomplex ( data ){ 
     $('#switchtotal'+lastIndex).html(data); //sets data to #switchtotal
     dbselect( { 'id':nsname, 'q':'sources','table':'switchers'  } , handle_sources ); 
}

dbselect( { 'id':nsname, 'q':'basecomplexity','table':'switchers'  }, handle_basecomplex ); 

});

1. well you can, with synchronous mode, but that's nasty, it stops everything

Kent Fredric
A: 

Give a look to the AjaxQueue Plugin, it provides you a way to manage multiple requests, and get the request in the expected order.

CMS