简体   繁体   English

如何使用ajax插入mysql表?

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

I want to insert data into table using ajax so data will insert without reload of page. 我想使用ajax将数据插入表中,因此数据将插入而无需重新加载页面。

This code insert data into table very well but code also reload the page. 此代码很好地将数据插入表中,但代码也重新加载页面。

But I want insert without reloading of page. 但我想要插入而不重新加载页面。

How can i do this ? 我怎样才能做到这一点 ?

<?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 from your event handler function. 从事件处理函数return false

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

Consider moving to modern methods of event binding . 考虑转向现代事件绑定方法

try this add this to form onsubmit = "return submitform();" 试试这个添加它来形成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;
  }

You have to create a php file that insert into your table the posted data and call it with ajax like that : 你必须创建一个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