【问题标题】:Adding Row Using PHP/JavaScript/AJAX to Database使用 PHP/JavaScript/AJAX 将行添加到数据库
【发布时间】:2017-02-17 14:08:30
【问题描述】:

我有一个可以点击的按钮,它会弹出一个带有一个文本字段的弹出框。每当我输入一些内容并单击“添加”时,我都希望将其插入到我的数据库中。

目前,当我单击“添加”时,它会插入数据库,但不会读取输入的值。因此,只需输入一个空值。我没有看到任何错误,但是在我的 JavaScript 中我执行了 console.log(type + " : " + value); 并在日志中返回 sku_group-0 :。我也做了一个console.log(dict),日志中的输出是Object {},所以看起来输入的值没有被记录。我也在日志中收到一条成功的row inserted 消息,所以看起来这只是能够获取要读取的值的问题,然后可以在insert-group.php 脚本中处理它们。

所以我的问题是如何让它读取 JavaScript 中的值,以便它可以成功输入数据库?

弹出框的HTML:

<div id="dialog-form" title="Add Group">
  <p class="validateTips">Please Add a Group</p>

<!-- Dialog box displayed after add row button is clicked -->
  <form>
    <fieldset>        

      <label for="sku_group">SKU Group</label>
      <input type="text" name="group" id="group" 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>

添加按钮的 HTML:

<button class="create-user" id="insertButton">Add Group</button>

JavaScript:

$( function() {   

    var dialog, form,

      sku_group = $( "#group" ),
      allFields = $( [] ).add( sku_group ),
      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 addGroup() {

      var valid = true;
      allFields.removeClass( "ui-state-error" );
// ----- Validation for each input in add row dialog box -----
      valid = valid && checkRegexp( sku_group, /^[a-z]([0-9a-z_\s])+$/i, "Please enter a valid SKU Group name" );
      console.log(allFields);
      if ( valid ) {
        var $tr = $( "#skuTable tbody tr td" ).eq(0).clone();
        var dict = {};
        var errors = "";
        $tr.each(function(){
        var type = $(this).attr('id');
        var value = $(this).html();
        console.log(type + " : " + value);

      switch (type) {
        case "group":
            dict["SKU Group"] = value;
        break;
        }
    });
        $( "#skuTable tbody" ).append($tr);
        dialog.dialog( "close" );
        console.log(dict);


        var request = $.ajax({
          type: "POST",
          url: "insert-group.php",
          data: dict
        });

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

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

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

        });

}

      return valid;
    }

    var dialog = $( "#dialog-form" ).dialog({
      autoOpen: false,
      height: 400,
      width: 350,
      modal: true,
      buttons: {
        "Add Group": addGroup,
        Cancel: function() {
          dialog.dialog( "close" );
        }
      },
      close: function() {
        form[ 0 ].reset();
      }
    });

    form = dialog.find( "form" ).on( "submit", function( event ) {
      event.preventDefault();
      addGroup();
    });

    $( ".create-user" ).button().on( "click", function() {
      dialog.dialog({
          show: 'blind',
          hide: 'blind'
      });
      dialog.dialog("open");
    });

  });

插入-group.php 脚本:

<?php

  $SKU_Group = $_POST['SKU Group'];

  $host="xxxxxxxxxxx"; 
  $dbName="xxxxxxx"; 
  $dbUser="xxxx"; 
  $dbPass="xxxxxxxxxxxxxx";

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

  $sql = "INSERT INTO SKU_Group_Dim ([SKU Group]) VALUES (?)";

  $stmt = $pdo->prepare($sql);
  $result = $stmt->execute(array($SKU_Group));
  echo json_encode($result);

?>

【问题讨论】:

  • 尝试使用 return false;而不是 event.preventDefault(); - 听起来你的表单帖子正在发生。
  • @Paul 我在使用return false;时在我的日志中得到相同的输出
  • 您尝试过登录 dict["SKU Group"] 而不是只登录 dict 。似乎它显示的是一个对象,所以它找到了它。我也看不到您将 dict 分配给任何东西的 php 函数
  • 用数据替换“数据:字典”:{ 'SKU_Group' : $('#group').val() } 并替换“$SKU_Group = $_POST['SKU Group'];” WITH $SKU_Group = $_POST['SKU_Group'];
  • @user1544541 这对我有用!非常感谢...如果您将其发布为答案,我将接受它!

标签: javascript php ajax sql-insert


【解决方案1】:
    REPLACE 
    "data: dict" 
    WITH 
    data:{ 'SKU_Group' : $('#group').val() } 

    AND 

    REPLACE 
    "$SKU_Group = $_POST['SKU Group'];" 
    WITH 
    $SKU_Group = $_POST['SKU_Group'];

【讨论】:

    【解决方案2】:

    你应该得到你的输入值:

    $('#group').val()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-24
      • 1970-01-01
      • 1970-01-01
      • 2020-02-29
      • 2012-08-15
      相关资源
      最近更新 更多