在HTML按钮上更新数据库行单击

时间:2017-02-10 14:56:31

标签: php jquery sql-server ajax sql-update

我目前有一个表,其中包含从SQL Server数据库导入的数据。该表还有每行的编辑按钮,如果需要,我可以选择编辑某一行。在保存时,它应该向我的update.php脚本发出一个AJAX请求,该脚本运行SQL更新查询。但是,每当我更新行并单击“保存”时,我都会收到此错误:

  

500(内部服务器错误)

但是,我可以在我的控制台中看到它正在记录我需要的正确值,所以我猜这个问题要么是AJAX相关的,要么是我update.php脚本中的某个地方。我的以下代码有什么问题,以便我可以让更新功能正常工作?

我的更新问题和编辑按钮所需的2列都在表格中:

<td class="sku" id="sku-<?php echo intval ($rows['SKU'])?>"><?php echo $rows['SKU']?></td>
<td class="group_id" style="display: none" id="group_id-<?php echo intval ($rows['SKU Group'])?>"><?php echo $rows['Group_ID']?></td>
<td><input type="button" class="edit" name="edit" value="Edit"></td>

获取值和AJAX请求的switch语句:

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 "group_id":
          dict["Group_ID"] = value.trim();
      break;
    case "sku":
      if (!$.isNumeric(value)) {
        isValid = false;
        errors += "Please enter a valid SKU\n";
      }
      if (isValid) {
          dict["SKU"] = value;
      }
      break;
  }
})
if (isValid) {
    console.log(dict);
  $this.val('Edit');
  tds.prop('contenteditable', false);
  var request = $.ajax({
      type: "POST",
      url: "update.php",
      data: dict
    });

    request.done(function (response, textStatus, jqXHR){
      if(JSON.parse(response) == true){
        console.log("row updated");
      } else {
        console.log("row failed to updated");
        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

  $SKU = $_POST['SKU'];
  $Group_ID = $_POST['Group_ID'];

  $host="xxxxxxxxxx"; 
  $dbName="xxxxx"; 
  $dbUser="xxxxxxxxxxxxx"; 
  $dbPass="xxxxxxxxxx";

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

  $sql = "UPDATE SKU_Group_Index SET SKU = :SKU WHERE Group_ID = :Group_ID";

  $stmt = $pdo->prepare($sql);
  $stmt->bindValue(':SKU', $SKU);
  $stmt->bindValue(':Group_ID', $Group_ID)  
  $result = $stmt->execute();
  echo json_encode($result);
  if(!$result) {
      echo json_encode(sqlsrv_errors());
  }

?>

编辑: 这是我的console.log(dict);看起来像的一个例子:

  

对象{SKU:&#34; 12345&#34;,Group_ID:&#34; 456&#34;}

0 个答案:

没有答案