簡體   English   中英

使用Ajax編輯表單后更新數據庫

[英]Update Database After Editing Form Using Ajax

我已經問了許多與此有關的問題,但仍然沒有找到好的答案。 我收到很多建議和問題,但是我對Javascript或Ajax不太滿意,因此我需要您的幫助,而不僅僅是建議。

我有一個用數據庫中的數據填充的表。 它有幾個按鈕...添加行,保存表,編輯和停用。 按下每個按鈕后最好更新數據庫,但是現在,我真正需要的是一旦按下“保存表”按鈕就可以更新所有內容。 我怎樣才能做到這一點。 我知道我需要使用Ajax,但不確定如何使用。 如果某人能夠花一些時間並發布答案,那將是非常棒的! 我已經為此工作了一段時間,最終可以真正弄清楚這一點。

數據庫連接:

<?php
$host="xxxxxxxxxxxxxxxx"; 
$dbName="xxxxxxx"; 
$dbUser="xxxx"; 
$dbPass="xxxxxxxxx";

$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM Stage_Rebate_Master ORDER BY MR_ID ASC";
?>

HTML / PHP:

<div id="dialog-form" title="Add Vendor">
  <p class="validateTips">All form fields are required.</p>

  <form>
    <fieldset>
      <label for="mr_name">Vendor</label>
      <input type="text" name="mr_name" id="mr_name" class="text ui-widget-content ui-corner-all">
      <label for="buyer_id">Buyer ID</label>
      <input type="text" name="buyer_id" id="buyer_id" class="text ui-widget-content ui-corner-all">
      <label for="poc_n">POC Name</label>
      <input type="text" name="poc_n" id="poc_n" class="text ui-widget-content ui-corner-all">
      <label for="poc_p">POC Email</label>
      <input type="text" name="poc_e" id="poc_e" class="text ui-widget-content ui-corner-all">
      <label for="poc_p">POC Phone</label>
      <input type="text" name="poc_p" id="poc_p" class="text ui-widget-content ui-corner-all">

      <!-- Allow form submission with keyboard without duplicating the dialog button -->
      <input type="submit" id="submit" tabindex="-1" style="position:absolute; top:-1000px">
    </fieldset>
  </form>
</div>


<div id="users-contain" class="ui-widget">
<table id="html_master" class="ui-widget ui-widget-content">
<thead>
    <tr class="ui-widget-header">
    <td>ID</td>
    <td>Vendor</td>
    <td>Buyer ID</td>
    <td>POC Name</td>
    <td>POC Email</td>
    <td>POC Phone</td>
    <td>Edit/Delete</td>
    </tr>
</thead>
<tbody>

<?php
    foreach ($dbh->query($sql) as $rows){
    ?>
    <tr>
        <td class="mr_id" contenteditable="false"><?php echo intval ($rows['MR_ID'])?></td>
        <td class="mr_name" contenteditable="false"><?php echo $rows['MR_Name']?></td>
        <td class="buyer_id" contenteditable="false"><?php echo $rows['Buyer_ID']?></td>
        <td class="poc_n" contenteditable="false"><?php echo $rows['MR_POC_N']?></td>     
        <td class="poc_e" contenteditable="false"><?php echo $rows['MR_POC_E']?></td>
        <td class="poc_p" contenteditable="false"><?php echo $rows['MR_POC_P']?></td>
        <td><input type="button" class="edit" name="edit" value="Edit">
        <input type="button" class="deactivate" name="deactivate" value="Deactivate"></td>
    </tr>
 <?php
  }
 ?>
</tbody>

    <input type="button" class="create-user" value="Add Row">
    <input type="submit" value="Save Table" class="save">

</table>
</div>

    <input type="button" class="create-user" value="Add Row">
    <input type="submit" value="Save Table" class="save">

Javascript:

// ----- 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 > 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.!#$%&'*+\/=?^_`{|}~-]+@[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 && checkRegexp( mr_name, /^[a-z]([0-9a-z_\s])+$/i, "Please enter a valid vendor name" );
      valid = valid && checkRegexp( buyer_id, /^(0|[1-9][0-9]*)$/, "Please enter a valid Buyer ID" );
      valid = valid && checkRegexp( poc_n, /^[a-zA-Z ]*$/, "Please enter a valid name" );
      valid = valid && checkRegexp( poc_e, emailRegex, "Please enter a valid email" );
      valid = valid && 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()
      };

});
}
});

您需要創建一個PHP文件來處理來自AJAX的帖子,接收數據並插入或更新數據庫。 我假設您可以處理PHP部分。 至於AJAX,您只需要將數據收集到一個對象中並將其發布到服務器即可。

var postData = {};  //Object to hold your post variables.
postData.id = 2;
postData.name = "Roger";
postData.anythingElse = "Another string";
//And so on.
$.ajax({
    url: "yourPHPfile.php",
    type: "post",
    data: postData,
    success: function(response) {
        console.log(response);
    }
});

yourPHPfile.php文件中,您將使用POST接收這些變量。

$id = $_POST['id'];
$name = $_POST['name'];
$anythingElse = $_POST['anythingElse'];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM