'jQuery ajax form submitting multiple times

I am having some issues with multiple form submissions with a jQuery/ajax form. I found this by printing every instance of form submission on my server, and saw that a form would submit correctly once, then again multiple times.

Just to be clear, this code works 100% correctly for the first submission, but when I click on another row in my table, and create a new dialog/submit it, it ends up submitting multiple times.

I think it has to do with event binding, but am having trouble fixing it. Any insight or help would be much appreciated.

The button's id is "save-flag-button"

// When someone clicks on the flag column in my table, a dialog pops up //
// on the condition that a flag does not exist. //
$(function() {
  $('.flag').click(function() {
    var cellId = "flag" + String(this.getAttribute("data-client-rel"));
    if (this.getAttribute("data-flag-exists") == '0') {

      // create dialog
      var dialog = flagDialog('Create Flag');
      
      // Making the form ajax
      $("form", dialog).ajaxForm(function(success, data) {
        if (success) {
          $("#" + cellId).attr("data-flag-exists", '1');
          $("#" + cellId).attr("data-flag-content", data["flag_state"]);
          $("#" + cellId).text(data["flag_state"]);
          $("#flag-dialog").dialog("close");
        } else {
          alert("Failed to submit flag. Please retry.");
        }
      });
    } else { }

    }).hover(function() {
      if (this.getAttribute("data-flag-exists") == '0') {
        this.innerHTML = '<span style="color: #4183C4;">Create flag!</span>';
      }}, function() {
        this.innerHTML = this.getAttribute("data-flag-content");
      })
    });

// jquery dialog code //
function flagDialog(dialogTitle) {
  var dialog = $("#flag-dialog").dialog({
    autoOpen: false,
    autoResize: true,
    modal: true,
    minHeight: 300,
    minWidth: 450,
    position: "center",
    title: dialogTitle,
    buttons: [{
      id: "flag-cancel-button",
      text: "Cancel",
      click: function() {
        $(this).dialog("close");
        }
      },
      {
      id:"save-flag-button",
      text: "Submit",
      click: function() {
        $("#flag-dialog").dialog("destroy");
        // $("#client-relationship-flag-form").submit();
        }
      }],
    close: function() {
      //$("#notes-text").text("");
    }
  });
  
  // Unbinding buttons here //
  $("#save-flag-button, #flag-cancel-button").unbind();
  $("#save-flag-button").unbind('click').click(function() {
    $("#client-relationship-flag-form").submit();
  });
  $("#flag-cancel-button").click(function() {
     $("#flag-dialog").dialog("close");
  });

  dialog.dialog("open");
  return dialog;
};


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source