【问题标题】:How to insert into mysql table using ajax?如何使用ajax插入mysql表?
【发布时间】:2014-04-25 13:42:39
【问题描述】:

我想使用 ajax 将数据插入到表中,这样数据将在不重新加载页面的情况下插入。

这段代码很好地将数据插入到表中,但代码也会重新加载页面。

但我想插入而不重新加载页面。

我该怎么做?

<?php
include('connection.php');
if(isset($_POST['cmt'])){
    $comment = addslashes($_POST['cmt']);
    $alertid = $_POST['alert_id'];
    mysql_query("INSERT INTO `comments` (`id`, `alert_id`, `comment`, `username`) VALUES (NULL, '".$alertid."', '".$comment."', 'tomas')");
}
?>


<script>
  function submitform(){
    var comment = $("#comment").val();
    var alertid = $("#alertid").val();
    $.ajax({
        type: "POST",
        //url: "ana.php",
        data:{cmt:comment,alert_id:alertid}
    }).done(function( result ) {
        $("#msg").html( result );
    });

  }
</script>

<form method = "POST" onsubmit = "submitform()">
   <textarea onFocus = "myFunction(1)" onBlur = "myFunction(0)" style="margin: 0px 0px 8.99305534362793px; width: 570px; height: 50px;" rows = "6" cols = "40" id = "comment"></textarea><br />
   <input type = "text" placeholder="Enter Maximium 100 Words" id = "alertid" value = "10">
   <input  type = "submit" name = "submit" value = "Comment">
</form>

【问题讨论】:

标签: javascript php jquery mysql ajax


【解决方案1】:

return false 来自您的事件处理函数。

onsubmit="submitform(); return false;">

考虑转移到modern methods of event binding

【讨论】:

    【解决方案2】:

    您必须创建一个 php 文件,将发布的数据插入到您的表中,并像这样使用 ajax 调用它:

    $.ajax({
    url: "/file.php",
    type: "POST",
    cache: false,
    dataType: "json",
    data: postValue,
    success: function(results) {
        bootbox.alert(results.message, function() {
            bootbox.setIcons(null);
            window.location.reload();
        });
    },
    error: function(results) {
        bootbox.alert(results.message, function() {
            bootbox.setIcons(null);
        });
    }
    

    });

    【讨论】:

      【解决方案3】:

      尝试将此添加到表单 onsubmit = "return submitform();"

       function submitform(){
          var comment = $("#comment").val();
          var alertid = $("#alertid").val();
          $.ajax({
              type: "POST",
              //url: "ana.php",
              data:{cmt:comment,alert_id:alertid}
          }).done(function( result ) {
              $("#msg").html( result );
          });
          return false;
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-16
        • 2017-06-13
        • 2014-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-07
        • 2014-11-26
        相关资源
        最近更新 更多