I'm trying to use bind to access external variables with ajax requests. I've replicated my problem in the code snippet below.
My ajax request is within a for loop, and I'm trying to bind eid and pid to the success function such that I can access their value at the time of the request. However, it seems that this has messed up data and status, because data is 'myPid' and status is an object with my returned data, although eid and pid seem to have displayed correctly.
The jQuery .ajax specification says that the arguments to the function are result, status, and xhr in that order, and this seems to be how it works before I add the step to bind eid and pid.
Am I missing something? Why does my returned data get bound to status instead?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var pid = 'myPid';
var eids = [888, 999];
for(var ind in eids) {
let eid = eids[ind];
$.ajax({
url: "https://reqres.in/api/users?page=2", async: false,
success: function(data, status) {
console.log("data:"+data);
console.log("status:"+status);
console.log("eid:"+eid);
console.log("pid:"+pid);
}.bind(eid, pid),
error: function(a, b, err) {
console.log(err);
}
});
}
});
});
</script>
</head>
<body>
<div><h2>Let AJAX change this text</h2></div>
<button>Change Content</button>
</body>
</html>