user1668630
user1668630

Reputation: 39

Return or structure code so data from ajax call can be used in dynamically populated list

an answer from a previously question I asked here has posed another problem for me, as I am learning more and more about async calls I still can not figure out how to accomplish (as the previous answer showed me) a list which allows me to store and use data from a selected list item.

$('#home').live('pageshow', function(){
    // creating object 
    var customerList = JSON.parse('{"customerInAccount":[{"customer_name":"Jane Doe","auto_id":"21"},{"customer_name":"Jack   Black","auto_id":"22"}]}');

    // creating html string
    var listString = '<ul data-role="listview" id="customerList">';

    // running a loop
    $.each(customerList.customerInAccount, function(index,value){
     listString += '<li><a href="#" data-cusid='+this.auto_id+'>'+this.customer_name+'</a></li>';
    });
    listString +='</ul>';

    console.log(customerList);

    //appending to the div
    $('#CustomerListDiv').html(listString);

    // refreshing the list to apply styles
    $('#CustomerListDiv ul').listview();

    // getting the customer id on the click
    $('#customerList a').bind('click',function(){
     var customerID = $(this).data('cusid');  
     alert(customerID);
    });
});

with js fiddle http://jsfiddle.net/amEge/3/

This code works excellent and will allow me to accomplish what I want but fist I need to populate the customerList from a ajax call. But from the "success" function I cannot seem to get the code to work.

$.post(postTo,{id:idVar} , function(data) {

    customerList = data;
    //alert(customerList);
})

When I move the code inside the ajax function it dose not work. I was just wondering if anyone could help me and maybe show me how to deal with this from asynchronous calls ?

Many Thanks

Upvotes: 0

Views: 837

Answers (2)

Jollymorphic
Jollymorphic

Reputation: 3530

Correct me if I'm wrong, but I'll hazard a guess that your "live" code looks something like this:

$('#home').live('pageshow', function(){
   // creating object 
   var customerList;

   $.post(postTo, {id:idVar}, function(data) {
      customerList = data;
      //alert(customerList);
   });

   // creating html string
   var listString = '<ul data-role="listview" id="customerList">';

   // and all the rest...

If so, then your problem is that the code that's depending on your customerList variable being filled in ("all the rest...") runs immediately, rather than waiting for the response from your HTTP request to come back from the Web server. That $.post() doesn't wait around (or "block," as we say in the computer software programming game) while the HTTP transaction makes its way to the Web server and back. Instead, the rest of your code runs immediately, and then later, when that response comes back to the browser, the JavaScript engine dutifully executes your success function (or "closure," as we hm hmm hmmmm).

So what you'll want to do is put all this other code (the stuff that's dependent on customerList) into a separate function, then call that function from within your success closure. You won't even need your customerList variable then; you can just pass the new response data as an argument to your new function.

Upvotes: 0

Jaya Mayu
Jaya Mayu

Reputation: 17257

You need to change your page as below.

// I assume this is your dot net web service url
var webServiceURL = 'customer.asmx/GetCustomer';

// here home is your page's ID
$('#home').live('pageshow', function(){
    getCustomerList();

});

function getCustomerList(){
    param=JSON.strigify({id:'2'});
    callWebService(param, webServiceURL, onGetCustListSuccess, onGetCustListFailed)
}

function onGetCustListFailed(){
    alert("service request failed");
}

function onGetCustListSuccess(data, status){
    // creating object 
    // replace previous line with below
    // var customerList = JSON.parse('{"customerInAccount":[{"customer_name":"Jane Doe","auto_id":"21"},{"customer_name":"Jack   Black","auto_id":"22"}]}');
    var customerList = JSON.parse(data.d);

    // creating html string
    var listString = '<ul data-role="listview" id="customerList">';

    // running a loop
    $.each(customerList.customerInAccount, function(index,value){
     listString += '<li><a href="#" data-cusid='+this.auto_id+'>'+this.customer_name+'</a></li>';
    });
    listString +='</ul>';

    console.log(customerList);

    //appending to the div
    $('#CustomerListDiv').html(listString);

    // refreshing the list to apply styles
    $('#CustomerListDiv ul').listview();

    // getting the customer id on the click
    $('#customerList a').bind('click',function(){
     var customerID = $(this).data('cusid');  
     alert(customerID);
    });
}

function callWebService(param,url,successFunc,errorFunc){
    if(errorFunc=='undefined'){
        errorFunc=OnDataError;
    } 
    $.ajax({            
            type: "POST",
            url: url,
            data: param,
            contentType:"application/json; charset=utf-8",
            dataType: "json",
            success: successFunc,
            error: errorFunc,
            beforeSend:function(){$.mobile.loading( 'show' );},
            complete:function(){$.mobile.loading( 'hide');}
    });
}

Hope this would help you out. If you have problems asks me here.

Upvotes: 1

Related Questions