I have the following PHP file that I will call using my $.ajax()
in my JS:
<?php
header('Content-Type: application/json');
echo json_encode(array('One' => 'Test'));
?>
And I have the following code in my JS:
<script type = "text/javascript">
let changeValue;
$('#someElementID').click(function() {
$.ajax({
type: 'POST',
url : 'phpfile.php',
dataType : 'json',
success: function(obj, textStatus) {
changeValue = obj.One;
}
});
$('#toBeChangedElementValue').text(changeValue);
}
</script>
Problem is: the changeValue
variable only gets its value after my $('#toBeChangedElementValue').text()
has been executed. How does it work? How do I fix this? I had to place $('#toBeChangedElementValue').text(changeValue)
in my success callback instead to make it work. Why didn't my changeValue
get updated first before that final .text()
happened?