【问题标题】:jQuery serialized data not being inserted into the databasejQuery序列化数据未插入数据库
【发布时间】:2013-10-06 04:34:12
【问题描述】:

我正在做三件事。

我正在使用以下 HTML 表单向 jQuery 发送信息。

        <div id="note_add_container">
            <form id="note_add" method="post">
                <input type="text" name="name" placeholder="name" />
                <input type="text" name="location" placeholder="location" />
                <button id="submit_note">Add note!</button>
            </form>
        </div>

这是我用来将此类序列化信息发布到数据库中的 jQuery 脚本。

   $('button').click(function () {  
        $.ajax ({
            type: "POST",
            url: "post.php",
            data: $('#note_add').serialize(), 
            success: function(){
                  alert("Done"); 
            }
        });    
    });

这是将信息插入数据库的 PHP。

$name = $_POST['name'];
$location = $_POST['location'];

$sql = "INSERT INTO get (name, location)
VALUES ('$name', '$location')";
if (!mysqli_query($connection, $sql)) {
    die('Error: ' . mysqli_error($link));
}

这不起作用。我单击按钮,没有任何反应。警报不会触发。任何人都可以引导我了解我的代码为什么不起作用的正确方向吗?

【问题讨论】:

  • 建议将ajax类型大写为POST
  • @AhsanShah 完成了,但还是没有运气,先生。

标签: php jquery html


【解决方案1】:

这不起作用。我单击按钮,没有任何反应。警报 不开火

您完全确定点击处理程序有效吗?您必须首先确保它可以正常工作,例如,

   $('button').click(function () {  
      alert('It works');
   });

如果它有效,那么您可以继续前进。否则检查它是否在 DOMReady $(function(){ ... }) 内部以及 jquery.js 是否已加载。

假设它有效,

你怎么知道你的 PHP 脚本返回了什么?你只是假设它“应该工作”,在这里:

 success: function(){
  alert("Done"); 
 }

success() 方法实际上保存了一个变量,该变量是来自服务器端的响应。应该改写为,

 success: function(serverResponse){
  alert(serverResponse); 
 }

至于 PHP 脚本,

if (!mysqli_query($connection, $sql)) {
    die('Error: ' . mysqli_error($link));
}

您只能通过“回显”错误消息来处理失败。当mysqli_query() 返回TRUE 时,您不会处理这种情况。您应该发送类似1 的信息来表示成功。

最后你的代码应该是这样的,

   $('#submit_note').click(function() {  
        $.ajax ({
            type: "POST",
            url: "post.php",
            data: $('#note_add').serialize(), 
            success: function(serverResponse) {
                  if (serverResponse == "1") {
                    alert('Added. Thank you');
                  } else {
                     // A response wasn't "1", then its an error
                     alert('Server returned an error ' + serverResponse);
                  }
            }
        });    
    });

PHP:

$sql = "INSERT INTO get (name, location)
VALUES ('$name', '$location')";

if (!mysqli_query($connection, $sql)) {
    die(mysqli_error($connection));
} else {
    die("1"); // That means success
}

/**
 * Was it $connection or $link?! Jeez, you were using both.
 * 
 */

【讨论】:

  • 我花了 2 年时间将此问题标记为已回答。谢谢!
【解决方案2】:

您在$.ajax 调用中指定的回调函数只会在收到来自服务器的响应时触发。由于在将数据插入数据库后,您永远不会从服务器将任何内容发送回客户端,因此客户端永远不会调用alert("Done");。在您的 PHP 文件中添加一行,在成功插入 SQL 后向客户端发送响应。响应可以像一个 JSON 对象一样简单,上面写着{'status': 'success'}

【讨论】:

  • 不过,没有任何东西被插入到数据库中。 jQuery 序列化数据未插入数据库。
  • alerted 什么都没有的原因仍然存在。但是,没有数据插入的问题完全是另一个问题。您能否检查 $name$location 的值以确保它们从请求中正确填充?
  • 当我取出 jQuery 并在提供的表单中添加一个 action="" 时,它就像一个魅力。现在关于检查它们,我该怎么做?该网页不会重新加载或返回任何内容或将我带到 php 文件。非常感谢您的帮助。
  • 所以问题不在于您的数据没有被插入,而是您的POST 请求根本没有被触发。至于网页在请求触发后没有响应,就像我说的那样,要让javascript调用回调函数(例如alert()),您需要从服务器向客户端发送响应......
  • 为什么响应应该是JSON 对象?为什么它不能是“1”(成功)或“0”(失败)?如果您同时处理多个值,那么可以坚持使用 JSON,因为您没有更好的选择。
【解决方案3】:

您应该采用更好的方式来处理您的表单。 serialize() 有帮助,但最好将数据处理成 JSON 字符串。使用 JSO 时,您还需要在 ajax 调用中设置 dataType。

$('#note_add').submit(function (event) {
    event.preventDefault();

    var formdata = $('#note_add').serializeArray();
    var formobject = {};

    $(formdata).each(function (event) {
        formobject[formdata[event].name] = formdata[event].value;
    });

    var data = {
        action: "formsend",
        json: JSON.stringify(formobject)
    };

    //* * send with ajax * *

    function sendajax(data) {
        var deferred = $.ajax({
            method: "post",
            url: "ajax.php",
            dataType: "json",
            data: data
        });
        return deferred.promise();
    }

    sendajax(formdata).done(function (response) {
        console.log(response);
        if (response.success == true) {
            alert("Done!");
        }
    })
});

赶上 PHP

if(isset($_POST['action']) && $_POST['action'] == 'formsend') {

  $data = json_decode($_POST['json'];

// here you can now access the $data with the fieldnames

  $name = $data->name;
  $location = $data->location;

 // Write to the database
$sql = "INSERT INTO get (name, location) VALUES ('$name', '$location')";
if (!mysqli_query($connection, $sql)) {
    die('Error: '.mysqli_error($link));
}

if (mysqli_affected_rows($connection) > 0) {
    echo json_encode(array("success" = > true, "message" = > "data is submitted"));
} else {
    echo json_encode(array("success" = > false, "message" = > "an error occurred"));
}
}

【讨论】:

  • OP 想知道mysqli_query() 是返回true 还是false。它的单一价值。为什么要发送多个值?
【解决方案4】:

将以下行添加到您的 php 文件以发送回响应:

HttpResponse::setCache(true);
HttpResponse::setContentType('text/html');       
HttpResponse::setData("<html>Success</html>");
HttpResponse::send();
flush();

改变ajax调用如下看结果:

  $('#submit_note').click(function () {  
        $.ajax ({
            type: "POST",
            url: "post.php",
            data: $('#note_add').serialize(), 
            success: function(respData) {
                  console.log('Response:', respData)
                  alert("Done"); 
            }
        });    
  });

【讨论】:

    【解决方案5】:
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="js/jquery-1.7.min.js"></script>
    <title></title>
    </head>
    <body>
    <div id="note_add_container">
      <form id="note_add" method="post">
        <input type="text" name="name" placeholder="name" />
        <input type="text" name="location" placeholder="location" />
        <button id="submit_note">Add note!</button>
      </form>
    </div>
    <div id="response"> </div>
    </body>
    <script type="text/javascript">
            $("#submit_note").click(function() {
                var url = "post.php"; // the script where you handle the form input.
                $.ajax({
                       type: "POST",
                       url: url,
                       data: $("#note_add").serialize(), // serializes the form's elements.
                       success: function(data)
                       {
                           $('#response').empty();
                           $('#response').append(data); // show response from the php script.
                       }
                     });
    
            return false; // avoid to execute the actual submit of the form.
        });
       </script>
    </html>
    

    post.php

    // Insert here your connection path
    
    <?php
    if((isset($_REQUEST['name']) && trim($_REQUEST['name']) !='') && (isset($_REQUEST['location']) && trim($_REQUEST['location'])!=''))
    {           
        $name = addslashes(trim($_REQUEST['name']));
        $location = addslashes(trim($_REQUEST['location']));    
    
        $sql = "INSERT INTO get (name, location) VALUES ('".$name."', '".$location."')";
        if (!mysqli_query($connection, $sql)) {
        die('Error: ' . mysqli_error($link));
        }
    
        echo "1 record added";
    }
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多