tags:

views:

28

answers:

1
  var url_string = '/index.php/dvs/get_dvs/' + id + '/';
        $.ll = {};
        $.ll.dvs_data  = {};
        $.post(url_string,{},
        function (data)
        {
                $.each(data.dvs, function(k,v) {
                $.each(v, function(dvs_name, dvs_value) {

                    $.ll.dvs_data[dvs_name] = dvs_value;

                });
            });

        }, "json");

        var test = $.ll.dvs_data;
        console.log(test['username']);
        console.log(test.username);
        console.log(test);

The above is part of some other code, the data is being received as console.log(test) displays the object in firebug (firefox) however I am unable to access the test.username or test['username] objects, they just get returned as undefined

+2  A: 

This is a common mistake when it comes to AJAX. The post call is asynchronous, meaning it will continue to run the code after it, even before a response from the server is received.

Any code that depends on a response from the server needs to go inside the callback function:

$.post(url_string,{},
    function (data)
    {
        $.each(data.dvs, function(k,v) {
            $.each(v, function(dvs_name, dvs_value) {

                $.ll.dvs_data[dvs_name] = dvs_value;

            });
        });

        // Move your code up here
        var test = $.ll.dvs_data;
        console.log(test['username']);
        console.log(test.username);
        console.log(test);

    }, "json");
box9