I've got a JavaScript function that loops over a set of devices, makes an API call to that device and returns results in JSON format. However, the results that are returned and printed to the screen are the same for all devices (even though they aren't supposed to be).
I've verified that the API call is hitting each different device on the server-side, yet still, the response shows like it's all from the same device.
From everything I've read this has to do with scopes but I cannot for the life of me get this to work any ideas?
JavaScript AJAX function: (UPDATED)
function getEthernetSwitchingTable(devices, macAddr) {
for (i=0;i<devices.length;i++) {
(function(idx){
var hostname = devices[idx]['hostname']
var deviceId = devices[idx]['id']
var URL = '/api/v1/device/'+hostname+'/ethernet-switching-table.json?macAddr='+macAddr
var ajax = $.get(URL, function(res){
console.log(hostname)
console.log(res)
}, "json")
})(i);
}
}
Server-side logs:
"GET /api/v1/device/cr01.corp.ldn01/ethernet-switching-table.json?macAddr=00:07:4d:55:d5:da HTTP/1.1" 200 317
"GET /api/v1/device/cr02.corp.ldn01/ethernet-switching-table.json?macAddr=00:07:4d:55:d5:da HTTP/1.1" 200 317
"GET /api/v1/device/cr02.plant.ldn01/ethernet-switching-table.json?macAddr=00:07:4d:55:d5:da HTTP/1.1" 200 317
"GET /api/v1/device/cr01.plant.ldn01/ethernet-switching-table.json?macAddr=00:07:4d:55:d5:da HTTP/1.1" 200 317
Console response:
cr01.corp.ldn01
{DeviceHostname: "cr02.plant.ldn01", DeviceId: 104, EthernetSwitchingTable: {…}, Status: 200}
cr02.corp.ldn01
{DeviceHostname: "cr02.plant.ldn01", DeviceId: 104, EthernetSwitchingTable: {…}, Status: 200}
cr02.plant.ldn01
{DeviceHostname: "cr02.plant.ldn01", DeviceId: 104, EthernetSwitchingTable: {…}, Status: 200}
cr01.plant.ldn01
{DeviceHostname: "cr02.plant.ldn01", DeviceId: 104, EthernetSwitchingTable: {…}, Status: 200}
Expected response:
cr01.corp.ldn01
{DeviceHostname: "cr01.corp.ldn01", DeviceId: 57, EthernetSwitchingTable: null, Status: 200}
cr02.corp.ldn01
{DeviceHostname: "cr02.corp.ldn01", DeviceId: 100, EthernetSwitchingTable: null, Status: 200}
cr02.plant.ldn01
{DeviceHostname:"cr02.plant.ldn01", DeviceId:104, EthernetSwitchingTable:{"l2ng-l2-mac-vlan-name":[{"data":"pack11-15-304"}]}, Status:200}
cr01.plant.ldn01
{DeviceHostname: "cr01.plant.ldn01", DeviceId: 59, EthernetSwitchingTable: null, Status: 200}