(javascript) function returning Undefined

Asked

Viewed 135 times

1

I’m trying to return a value from one function to the other, get_Positions() has to receive the lat and lng from parseJson(data), it’s only returning Undefined. I want to receive these two values from within get_Positions().


get_Positions();
      function get_Positions(){
        $.ajax({
          url: 'http://taxer-cc.umbler.net/read.php',
          type: 'POST',
          dataType: 'html',
          data: 'value1=1'
        })
        .done(function(data) {
          var lct = parseJson(data);
          console.log(lct);
        })
        .fail(function(e) {
          console.log("Error: "+e);
        });
        function parseJson(data){
          $.each($.parseJSON(data), function (item, value) {
            $.each(value, function (i, k) {
              var location = function(){
                lat = k.lat;
                lng = k.lng;
                return [lat,lng];
              }
              loc = location();
              lat = loc[0];
              lng = loc[1];
              return [lat,lng];
            });
          });
        }
      }

1 answer

2


The function parseJson returns nothing. The return [lat,lng]; that you added, is returning the value to the callback of the $.each and not for the function parseJson.

The correct is:

function parseJson(data) {
    var result = [];

    $.each($.parseJSON(data), function(item, value) {
        $.each(value, function(i, k) {
            var location = function() {
                lat = k.lat;
                lng = k.lng;
                return [lat, lng];
            }
            loc = location();
            lat = loc[0];
            lng = loc[1];

            console.log([lat, lng]);

            result = [lat, lng];
        });
    });

    return result;
}

You can also use this way:

function parseJson(data){
     /* Transforma a string json em objeto */
     let result = JSON.parse(data);

     /* Captura a primeira key do objeto */
     let key = Object.keys(result)[0];

     /* Retorna os valores. */
     return [result[key][0].lat, result[key][0].lng];
}
  • Thank you, it worked properly!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.