簡體   English   中英

根據SELECT和INPUT值更新數據庫

[英]Update Database Based on SELECT and INPUT Values

我有一個具有多個不同輸入的表單。 表格的兩個部分是一個下拉框和三個聯系信息輸入框。 每當我在下拉框中進行選擇時,它都會自動將信息填充到文本框中。 我還在文本框旁邊有一個保存按鈕。 一旦單擊保存按鈕,這使我可以更新該字段(如果需要更改)。 因此,例如,如果我將下拉框值硬編碼到我的update語句中,它就可以工作,但是如果不對它進行硬編碼,我就無法使其正常工作。

因此,我認為我只需要獲取Javascript即可讀取在下拉框中選擇的值。 我怎樣才能解決這個問題? 由於它已經存在,所以我不在SUBMIT上運行它。 我只是單擊表單中的保存按鈕,該按鈕會自動更新信息。

下拉框代碼:

<div>
<div id="vendor">
<strong>Vendor:</strong>
</div> 

<div class="align">
<select name="vendor_dropdown" id="ven" onChange="updateinput();">
    <option value="">Choose a Vendor</option>
        <?php foreach($users->fetchAll() as $user): ?>
            <option
                    data-name="<?php echo $user['MR_POC_N'];?>"
                    data-email="<?php echo $user['MR_POC_E'];?>"
                    data-phone="<?php echo $user['MR_POC_P'];?>"
            >
                <?php echo $user['MR_Name'];?>
            </option>
        <?php endforeach; ?>
</select>
</div>

</div>

自動填充的聯系信息代碼:

<div>
<div id="contact_info">
<strong>Contact Information:</strong><br>
</div>

<div class="align1">
<table align="left" id="contact">
<tr align="left">
    <th>Name</th>
    <th>Email</th>
    <th>Phone Number</th>
</tr>
    <tr>
        <td><input type="text" id="name" class="name" name="name"></td>
        <td><input type="email" id="email" class="email" name="email"></td>
        <td><input type="tel" id="tel" class="tel" name="number"></td>
        <td><input type="button" class="edit" name="edit" value="Save"></td>
    </tr>
</table>
</div>

</div>

用於編輯信息的Javascript:

// ----- Edit Contact Info -----

$(document).on("click", "#contact .edit", function () {
  var $this = $(this);
  var tds = $this.closest('tr').find('td').filter(function () {
    return $(this).find('.edit').length === 0;
  });
  if ($this.val() === 'Edit') {
   /*if($this.id !== '.mr_id') {
        tds.not('.mr_id').not('.mr_name').prop('contenteditable', true);
   }*/
  } else {
    var isValid = true;
    var errors = '';
    $('#myDialogBox').empty();
    var elements = tds;
    if (tds.find('input').length > 0) {
      elements = tds.find('input');
    }
    var dict = {}; 
    elements.each(function (index, element) {
      var type = $(this).attr('class');
      var value = (element.tagName == 'INPUT') ? $(this).val() : $(this).text();
      console.log(type);
      // ----- Switch statement that provides validation for each table cell -----
      switch (type) {
        case "ven":
              dict["MR_Name"] = value;
            break;
        case "name":
          if (value == value.match(/^[a-zA-Z\s]+$/)) {
              dict["MR_POC_N"] = value;
            break;
          }
          else {
            isValid = false;
            errors += "Please enter a valid Name\n";
          }
          break;
        case "email":
          if (value == value.match(/^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/)) {
              dict["MR_POC_E"] = value;
            break;
          }
          else {
            isValid = false;
            errors += "Please enter a valid Email\n";
          }
          break;
        case "tel":
          if (value == value.match('^[0-9 ()+/-]{10,}$')) {
              dict["MR_POC_P"] = value;
            break;
          }
          else {
            isValid = false;
            errors += "Please enter a valid Phone Number\n";
          }
          break;
      }
    })

    if (isValid) {
        console.log(dict);

    var selIndex = ven.selectedIndex;
    console.log();
    var selName = $( "#ven option:selected" ).text();

      //$this.val('Save');
      //tds.prop('contenteditable', false);
      var request = $.ajax({
      type: "POST",
      url: "update.php",
      data: { ven : selName },
      success: function(data){
          console.log(selName);
          }
    });

        request.done(function (response, textStatus, jqXHR){
          if(JSON.parse(response) == true){
            console.log("Data saved");
          } else {
            console.log("Data failed to save");
            console.log(response);
            console.log(textStatus);
            console.log(jqXHR);
          }
        });

        // Callback handler that will be called on failure
        request.fail(function (jqXHR, textStatus, errorThrown){
            // Log the error to the console
            console.log(textStatus);
            console.log(jqXHR);
            console.error(
                "The following error occurred: "+
                textStatus, errorThrown
            );
        });

        // Callback handler that will be called regardless
        // if the request failed or succeeded
        request.always(function () {

        });
    } else {
      alert(errors);
    }
  }
});

update.php:

<?php

  $MR_Name = $_POST['ven'];
  $MR_POC_N = $_POST['MR_POC_N'];
  $MR_POC_E = $_POST['MR_POC_E'];
  $MR_POC_P = $_POST['MR_POC_P'];

  $host="xxxxxxx"; 
  $dbName="xxxxxxxxx"; 
  $dbUser="xxxx"; 
  $dbPass="xxxxxxxx";

  $pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);

  $sql = "UPDATE Stage_Rebate_Master SET MR_POC_N = :MR_POC_N, MR_POC_E = :MR_POC_E, MR_POC_P = :MR_POC_P WHERE MR_Name = '$MR_Name'";

  $stmt = $pdo->prepare($sql);
  $stmt->bindValue(':MR_Name', $MR_Name);  
  $stmt->bindValue(':MR_POC_N', $MR_POC_N);
  $stmt->bindValue(':MR_POC_E', $MR_POC_E);
  $stmt->bindValue(':MR_POC_P', $MR_POC_P);  
  $result = $stmt->execute();
  echo json_encode($result);

?>

試試這個javascript

// -----編輯聯系信息-----

$(document).on("click", "#contact .edit", function () {
 var $this = $(this);
var tds = $this.closest('tr').find('td').filter(function () {
return $(this).find('.edit').length === 0;
 });
  if ($this.val() === 'Edit') {
   /*if($this.id !== '.mr_id') {
    tds.not('.mr_id').not('.mr_name').prop('contenteditable', true);
 }*/
  } else {
var isValid = true;
var errors = '';
$('#myDialogBox').empty();
var elements = tds;
if (tds.find('input').length > 0) {
  elements = tds.find('input');
}
var dict = {}; 
elements.each(function (index, element) {
  var type = $(this).attr('class');
  var value = (element.tagName == 'INPUT') ? $(this).val() : $(this).text();
  console.log(type);
  // ----- Switch statement that provides validation for each table cell -----
  switch (type) {
    case "ven":
          dict["MR_Name"] = value;
        break;
    case "name":
      if (value == value.match(/^[a-zA-Z\s]+$/)) {
          dict["MR_POC_N"] = value;
        break;
      }
      else {
        isValid = false;
        errors += "Please enter a valid Name\n";
      }
      break;
    case "email":
      if (value == value.match(/^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/)) {
          dict["MR_POC_E"] = value;
        break;
      }
      else {
        isValid = false;
        errors += "Please enter a valid Email\n";
      }
      break;
    case "tel":
      if (value == value.match('^[0-9 ()+/-]{10,}$')) {
          dict["MR_POC_P"] = value;
        break;
      }
      else {
        isValid = false;
        errors += "Please enter a valid Phone Number\n";
      }
      break;
  }
})

 if (isValid) {
    console.log(dict);
  //$this.val('Save');
  //tds.prop('contenteditable', false);
  var request = $.ajax({
      type: "POST",
      url: "update.php",
      data: {MR_Name: dict['MR_Name], MR_POC_N: dict['MR_POC_N'],  MR_POC_E: dict['MR_POC_E'],  MR_POC_P: dict['MR_POC_P'], }
    });

    request.done(function (response, textStatus, jqXHR){
      if(JSON.parse(response) == true){
        console.log("Data saved");
      } else {
        console.log("Data failed to save");
        console.log(response);
        console.log(textStatus);
        console.log(jqXHR);
      }
    });

    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // Log the error to the console
        console.log(textStatus);
        console.log(jqXHR);
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
    });

    // Callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {

    });
} else {
  alert(errors);
}
}
   });

暫無
暫無

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

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