Joao Joao - 26 days ago 12
jQuery Question

javascript behaviour in run time differs from debug

I have some problem debugging a script, just because in debug mode all works fine... but not in runtime:
I have this function in javascript:

function Add() {
...
$('#Value').val($('#Value').val()); // Value is a div class="input"
...
$.get('@Url.Action("GetSomeData", "_Shared")', { id: parseInt($('#DataID').val()) },
function (result) { $('#SomeData').val(result); });

if ($('#SomeData').val() == "x") {
$('#tmp').val($('#Value').val());
}
else {
$('#tmp').val("0");
}
...
}


and the controller _Shared simply returns an attribute:

public string GetSomeData(int id)
{
return unitOfWork.DataRepository.GetByID(id).Something;
}


What happens is when I use a breakpoint in the "
if
",
$('#SomeData').val()
has the correct value but if I remove the breakpoint, write a
console.log($('#SomeData').val())
and execute, it is alway empty and the
$('#tmp').val()
is always "0".
Can anybody tell me what I'm doing wrong?

Answer Source

This is a synchronicity issue. $.get is asynchronous, and the callback you pass it will run when it is finished, not inline with the code where it is written. So your function (result) { $('#SomeData').val(result); }); is running after your if ($('#SomeData').val() == "x") {...

You can fix this by adding the code to run after the $.get to the callback:

$('#Value').val($('#Value').val()); // Value is a div class="input"
...
$.get('@Url.Action("GetSomeData", "_Shared")', { id: parseInt($('#DataID').val()) },
        function (result) {
            $('#SomeData').val(result);
            if ($('#SomeData').val() == "x") {
                $('#tmp').val($('#Value').val());
            }
            else {
                $('#tmp').val("0");
            }
        });

...

Note, it works when you add the breakpoint because that gives your asychronous $.get time to finish and execute.