3

I want to create a JSON array like this:

var ddBasic = [
    { text: "Facebook", value: 1, },
    { text: "Twitter", value: 2, },
    { text: "LinkedIn", value: 3, },
    { text: "Foursquare", value: 4, }
];

I'm using data from last.fm, so it would be something like this:

var tags = [
        { text: "rock", value: "rock", },
        { text: "pop", value: "pop", },
    ];

It needs to have a comma at the end so the ddslick dropdown function ignores the imageSrc and other things it can use for a dropdown, other it throws this error:

Uncaught TypeError: Cannot read property 'imageSrc' of undefined

To tie everything together, I have:

$('#tag').ddslick({
    data: tags,
    onSelected: function(selectedData) {}   
});

This is the function that gets the tags:

var tags = [];

var getTopTracks = function () {
    $.getJSON(
    settings.PHP_REQUEST_URL, {
        method: "tag.getTopTags",
        api_key: settings.LASTFM_APIKEY,
        format: "json",
    },

    function (data) {
        var limit = 50;

        data.toptags.tag.sort(function (t1, t2) {
            return t2.count - t1.count;
        });

        $.each(data.toptags.tag, function (i, item) {
            if (i > limit) return false;
            console.log(item.name);
            tags.push({
                text: item.name,
                value: item.name
            });
        });
    });
};

// event handlers (load quando o form é invocado só)
getTopTracks();
alert(tags.length);

// define tema para a combobox   
$('#tag').ddslick({
    data: tags,
    onSelected: function (selectedData) {}
});

How can I accomplish this?

9
  • You're saying it works fine with the comma? I don't see how that would make a difference. Commented Oct 13, 2012 at 17:01
  • Oh...apparently it wasn't the comma, it's something in my array. I'm pushing values with tags.push({"text" : item.name, "value" : item.name}); - is this the correct syntax? Length shows 0 after pushing, which makes me wonder what's wrong. Commented Oct 13, 2012 at 17:06
  • Check the console for errors... is item defined? Commented Oct 13, 2012 at 17:08
  • 1
    @sachleen: possible but this would mean there's another tags variable hiding somehwere (well: where?) because otherwise push would throw something like can not call push on undefined Commented Oct 13, 2012 at 17:35
  • 1
    Fixed, it was because I was trying to get values before AJAX finished the request. All fixed. Thanks very much for your help. Commented Oct 13, 2012 at 17:51

1 Answer 1

2
var tags = []; //initialised tags with length 0
getTopTracks(); //fetching date in background (!)
alert(tags.length); //running while data is still fitched (unless you've a 0ping connection => alerting length 0

At the point you use the alert it's very likely tags is not filled as $.getJSON() is an asynchronus request, meaning the request will be handled in the background and execution of the script continues. You have to use the callback method as you already did for filling up the array.

This, getJSON, is a shorthand Ajax function, which is equivalent to:
$.ajax({   
   url: url,
   dataType: 'json',
   data: data,
   success: callback
});

http://api.jquery.com/jQuery.getJSON/

//getJSON success callback:
function (data) {
    var limit = 50;

    data.toptags.tag.sort(function (t1, t2) {
        return t2.count - t1.count;
    });

    $.each(data.toptags.tag, function (i, item) {
        if (i > limit) return false;
        console.log(item.name);
        tags.push({
            text: item.name,
            value: item.name
        });
    });
    //alert the length AFTER the tags been pushed
    alert(tags.length);

    // define tema para a combobox   
    $('#tag').ddslick({
        data: tags,
        onSelected: function (selectedData) {}
    });
}
Sign up to request clarification or add additional context in comments.

6 Comments

Oh wow, it's because I'm doing this on page load, which means that it loads the elements before the call is made. How do I wait until it finishes?
You move your code after the $.each into the callback method. So you make sure it's get executed after the array was filled.
value is okay but text property showing as undefined:
@Can Ürek: uhm can't really follow. Would you mind writing another question for your problem possible with a minimal example?
I handle that. My solution like that. var json = {}; json[name] = value; That's work for me.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.