如何使用ajax插入mysql表?

时间:2014-03-19 11:01:23

标签: javascript php jquery mysql 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>

3 个答案:

答案 0 :(得分:1)

来自事件处理函数的

return false

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

考虑转移到modern methods of event binding

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

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

});