Function calling $.getJSON() returns Undefined

Asked

Viewed 8,938 times

3

I’m trying to get the data from a JSON through javascript with Jquery’s getJSON function, but it’s returning Undefined. Follows 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>
		<div id="log"></div>
	</body>
</html>

  • can’t reproduce your error here dude. I tried to access this URL directly in the browser and it worked. I tried to create a . html and run it, it worked. :/

  • But it prints the json values on the page ? Here it doesn’t print the value and when I open the console in Firefox it has this error.

  • No longer giving this error. I think I was wrong. But it still doesn’t work. As I said, it is returning Undefined.

2 answers

4


As it stands, its function will not append anything in the <div>. That’s because the function $.getJSON() is asynchronous, meaning it is not executed at exactly the same time it is called.

So what happens in your code is that:

  1. you create a variable var dados;, initialized with the value undefined javascript standard.

  2. you call $.getJSON() to perform, which you waiting setting the value of the variable dados created above, but this nay happens;

  3. you return dados, which has not yet been defined, because $.getJSON() not yet executed.

What you should do is use a callback Function, in the manner suggested by job documentation $.getJSON():

$(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>
<div id="log"></div>

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

JSON.stringfy() was used because the value returned by the function $.getJSON() is a JSON object, which you cannot use to append to <div>. This function converts the JSON object into a string.

  • 1

    Thank you. It helped a lot.

0

I have a similar problem, for 3 days I fight and nothing!

javascript code

var readUrlHome = "/Home/Lergrafico/"; 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 successful msg.

the above examples do not work, in all these examples the var declared before the method continues Undefined, one of these methods ai, whatever it worked, is called inside another function executed when I choose an item in a drop down list.

Any idea what I can do?

Editing:

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

Browser other questions tagged

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