Joppo
Joppo

Reputation: 729

How to prevent many nested functions within an (jquery) ajax call?

I'm developing a webpage that retrieves some database info via a (jquery) ajax call and then manipulates the data and displays it on the page via various javascript functions. I use a module pattern ('userapp' in the code example below) to avoid globals and to use the data by the various functions.

The simplified code below works, but only if I include all the functions (such test() in the code below) within the ajax call, and I think that's going to result in ugly complex code (also in line with some best javascript practises I read on the web). When I tried to call the example function test() outside /after the ajax call (embedded in init()), test() does not work as I think the ajax call has not completed setting the variables ('products[]' in example) yet.

My question: is it possible to call other functions outside the ajax call, and if so, how? I looked at callback examples but I'm not sure whether/how that would solve my problem...

simplified code:

userapp = function(){
 //userapp properties 
 var today = new Date();
 var products = [];

 var copyItems = function(source_items, target_items){
   //do something
 };//var copyItems

 var init = function(){
  $.ajax({
    url: "user_admin_get.php",
    data: { command: "getuserbaseinfo", val1: "", val2: "" },
    success: function (msg) {
        copyItems(msg.eproducts,products); //set values for 'products' used by test()

        test(); //calling test() here works as the the values has been set()
    },//success: function(msg)
    error: function(msg) {
        console.log('error result from php file:');
    },//error:
    dataType: "json"
   });//$.ajax({

 };//var init = function(){

 var test = function(){
   //do something
 };//test()

 return{init:init, test:test} //return (only) public functions and vars
}(); //userapp()

//main function document ready    
$(document).ready(function(){

  userapp.init();
  //userapp.test(); //test() is not working here as init() has not set the requirement parameters tey


 }); //$(document).ready

Upvotes: 1

Views: 208

Answers (1)

acoiro
acoiro

Reputation: 888

You want to pass a callback to init and call test inside this callback.

var init = function(callback){
  $.ajax({
    ....
    success: function (msg) {
        ....
        callback();
    }
    ...
 };

...

userapp.init(function() {
  // user app is ready!
  userapp.test();
});

Upvotes: 1

Related Questions