views:

50

answers:

2

Let's look at the output of console.log. A click on the button changes the name if we use the function changeName(). But if we use the function changeNameAjax() (where response.name = 'Ford Prefect'), one click on the button doesn't change the name, only a second click does. Why?

<!DOCTYPE html>
<head>
    <script type='text/javascript' src='js/jquery.js'></script>
    <script type="text/javascript">
    $(document).ready(function() {
        $('button').click(function(){

            //changeName();
            changeNameAjax();

            var box = document.getElementById("box").innerHTML;
            console.log(box);

            function changeName(){
                $('#box').html('<p>Ford Prefect</p>');
            }

            function changeNameAjax(){
                $.ajax({
                    url: 'getName.php?jsoncallback=?',
                    dataType: 'json',
                    success: function(response){
                        $('#box').html('<p>' + response.name + '</p>');
                    }
                });
            }

        });
    });
</script>
</head>
<body>
    <button>Update</button>
    <div id='box'>
        <p>Arthur Dent</p>
    </div>
</body>
</html>
A: 

My 10 cents: It happens because you're declaring the changeNameAjax() function inside the click event. The first click will define the function, the second will execute it.

DfKimera
Not really, while each click will define a new changeNameAjax function inside the scope of the click function.There is no way a second click can reach the changeNameAjax function defined in a previous click since each time the click function executes it will get a fresh scope.
nxt
A: 

This is because AJAX is asynchronous, meaning that success function doesn't run until later, when the response from the server comes back. So this line:

$('#box').html('<p>' + response.name + '</p>');

Doesn't run until after you've called console.log, in fact if you click fast or the server is slow, you can click several times before the success function completes once.

Even if the response is instantaneous (local server for instance), since JavaScript is single threaded, that success still happens afterwards...to see this, just stick a console.log('Success') in your success function, then you'll get a good illustration of the order and when the callbacks execute.

Nick Craver