Here is the code:
$("#inputtxt").change(function() {
var doneflag = 0;
var testname = " ";
var rawinput = $('#inputtxt').val();
var scnt = 0;
var indata = {};
$('#inputtxt2').val("");
$('#lnghost').show();
$('#lnghost2').hide();
// go load some arrays from data in a database
getDBaseData(fnarray,lnarray,flarray);
// Option 1:
// $(function() {
// setInterval("doneflag=1;", 5000);
// });
// Option 2:
// while (doneflag == 0) {
// t1 = setTimeout("doneflag = 1;",5000);
// };
// Option 3:
// alert('Found 0 |'+fnarray[0] + '|' + lnarray[0]+'Found 1 |'+fnarray[1] + '|' + lnarray[1]+ ' doneflag is '+doneflag);
$.each(fnarray, function(i,val) { ... yada yada yada
Here's what's happening:
It's supposed to work such that the getDbaseData function runs, gets data from the database, load the arrays, then come back and run on. Instead, what's happening is that the getDbaseData function takes off, and this program keeps going so that it hits the .each function BEFORE the arrays are populated.
Between these two statements I have 3 options commented out that I have tried.
- The setInterval doesn't seem to do anything that I can tell.
- The while loop runs indefinitely
- the alert statement seems to make everything run fine, even though it pulls up empty fields from the array. But it seems to stop things long enough for the dbase call to catch up.
Of course I don't want the alert statement. Am I doing something obviously wrong? Does anyone know how to fix this? Help is much appreciated.
========================== Update ======================
Okay, I've read the answers below, but some of you wanted to see the getDbaseData function, so here it is:
<script type="text/javascript">
function getDBaseData(fnlist,lnlist,fllist) {
/* First call the php routine to get the database values, then process that info based on the following statements */
$.getJSON('getnames.php', {indata: $("#inputtxt").val() }, function (data) {
var newHTML = ' ';
var doneflag = 'false';
if (data[0].first == ' ') {
fnlist[0] = 'none';
lnlist[0] = 'none';
fllist[0] = 'none';
return false;
};
$.each(data,function(l, val) {
newHTML += '<li>' + data[l].first + ' ' + data[l].last + '</li>';
fnlist[l] = data[l].first;
lnlist[l] = data[l].last;
fllist[l] = 'hide';
});
$('#NameList').html(newHTML); /* part of test code */
}); /* end of getJSON call */
};
</script>
I've tested every part of this function, and it returns exactly what it is supposed to, so I don't believe there is any logic problem here. I had not considered putting everything into the callback function, but I will try that.