Function calling $ .getJSON () returns undefined

3

I'm trying to get data from a JSON via javascript with the getJSON function from Jquery, but it's returning undefined. Here is the code:

$(document).ready(function(){
    $("#log").append(pegaPrev("São Paulo-SP"));
});

function pegaPrev(cidade){

	var dados;
	var servidor = "http://developers.agenciaideias.com.br/tempo/json/" + cidade;
	
	$.getJSON( servidor, function(data){
		dados = data;
	});
	
	
	return dados;
}
<!DOCTYPE html>
<html>
	<head>
		<title></title>
		<meta charset='UTF-8'>
		<meta http-equiv='content-type' content='text/html; charset=UTF-8'>
        	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script></head><body><divid="log"></div>
	</body>
</html>
    
asked by anonymous 09.03.2016 / 22:38

2 answers

4

The way it is, its function will not append anything to <div> . This is because the $.getJSON() function is asynchronous, that is, it does not execute exactly the same time it is called.

So what happens in your code is that:

  • You create a var dados; variable, initialized with the% JavaScript default value.

  • You call undefined to execute, which you expects to set the value of the variable $.getJSON() created above, but does not / p>

  • You return dados , which has not yet been defined, because dados has not yet executed.

  • What you should do is use a callback function , as is suggested by $.getJSON() documentation:

    $(document).ready(function() {
    	pegaPrev("São Paulo-SP", function(dados) {
    		$('#log').append(dados);
    	});
    });
    
    function pegaPrev(cidade, callback) {
    	var servidor = "http://developers.agenciaideias.com.br/tempo/json/" + cidade;
    
    	$.getJSON( servidor, function(data) {
    		callback(JSON.stringify(data));
    	});
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script><divid="log"></div>

    Notice that the append of the JSON returned by the call to $.getJSON() is done inside a function that you pass as a parameter to $.getJSON() .

    pegaPrev() was used because the returned value by the JSON.stringfy() function is a JSON object, which you can not use to append the $.getJSON() . This function converts the JSON object to a string.

        
    09.03.2016 / 23:20
    0

    I have a similar problem, it's been 3 days since I fought and nothing!

    javascript code

    var readUrlHome="/ Home / ReadGraphic /";     var barChartData;

    function getJsonData(idIndicadores, idUgbs) {
        $.getJSON(readUrlHome, { IdIndicador: idIndicadores, IdUGB: idUgbs }, function (data) {
            barChartData = data;
        });
    }
    
    var dataFromLoadData;
    
    function loadData(idIndicadores, idUgbs) {
        $.getJSON("/Home/LerGrafico/", { data:{ IdIndicador: idIndicadores, IdUGB: idUgbs }, format: "json" }).done(function (data) {
            dataFromLoadData = data;
        });
    }
    
    var dataFromLoadData02;
    
    function LoadData02(idIndicadores, idUgbs) {
        var property = this;
        this.getingData = function () {
            $.getJSON(readUrlHome, { IdIndicador: idIndicadores, IdUGB: idUgbs }, function (data) {
                return data;
            });
        }
    }
    
    var dataFromLoadDataAjax;
    
    function LoadDataAjax(idIndicadores, idUgbs) {
        var datatoreturn;
        $.ajax({
            type: 'GET',
            dataType: 'json',
            url: '/Home/LerGrafico/',
            data: { IdIndicador: idIndicadores, IdUGB: idUgbs },
            success: function (data, msg) {
                dataFromLoadDataAjax = data;
                datatoreturn = data;
                alert(msg)
            }
        });
    
        return datatoreturn;
    }
    

    This last method displays an alert with msg of success.

    The above examples do not work, in all of these examples the var declared before the method continues undefined, one of those methods there, whatever works, is called inside another function executed when I choose an item in a drop down list.

    Any idea what I can do?

    Editing:

    I was able to get it right, instead of get json returning the result storing in a variable I put the javascript method that would make use of the requested data, had tried before but had given an error in a value among the data returned, when I stopped to check I realized it was a mistake to load this wrong value into chartjs. I thought the call was not working but the error was in the assembly of chartjs, after realizing that I changed the value and it worked.

        
    27.06.2017 / 05:29