1

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.

Client side code:

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) {
}

Server code:

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);
    }
    });
});
Bahman Parsa Manesh
  • 2,314
  • 3
  • 16
  • 32
Parndhaman M
  • 31
  • 1
  • 7
  • 1
    Possible duplicate of [Calling an asynchronous function within a for loop in JavaScript](https://stackoverflow.com/questions/13343340/calling-an-asynchronous-function-within-a-for-loop-in-javascript) – ponury-kostek Dec 23 '18 at 22:00
  • This code works fine for me (aside from some deficiencies in other areas), are you sure it shouldn't be `var i = 0` instead of `var i = 1`) – Adam Jenkins Dec 23 '18 at 22:04
  • Try adding console.log statements inside your loop (print `strJSON`) and see if it executes as many times as you think. Also add one at top of UpdateTeamArr, to confirm how often it's actually called. Last be aware you seem to have an extra curly brace at the end of the loop - possibly copypaste error. – Elliot Nelson Dec 23 '18 at 22:05
  • Not a duplicate of Calling an asynchronous function within a for loop in JavaScript – @ponury-koste. That talks about closure whereas here its the number of executions. – Parndhaman M Dec 23 '18 at 22:10
  • @adam - var i = 1 is intentional – Parndhaman M Dec 23 '18 at 22:10
  • @Elliot Nelson - console logs in the server indicate everything is fine there. They are printed n number of times. Its the client side thats causing the error. – Parndhaman M Dec 23 '18 at 22:12

2 Answers2

1

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

PabloQ
  • 361
  • 3
  • 6
1

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.

Elliot Nelson
  • 11,371
  • 3
  • 30
  • 44