douchen2025 2017-02-16 13:31
浏览 65

使用JavaScript / AJAX将行插入数据库

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); and it returns sku_group-0 : in the logs. 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. 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.

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

HTML of Add button:

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

HTML of Popup Box:

<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:

$( 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:

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

?>
  • 写回答

1条回答 默认 最新

  • duanrui3480 2017-02-16 13:37
    关注

    Modify the statement

    sku_group = $( "#group" )
    

    with

    sku_group = $( "#group" ).val();
    

    This should solve your problem.

    Edit to Save TxtValue into Database...

     $(function () {
            var TxtValue = $("#group").val();
    
            $("#submit").click(function (e) {
    
                    e.preventDefault();
                if(!TxtValue){
                    $.ajax({
                        type: "POST",
                        url: "insert-group.php",
                        data: {[agrumentName]: TxtValue},
                        success: function(e){
                            console.log(e);
                            console.log("Row Insrerted");
                        }
                    });
                }
                else{
                    console.log("Cannot Insert Null Value");
                }
            })
        })
    

    replace [agrumentName] with your server function argument.

    Hope this helps :)

    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)