繁体   English   中英

如何使用ajax插入mysql表?

[英]How to insert into mysql table using ajax?

我想使用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>

从事件处理函数return false

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

考虑转向现代事件绑定方法

试试这个添加它来形成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;
  }

你必须创建一个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);
    });
}

});

暂无
暂无

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

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