如何使用ajax插入mysql表? [英] How to insert into mysql table using ajax?

查看:43
本文介绍了如何使用ajax插入mysql表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用ajax将数据插入表中,以便在不重新加载页面的情况下插入数据.

I want to insert data into table using ajax so data will insert without reload of page.

这段代码可以很好地将数据插入表中,但是代码也可以重新加载页面.

This code insert data into table very well but code also reload the page.

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

But I want insert without reloading of page.

我该怎么做?

<?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>

推荐答案

尝试将其添加到表单onsubmit ="return Submitform();"

try this add this to form 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;
  }

这篇关于如何使用ajax插入mysql表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆