I am experiencing very strange behavior in a function that performs an AJAX call to my server.
The code below is lifted from my jQuery script. The 2 functions shown below appear exactly in this order within my script. If you follow the alerts, they document the processing order of the overall script.
What is odd, and unexplained, and quite frankly problematic to my script's process is that the $.ajax()
call does not get executed when I am needing it to. It gets executed last.
Is there something wrong with the coding of my script?
$(document).ready(function() {
$(window).load(function() {
$('#agentID').change(function() {
alert('This alert displays on screen First');
$.ajax({
url: '/scripts/ajaxAgent.php',
type: 'GET',
dataType: 'html',
data: 'lookup=' + $('#agentID').val(),
success: function(data) {
if (data == 1) {
alert('Oddly and incorrectly, this alert displays on screen Third');
$('.visibility').show();
$('#resTypeID').closest('div').removeClass("optional");
$('#resTypeID').closest('div').addClass("required");
}
else {
alert('Oddly and incorrectly, this alert displays on screen Third');
$('.visibility').hide();
$('#resTypeID').closest('div').removeClass("required");
$('#resTypeID').closest('div').addClass("optional");
}
resTypeVisibilityHandler = data; // this var is set to global at top of this script
}, // end success
error: function() {
alert('An error occurred in processing.');
} // end error
}); // end .ajax()
}); // end agentID .change()
$('#agentID').focus();
$(document).on('change', '.visibilityControl', function(event) {
alert('This alert displays on screen Second');
// ...
}); // end .on('change') visibility control
}); // end .load()
}); // end .ready()
@pep has the answer to my unique question. For some reason SO is blocking new answers or incorrect answers. Here is the solution:
"So instead, you could simply wrap all of your code that needs to be executed when the script completes into a function. Then, at the end of AJAX success, you can call that function and at that point the timing will be correct, as the code would execute third in your example as expected."
He's got it...that's the work around !
2014-12-12 @ 13:15 (GMT-5) petitioned request to the SO Lords to reopen this question so I can properly accept the correct answer.