使用HTML / PHP / AJAX将行插入数据库

时间:2021-04-26 01:39:42

I have a button that can be clicked that will bring up a popup box with one textfield. Whenever, I enter something and click "Add", I want it to be inserted into my database.

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

Currently, when I click "Add", it will insert into the DB, but it will not read the value entered. Therefore, a null value is simply entered. I get no errors that I can see, however in my JavaScript I do a console.log(dict) and the output in the log is Object {} so it doesn't look like the entered value is being logged. I also am getting a successful row inserted message in the logs too so I would definitely think that it is just a matter of being able to get the values to be read.

目前,当我单击“添加”时,它将插入到数据库中,但它不会读取输入的值。因此,只需输入空值。我没有看到任何错误,但是在我的JavaScript中,我执行了console.log(dict),日志中的输出是Object {},因此看起来输入的值不会被记录。我也在日志中获得了成功的行插入消息,所以我肯定认为这只是能够获取要读取的值的问题。

So my question is how can I get it to read the value and successfully enter it into the database.

所以我的问题是如何让它读取值并成功将其输入数据库。

HTML of Add button:

添加按钮的HTML:

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

HTML of Popup Box:

弹出框的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>

JavaScript:

JavaScript的:

// ----- Dialog Box for adding a row -----

$( 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" ).eq(0).clone();
        var dict = {};
        var errors = "";
        $.each(function(){
          $tr.find('.' + $(this).attr('id')).html( $(this).val()+"-"+sku_group );
          var type = $(this).attr('id');
          var value = $(this).val();
          console.log(type + " : " + value);
          // ----- Switch statement that provides validation for each table cell -----
          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");
    });

  });

insert-group.php script:

insert-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);

?>

EDIT

编辑

My html table:

我的html表:

<table id="skuTable" cellspacing="5" class="ui-widget ui-widget-content">
    <thead>
        <tr class="ui-widget-header">
            <th class="skuRow">SKU Group</th>
            <th class="skuRow">Group ID</th>
            <th class="skuRow">Edit</th>
            <th class="skuRow">Delete</th>
        </tr>
    </thead>
    <tbody>

        <?php foreach ($dbh->query($sql_table) as $rows) { ?>

        <tr>
            <td class="sku_group" id="sku_group-<?php echo intval ($rows['SKU Group'])?>"><?php echo $rows['SKU Group']?></td>
            <td class="group_id" align="center" id="group_id-<?php echo intval ($rows['Group_ID'])?>"><?php echo $rows['Group_ID']?></td>
            <td><button type="button" class="edit" name="edit">Edit</button></td>
            <td><button type="button" class="delete" onclick="deleteRow(this)">Delete</button></td>
        </tr>
    <?php
        }
    ?>
    </tbody>
</table>

2 个解决方案

#1


1  

Your value does not good Try to change

你的价值不好尝试改变

var value = $(this).val();

To

var value = $(this).find('input[type=text]').val();

#2


0  

Try changing your $.each function to $tr.each. I think you should provide something for it to iterate over. Here is the link to .each() documentation.. If you want to iterate over all 's you have to add td to jquery call.

尝试将$ .each函数更改为$ tr.each。我认为你应该提供一些东西来迭代。这是.each()文档的链接..如果你想迭代所有的,你必须将td添加到jquery调用。

My fix would look like this:

我的修复将如下所示:

    var $tr = $( "#skuTable tbody tr td" ).eq(0).clone();  //get all td of sku-table
    var dict = {};
    $tr.each(function(){
      var type = $(this).attr('id');    // get value of current tr
      var value = $(this).html();       // get html content inside of tr

      switch (type) {
        case "group":
            dict["SKU Group"] = value;
            break;
        }
    });

    $('#group').val(dict['SKU Group']);  // set value of the input field

#1


1  

Your value does not good Try to change

你的价值不好尝试改变

var value = $(this).val();

To

var value = $(this).find('input[type=text]').val();

#2


0  

Try changing your $.each function to $tr.each. I think you should provide something for it to iterate over. Here is the link to .each() documentation.. If you want to iterate over all 's you have to add td to jquery call.

尝试将$ .each函数更改为$ tr.each。我认为你应该提供一些东西来迭代。这是.each()文档的链接..如果你想迭代所有的,你必须将td添加到jquery调用。

My fix would look like this:

我的修复将如下所示:

    var $tr = $( "#skuTable tbody tr td" ).eq(0).clone();  //get all td of sku-table
    var dict = {};
    $tr.each(function(){
      var type = $(this).attr('id');    // get value of current tr
      var value = $(this).html();       // get html content inside of tr

      switch (type) {
        case "group":
            dict["SKU Group"] = value;
            break;
        }
    });

    $('#group').val(dict['SKU Group']);  // set value of the input field