Pregunta

I have a problem with the final values assigned to global variables (success, count_error, error) in my code below. Before the outputting section if I don't include "alert( success );" all values are zero. However if I include that line then the correct values are outputted. Why is this, is there something wrong with the variable scope ?

<html>
<head>

<script src="../jquery-1.11.0.js"></script>
<script>
var rows_all = [1,2,3,4,5,6,7,8,9,10],
    success = 0,
    count_error = 0,
    error = [];

/////////////////////////////////////////////////////////////////////////
// In test_addresses create lat/lon [number] from coordinates [string] //
/////////////////////////////////////////////////////////////////////////
$.getJSON("http://******.cartodb.com/api/v2/sql?q=" + "SELECT cartodb_id FROM test_addresses" + "&api_key=******", function(data) {

//get #rows for loop function
//$.each(data.rows, function(key, val) {
    //rows_all.push(val['cartodb_id']);
//});


//loop through rows (get coordinates), manipulate + post values
$.each(rows_all, function(key1, val1) {
    $.getJSON("http://******.cartodb.com/api/v2/sql?q=" + "SELECT address, coordinates FROM test_addresses WHERE cartodb_id=" + val1 + "&api_key=******", function(data1) {
        $.each(data1.rows, function(key2, val2) {
            address = val2['address'];
            lat_lon = val2['coordinates'];
            if (lat_lon.indexOf('?') === -1) {
                lat = parseFloat( lat_lon.split(',')[0] );
                lon = parseFloat( lat_lon.split(',')[1] );
                $.post("http://******.cartodb.com/api/v2/sql?q=" + "UPDATE test_addresses SET lat=" + lat + ", lon=" + lon + "WHERE cartodb_id=" + val1 + "&api_key=******");
                success++; //number of successfully completed operations
            }
            else {
                count_error++; //#error operations
                list = {};
                list["id"] = val1; //@which cartodb_id in table
                list["address"] = address; //@which matching address in table
                error.push(list); 
            }
        });
    });
});

alert( success );
//Ouput text    
$("#result").html(success + " entries successfully geocoded. </br><br>There were " + count_error + " errors. <br>More pecifically at cartodb_id : address:");   
$.each(error, function(key4, val4) {
    $("#result").append("<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + val4["id"] + " : " + val4["address"]);
});

$.each(rows_all, function(key5, val5) {
    $("#result").append("<br>" + key5);
});
});

</script>
</head>

<body>
    <p id="result"></p>
</body>
</html>
¿Fue útil?

Solución

It is an asynchronous request, so the alert() will fire before getting the data. So you should change the code like,

$.getJSON("http://******.cartodb.com/api/v2/sql?q=" + "SELECT cartodb_id FROM test_addresses" + "&api_key=******", function (data) {

//get #rows for loop function
//$.each(data.rows, function(key, val) {
//rows_all.push(val['cartodb_id']);
//});


//loop through rows (get coordinates), manipulate + post values
$.each(rows_all, function (key1, val1) {
    $.getJSON("http://******.cartodb.com/api/v2/sql?q=" + "SELECT address, coordinates FROM test_addresses WHERE cartodb_id=" + val1 + "&api_key=******", function (data1) {
        $.each(data1.rows, function (key2, val2) {
            address = val2['address'];
            lat_lon = val2['coordinates'];
            if (lat_lon.indexOf('?') === -1) {
                lat = parseFloat(lat_lon.split(',')[0]);
                lon = parseFloat(lat_lon.split(',')[1]);
                $.post("http://******.cartodb.com/api/v2/sql?q=" + "UPDATE test_addresses SET lat=" + lat + ", lon=" + lon + "WHERE cartodb_id=" + val1 + "&api_key=******");
                success++; //number of successfully completed operations
                alert(success);

            } else {
                count_error++; //#error operations
                list = {};
                list["id"] = val1; //@which cartodb_id in table
                list["address"] = address; //@which matching address in table
                error.push(list);
            }
        });
        //Ouput text    
        $("#result").html(success + " entries successfully geocoded. </br><br>There were " + count_error + " errors. <br>More pecifically at cartodb_id : address:");
        $.each(error, function (key4, val4) {
            $("#result").append("<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + val4["id"] + " : " + val4["address"]);
        });

        $.each(rows_all, function (key5, val5) {
            $("#result").append("<br>" + key5);
        });
    });
});



});

You should put the code inside the scope of $.getJSON itself. So it will run only after getting the data.

Actually its not alert() doing the magic. If you put an alert, the success event will happen with in less timespan, before the user clicks ok button. Within that time all the values will be populated.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top