This question already has an answer here:
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 :(
Thanks to the comments guys! :D
I've found the answer. The problem wasn't the scope at all. Actually, the calls to console.log() wasn't in the order of the script. The calling order was 312 before, now it is 123 :D I changed the ajax method to $.ajax() instead of $.post() and set the option 'async' to false to achieve this, like so: