javascriptjqueryajaxgeonames

Javascript: undefined when I want to get the response


I want to get the city name from the postcode. I started to achieve it with the GeoNames example, but I encountered some errors with it. I managed to "work" (it sends the request and on the response tab I see the correct response, but I couldn't reach it.

My snippet is:

var countrycode = document.getElementById("countrySelect").value;
var postalcode = document.getElementById("postalcodeInput").value;

    request = 'http://api.geonames.org/postalCodeLookupJSON?postalcode=' + postalcode + '&country=' + countrycode + '&callback=getLocation&username=myUname';

    // Create a new script object
    aObj = jQuery.getJSON(request)
    console.log(aObj);
    response = aObj.responseText;
    console.log(response);

From the console.log(aObj) I got:

Object { readyState: 1, getResponseHeader: getResponseHeader(), getAllResponseHeaders: getAllResponseHeaders(), setRequestHeader: setRequestHeader(), overrideMimeType: overrideMimeType(), statusCode: statusCode(), abort: abort(), state: state(), always: always(), catch: catch(),...

And if I click on the more, I see that the response is in the responseText.

The output of the console.log(response) is 'undefined'

How to get the response? What am I missed?


Solution

  • Please find the sample. getJson is the asynchronous call, Kindly write your logic in the success callback as shown below.

    $.getJSON(request, function(result){
               //success logic
               console.log(result);
               //response = aObj.responseText;
                //console.log(response);
            });
    

    Kindly refer http://api.jquery.com/jquery.getjson/ for more understanding.