title: Update Database After Editing Form Using Ajax
body: <p>I have asked many questions related to this, but still have not found a good answer. I get a lot of suggestions and questions, but I am not very good with Javascript or Ajax, so I need your help and not just suggestions.</p>
  
  <p>I have a table that is populated with data from a database. It has a few buttons...add row, save table, edit, and deactivate. It would be nice to have the database update after each button is pressed, but for now, all i really need is for everything to update once the Save Table button is pressed. How can I get this to happen. I know I need to use Ajax, but unsure of how. If someone would be able to take some times and post an answer that would be awesome! I've been working on this for a while and could really go for figuring this out finally.</p>
  
  <p>DB connection:</p>
  
  <pre><code>&lt;?php
  $host="xxxxxxxxxxxxxxxx"; 
  $dbName="xxxxxxx"; 
  $dbUser="xxxx"; 
  $dbPass="xxxxxxxxx";
  
  $dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
  $dbh-&gt;setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
  $sql = "SELECT * FROM Stage_Rebate_Master ORDER BY MR_ID ASC";
  ?&gt;
  </code></pre>
  
  <p>HTML/PHP:</p>
  
  <pre><code>&lt;div id="dialog-form" title="Add Vendor"&gt;
    &lt;p class="validateTips"&gt;All form fields are required.&lt;/p&gt;
  
    &lt;form&gt;
      &lt;fieldset&gt;
        &lt;label for="mr_name"&gt;Vendor&lt;/label&gt;
        &lt;input type="text" name="mr_name" id="mr_name" class="text ui-widget-content ui-corner-all"&gt;
        &lt;label for="buyer_id"&gt;Buyer ID&lt;/label&gt;
        &lt;input type="text" name="buyer_id" id="buyer_id" class="text ui-widget-content ui-corner-all"&gt;
        &lt;label for="poc_n"&gt;POC Name&lt;/label&gt;
        &lt;input type="text" name="poc_n" id="poc_n" class="text ui-widget-content ui-corner-all"&gt;
        &lt;label for="poc_p"&gt;POC Email&lt;/label&gt;
        &lt;input type="text" name="poc_e" id="poc_e" class="text ui-widget-content ui-corner-all"&gt;
        &lt;label for="poc_p"&gt;POC Phone&lt;/label&gt;
        &lt;input type="text" name="poc_p" id="poc_p" class="text ui-widget-content ui-corner-all"&gt;
  
        &lt;!-- Allow form submission with keyboard without duplicating the dialog button --&gt;
        &lt;input type="submit" id="submit" tabindex="-1" style="position:absolute; top:-1000px"&gt;
      &lt;/fieldset&gt;
    &lt;/form&gt;
  &lt;/div&gt;
  
  
  &lt;div id="users-contain" class="ui-widget"&gt;
  &lt;table id="html_master" class="ui-widget ui-widget-content"&gt;
  &lt;thead&gt;
      &lt;tr class="ui-widget-header"&gt;
      &lt;td&gt;ID&lt;/td&gt;
      &lt;td&gt;Vendor&lt;/td&gt;
      &lt;td&gt;Buyer ID&lt;/td&gt;
      &lt;td&gt;POC Name&lt;/td&gt;
      &lt;td&gt;POC Email&lt;/td&gt;
      &lt;td&gt;POC Phone&lt;/td&gt;
      &lt;td&gt;Edit/Delete&lt;/td&gt;
      &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
  
  &lt;?php
      foreach ($dbh-&gt;query($sql) as $rows){
      ?&gt;
      &lt;tr&gt;
          &lt;td class="mr_id" contenteditable="false"&gt;&lt;?php echo intval ($rows['MR_ID'])?&gt;&lt;/td&gt;
          &lt;td class="mr_name" contenteditable="false"&gt;&lt;?php echo $rows['MR_Name']?&gt;&lt;/td&gt;
          &lt;td class="buyer_id" contenteditable="false"&gt;&lt;?php echo $rows['Buyer_ID']?&gt;&lt;/td&gt;
          &lt;td class="poc_n" contenteditable="false"&gt;&lt;?php echo $rows['MR_POC_N']?&gt;&lt;/td&gt;     
          &lt;td class="poc_e" contenteditable="false"&gt;&lt;?php echo $rows['MR_POC_E']?&gt;&lt;/td&gt;
          &lt;td class="poc_p" contenteditable="false"&gt;&lt;?php echo $rows['MR_POC_P']?&gt;&lt;/td&gt;
          &lt;td&gt;&lt;input type="button" class="edit" name="edit" value="Edit"&gt;
          &lt;input type="button" class="deactivate" name="deactivate" value="Deactivate"&gt;&lt;/td&gt;
      &lt;/tr&gt;
   &lt;?php
    }
   ?&gt;
  &lt;/tbody&gt;
  
      &lt;input type="button" class="create-user" value="Add Row"&gt;
      &lt;input type="submit" value="Save Table" class="save"&gt;
  
  &lt;/table&gt;
  &lt;/div&gt;
  
      &lt;input type="button" class="create-user" value="Add Row"&gt;
      &lt;input type="submit" value="Save Table" class="save"&gt;
  </code></pre>
  
  <p>Javascript:</p>
  
  <pre><code>// ----- Deactivate/Activate Row -----
  
  $(document).on("click", "#html_master .deactivate", function () {
    var $this = $(this);
    var $tr = $this.closest('tr');
    var action = $tr.hasClass('deactivated') ? 'activate' : 'deactivate';
  
    // ------ Confirmation box in order to deactivate/activate row -----
    if (confirm('Are you sure you want to ' + action + ' this entry?')) {
      $tr.toggleClass('deactivated');
      $this.val(function (i, t) {
        return t == 'Deactivate' ? 'Activate' : 'Deactivate';
      });
    }
  });
  
  // ----- Edit Row -----
  
  $(document).on("click", "#html_master .edit", function () {
    var $this = $(this);
    var tds = $this.closest('tr').find('td').not('.mr_id').filter(function () {
      return $(this).find('.edit').length === 0;
    });
    if ($this.val() === 'Edit') {
      $this.val('Save');
      tds.prop('contenteditable', true);
    } else {
      var isValid = true;
      var errors = '';
      $('#myDialogBox').empty();
      // changed from here.......
      var elements = tds;
      if (tds.find('input').length &gt; 0) {
        elements = tds.find('input');
      }
      elements.each(function (index, element) {
        var type = $(this).attr('class');
        var value = (element.tagName == 'INPUT') ? $(this).val() : $(this).text();
        // changed from here....... to here
        // ----- Switch statement that provides validation -----
        switch (type) {
          case "buyer_id":
            if (!$.isNumeric(value)) {
              isValid = false;
              errors += "Please enter a valid Buyer ID\n";
            }
            break;
          case "poc_n":
            if (value == value.match(/^[a-zA-Z\s]+$/)) {
              break;
            }
            else {
              isValid = false;
              errors += "Please enter a valid Name\n";
            }
            break;
          case "poc_e":
            if (value == value.match(/^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/)) {
              break;
            }
            else {
              isValid = false;
              errors += "Please enter a valid Email\n";
            }
            break;
          case "poc_p":
            if (value == value.match('^[0-9 ()+/-]{10,}$')) {
              break;
            }
            else {
              isValid = false;
              errors += "Please enter a valid Phone Number\n";
            }
            break;
        }
      })
      if (isValid) {
        $this.val('Edit');
        tds.prop('contenteditable', false);
      } else {
        alert(errors);
      }
    }
  });
  
  // ----- Dialog Box -----
  
  $( function() {   
  
      var dialog, form,
  
        emailRegex = /^[a-zA-Z0-9.!#$%&amp;'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
        phoneRegex = /^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/,
        mr_name = $( "#mr_name" ),
        buyer_id = $( "#buyer_id" ),
        poc_n = $( "#poc_n" ),
        poc_e = $( "#poc_e" ),
        poc_p = $( "#poc_p" ),
        allFields = $( [] ).add( mr_name ).add( buyer_id ).add( poc_n ).add( poc_e ).add( poc_p ),
        tips = $( ".validateTips" );
    console.log(allFields);
  
      function updateTips( t ) {
        tips
          .text( t )
          .addClass( "ui-state-highlight" );
        setTimeout(function() {
          tips.removeClass( "ui-state-highlight", 1500 );
        }, 500 );
      }
  
      function checkRegexp( o, regexp, n ) {
        if ( !( regexp.test( o.val() ) ) ) {
          o.addClass( "ui-state-error" );
          updateTips( n );
          return false;
        } else {
          return true;
        }
      }
  
     function addVendor() {
        var valid = true;
        allFields.removeClass( "ui-state-error" );
  
        valid = valid &amp;&amp; checkRegexp( mr_name, /^[a-z]([0-9a-z_\s])+$/i, "Please enter a valid vendor name" );
        valid = valid &amp;&amp; checkRegexp( buyer_id, /^(0|[1-9][0-9]*)$/, "Please enter a valid Buyer ID" );
        valid = valid &amp;&amp; checkRegexp( poc_n, /^[a-zA-Z ]*$/, "Please enter a valid name" );
        valid = valid &amp;&amp; checkRegexp( poc_e, emailRegex, "Please enter a valid email" );
        valid = valid &amp;&amp; checkRegexp( poc_p, phoneRegex, "Please enter a valid phone number" );
  
        if ( valid ) {
          var $tr = $( "#html_master tbody tr" ).eq(0).clone();
          $.each(allFields, function(){
            $tr.find('.' + $(this).attr('id')).html( $(this).val() );
          });
          $tr.find('.mr_id').html( $( "#html_master tbody tr" ).length + 1 );
          $( "#html_master tbody" ).append($tr);
          dialog.dialog( "close" );
        }
        return valid;
      }
  
      var dialog = $( "#dialog-form" ).dialog({
        autoOpen: false,
        height: 400,
        width: 350,
        modal: true,
        buttons: {
          "Add Row": addVendor,
          Cancel: function() {
            dialog.dialog( "close" );
          }
        },
        close: function() {
          form[ 0 ].reset();
          allFields.removeClass( "ui-state-error" );
        }
      });
  
      form = dialog.find( "form" ).on( "submit", function( event ) {
        event.preventDefault();
        addVendor();
      });
  
      $( ".create-user" ).button().on( "click", function() {
        dialog.dialog( "open" );
      });
    } );
  
  
  // ----- Save Table -----
  $(document).on("click", ".save", function () {
  
    // ------ Confirmation box in order to deactivate/activate row -----
    if (confirm('Saving will update the entire table. Are you sure you want to save?')) {
    var tabledata=[];
    $( "#html_master tbody tr" ).each(function( index ) {
        tabledata[index] = {
            mr_id: $( this ).find("td.mr_id").text(),
            mr_name: $( this ).find("td.mr_name").text(),
            buyer_id: $( this ).find("td.buyer_id").text(),
            poc_n: $( this ).find("td.poc_n").text(),
            poc_e: $( this ).find("td.poc_e").text(),
            poc_p: $( this ).find("td.poc_p").text()
        };
  
  });
  }
  });
  </code></pre>