I am having trouble when trying to implement a delay to a jQuery loop function (.each).
The problem is: I have a list of rows with multiple columns, where the user needs to enter his data.
Now when the user clicks on a button save, all rows needs to be retrieved one by one and their data inserted in a database.
1st get inserts the data and return the last inserted id. Then in the second $.get that last inserted id is used as a history entry.
The code below works as it should, the only problem is the whole procedure is being finished before the nested $.get starts. So all data inserted by the second $.get is the same.
The function getIdNumber removes unwanted characters from the id (ex from row_1 to 1)
$('.data_row').each(function(i){
id = getIdNumber(this.id);
setTimeout(function() {
date = $('#dat_'+id).val();
customer = $('#cus_'+id).val();
amount_paid = $('#amt_'+id).val();
remarks = $('#rem_'+id).val();
account = $('#acc_'+id).val();
url = "bin/_receipts.php?addreceipts=&date="+date+"&customer="+customer+"&amountpaid="+amount_paid+"&remarks="+remarks+"&paidaccount=" + account;
$.get(url, function(d){
url2 = "bin/_ledgerHandler.php?addaudittrail=&user="+escape("<? echo $_SESSION["user_id"]; ?>")+"&trantype="+escape("Receipt - "+d+"")+"&val="+escape(amount_paid)+"&category=receipts";
$.get(url2, function(){
});
});
}, 1000*i);
});
For your second $.get, rather than using the values you calculated before the first get, you need to include everything the second $.get needs in the data result of the first get. That way you can guarantee that all the data for the second $.get is relevant to the result of the first.
In other words, don’t use the values of amount_paid in you second $.get, instead return any needed values in your data along with the last insert id.