This question already has an answer here:
- How do I return the response from an asynchronous call? 35 answers
I'm facing some difficulties in my code related to scope. Here is my code:
<script type="text/javascript">
var totalHoras = {};
var dadosCategorias = {"teste": "1234"};
var t; // timeout handler para exibição de feedback para o usuário
$().ready(function() {
// obtém dados das categorias
var obterDadosCategorias = function() {
$.post(
"{{ baseRoute }}/cadastro/categoria/listar"
, {
"ajax": "true"
}
).done(function(data) {
var obj = $.parseJSON(data);
if (obj.result) {
console.log(dadosCategorias); // returns 'object{"teste": "1234"}'
dadosCategorias = obj.data;
console.log(dadosCategorias); // returns 'string(11) "it works!!!"'
} else {
alert('Erro interno: não foi possível obter os dados das categorias');
}
});
};
obterDadosCategorias();
console.log(dadosCategorias); // returns 'object{"teste": "1234"}'
The question is: why the hell is the third call of console.log returning the orginal var value? isn't is suposed to be overwriten?
The console was suposed to be
'object{"teste": "1234"}'
'string(11) "it works!!!"'
'string(11) "it works!!!"'
But it is
'object{"teste": "1234"}'
'string(11) "it works!!!"'
'object{"teste": "1234"}'
I've trie to use the "context" option with window in $.ajax() function, but does not work too :(