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>