Reputation: 31
Employee webpage makes Ajax calls to the node.js web server in a loop. Code as given. All data values are correct. I expect the callback UpdateTeamArr
to be called n times where n is equal to the loop max - document.getElementById("deptSelect").options.length
. But its called only once. Thanks for your effort and support.
for (var i = 1; i < document.getElementById("deptSelect").options.length; i++) {
var objJSON = {
"deptid": document.getElementById("deptSelect").options[i].dataset.id,
"empid": selectedEmployeeId
}
var strJSON = JSON.stringify(objJSON);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("post", "../../GetEmployeesTeams", true);
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) {
UpdateTeamArr(xmlhttp);
}
}
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
xmlhttp.send("strJSON=" + strJSON);
}
}
function UpdateTeamArr(xmlhttp) {
}
app.post('/GetEmployeesTeams', function(req, res) {
var connection = mysql.createConnection({
host : "127.0.0.1",
port : 3306,
user : "root",
password : "root",
database : "lighting"
});
var strJSON = req.param('strJSON');
var objJSON = JSON.parse(strJSON);
connection.connect();
connection.query("SELECT db_teamemp.teamid, db_department.id AS deptid FROM lighting.db_teamemp, lighting.db_department, lighting.db_team WHERE db_teamemp.empid='" +
objJSON.empid + "' AND db_department.id='" + objJSON.deptid + "' AND db_teamemp.teamid=db_team.id AND db_team.dept=db_department.id;",
function(err, result, fields) {
if (err)
throw err;
else {
connection.end();
res.status(200);
return res.send(result);
}
});
});
Upvotes: 1
Views: 78
Reputation: 11557
Ah, you are using a var
here for xmlhttp
. A var is not block scoped, it's hoisted - that means this single var is used by all calls to UpdateTeamArr
. I believe you are calling the function N times, but with the last response every time.
An easy test of this theory is simply changing var
to let
on that line.
Upvotes: 1
Reputation: 361
Why don't you try to perform just a single request to the server by creating a uniq JSONArray with a list containing all Employees id's inside your 'deptSelect'?
This way you send a response with also a list containing the other attributes for the employees in another JSONArray format, that you can iterate in the UpdateTeamArr function
Upvotes: 1