Hi, I have a jQuery question:
I have an "ADD" button that adds text to the database via AJAX call ($.post()...). The problem is, items are getting repeatedly added. For example:
After page loads: User clicks "ADD" button:
- the first time, it adds an item.
- a seconds time, it adds an item and then adds it again (total 2 items)
- a thrid time, it adds an item and then adds it again and than again (total 3 items)
- etc...
This is a problem as the data is duplicating.
I've narrowed down the problem:
$(document).ready(function()
{
// set event handler for Add button
bindAddButtonEventListener();
});
// set event handler for Add button
function bindAddButtonEventListener()
{
// event handler for the add button
$("#addRecord").click(function()
{
openPopUpBox();
enablePopUpBoxControls();
// event handler for Submit button on admin Popup box. Submits data to database
$("#editPopUp #submitChanges").click(function(event)
{
addNewRecord();
});
});
}
// this method will submit a new record to the server, using AJAX post
function addNewRecord()
{
var obj = buildJSONobject();
$.post("admin/addRecordToDatabase", obj, function(data)
{
displayServerValidation(data);
cancelPopUpChanges();
getCatagoriesItems();
});
disablePopUpBoxControls();
}
// this unbinds the events for the popup box controls
function disablePopUpBoxControls()
{
// unbind event handler for button
$("#editPopUp #submitChanges").unbind("click", bindEditButtonEventListener);
//$("#editPopUp #submitChanges").unbind("click", bindAddButtonEventListener);
// unbind event handler for button
$("#editPopUp #cancelEdit").unbind("click", enablePopUpBoxControls);
}
For some reason, inside bindAddButtonEventListener(), when this code runs:
$("#editPopUp #submitChanges").click(function(event)
{
addNewRecord();
});
addNewRecord() is called again the second time and a third time, the third time and then again. I can't figure out how to stop it from doing it. I thought that unbinding would help, but it doesn't seem to. Any help would be much appreciated.