0

Why the freak is Javascript hoisting the variable jsonObj?!?!

If I place the console.debug into the $.get function, I can see the JSON data. Otherwise, it's an empty string.

function searchDirectory() {

    var jsonObj = '';
    var params = {
        'firstName':    $('input[name=firstName]').val(),
        'lastName':     $('input[name=lastName]').val()
    };

    $.get("directory-search.php", params, function (data) {
        jsonObj = JSON.parse(data);
    })
    .fail(function () {
        alert("Oops! We could not process your request. Please try again later.");
    });
    console.debug(jsonObj);
}

I've tried not declaring the variable at the top and letting it set the global inside the $.get function, but that requires that I click the button that calls this function twice the first time.

hyp3rg3om3tric
  • 449
  • 1
  • 4
  • 10

0 Answers0