Question

I am new with Promises. This is also my first post on stackoverflow. I am trying to refactor the following procedure using promises:

var listBuilder = (function() {

$.post("sc.php",{task: "getLocations"},function(data) {
    $.each(data, function(i,item) {
        $('<li>',{id: "loc-" + item.idlocatii, text: item.denumire})
            .appendTo("#lista")
            .addClass("locationList")
            .draggable({
                revert: "invalid",
                helper: "clone"
            });
    });
},'json');

})();

So I came with the following code to replace the above:

var listBuilder = (function() {

function addListItem(item) {
    $('<li>',{id: "loc-" + item.idlocatii, text: item.denumire})
        .appendTo("#lista")
        .addClass("locationList")
        .draggable({
            revert: "invalid",
            helper: "clone"
        });
}

var getLocations = $.post("sc.php",{task: "getLocations"},'json');

getLocations.done(function(data) {
    $.each(data, function(i,item) {
        addListItem(item);
    });
});

})();

The refactored version of code returns the error below:

Uncaught TypeError: Cannot use 'in' operator to search for '1026' in [{"idlocatii":"1","denumire":"Hirsch Hopfen"},{"idlocatii":"2","denumire":"Berlinerstr. 24"},{"idlocatii":"3","denumire":"Pfalzerstr. 26"},{"idlocatii":"4","denumire":"Christophal......}]

Can you explain where is the error?

Thank you!

Was it helpful?

Solution

It's possible that the data you're getting back is actually a JSON string and not an object. What happens if you change your getLocations.done block to the following:

getLocations.done(function(data) {
    var parsedData = JSON.parse(data);
    $.each(parsedData, function(i,item) {
        addListItem(item);
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top