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>
This is because AJAX is asynchronous, meaning that
successfunction doesn’t run until later, when the response from the server comes back. So this line: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 thesuccessfunction completes once.Even if the response is instantaneous (local server for instance), since JavaScript is single threaded, that
successstill happens afterwards…to see this, just stick aconsole.log('Success')in yoursuccessfunction, then you’ll get a good illustration of the order and when the callbacks execute.