I got it to work with everyone's help. I change the 'context:' to 'this' from 'this.parentNode'. I still get confused with the 'this' context. With limited testing it appears to have fixed my problem with running multiple instances. Thanks for your help. The new code is shown below.
I am new to jQuery and Javascript. I am creating a general object to navigate database tables (NavDb). It works perfectly if I create 1 instance. When I run multiple instances it fails. I traced the problem to how I use 'this'. One routine that initializes/handles ajax requests fails. A form can have any number of selectors (autocomplete or drop-downs). The routine recursively performs ajax requests until all the selectors have been initialized. The 'this' variable refers to the ajax object when entering the 'success:' function. I need a reference to the parent object so I created a $this on line 2. The problem is it creates a closure and messes up the second instance (I believe that is what is happening). How do I get a reference to the parent object inside the success function? Can I bind the ajax request to the parent object? I need something like this:
var $this = this.parent;
Hopefully I explained this clearly.
New code
NavDb.prototype.getSelData = function () {
if (this.curSelector >= this.selectors.length) {
return;
}
else {
var sql = this.selectors[this.curSelector].sql;
$.ajax({
url: 'php/select.php',
type: 'POST',
context: this, // Only needed 'this' not this.parentNode.
dataType: 'json',
data: {
'sql': sql
}
}).done(function (data) {
if (data.success) {
if (data.v.length > 0) {
this.selectors[this.curSelector].data = data;
if (this.selectors[this.curSelector].type == "autoComp") {
this.initAC();
};
if (this.selectors[this.curSelector].type == "dropDown") {
this.initDD();
};
}
}
this.curSelector++;
this.getSelData();
}).fail(function (XHR, textStatus, errorThrown) {
$("#status").html(getErrorText(XHR.responseText));
});
};
};
Old code
NavDb.prototype.ajaxSelData = function () {
var $this = this;
if (this.curSelector >= this.selectors.length) {
$this = null;
return;
}
else {
var sql = $this.selectors[$this.curSelector].sql;
$.ajax({
url: 'php/select.php',
type: 'POST',
dataType: 'json',
data: {
'sql': sql
},
success: function (data) {
if (data.success) {
if (data.v.length > 0) {
$this.selectors[$this.curSelector].data = data;
if ($this.selectors[$this.curSelector].type == "autoComp") {
$this.initAC();
};
if ($this.selectors[$this.curSelector].type == "dropDown") {
$this.initDD();
};
}
} else {
alert(data.error);
}
$this.curSelector++;
$this.ajaxSelData();
}
});
};
};