简体   繁体   English

使用PHP / JavaScript / AJAX向数据库添加行

[英]Adding Row Using PHP/JavaScript/AJAX to Database

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 that was 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(type + " : " + value); 我没有看到任何错误,但是在我的JavaScript中,我做了console.log(type + " : " + value); and it returns sku_group-0 : in the logs. 并在日志中返回sku_group-0 : I also 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. 我也做了console.log(dict) ,日志中的输出是Object {}所以看起来好像没有记录输入的值。 I also am getting a successful row inserted message in the logs too so it definitely looks like it is just a matter of being able to get the values to be read so they can then be processed in the insert-group.php script. 我也在日志中也获得了成功的row inserted消息,因此它看起来肯定只是能够读取值的问题,因此可以在insert-group.php脚本中对其进行处理。

So my question is how can I get it to read the value in the JavaScript so that it can be successfully entered into the database? 所以我的问题是如何获取它以读取JavaScript中的值,以便可以将其成功输入数据库中?

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>

HTML of Add button: 添加按钮的HTML:

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

JavaScript: 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");
    });

  });

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

?>
    REPLACE 
    "data: dict" 
    WITH 
    data:{ 'SKU_Group' : $('#group').val() } 

    AND 

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

您应该通过以下方式获得输入值:

$('#group').val()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM