簡體   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