【问题标题】:Insert into mysql database from html form without redirecting [duplicate]从html表单插入mysql数据库而不重定向[重复]
【发布时间】:2016-05-29 06:13:41
【问题描述】:

我正在使用一个 mysql 数据库和一个我试图与之通信的网页。

这是我的情况:

我有一个 listmat.php 文件,它可以回显表 Material 中的所有记录,并且它可以工作。

现在我设法在特定的div 中显示listmat.php 文件的输出,而无需使用以下代码刷新漏洞页面:

<script>
$(document).ready(function(){
  $("#matbutton").click(function(){
    $("#matins").load('listmat.php');
  });
});
</script>

matbutton 是表单中提交按钮的 ID,matinsdiv 的 ID,其中我显示了 listmat.php 的输出

这是我的表格:

<form id="formmatins" method="post" action="listmat.php">
<p>Name:<input type="text" Name="Mat" id="Material"></p>
<center><input type="submit" value="Insert/Remove" id="matbutton"></center>`
</form>

我想做的是使用matbuttonlistmat.php 回显他的所有记录的表中插入文本框的值。这样每次我点击一条记录都会插入并在 div 中显示新表

问题是,如果我使用 post 方法在表单中插入按钮,通过单击它会重定向到输出更改页面,但如果我把它拿出来,回声工作但我显然无法将文本框的值传递给listmat.php 文件作为插入的参数,因为按钮对 post 方法不感兴趣。

我环顾四周,看起来解决方案在 jquery/ajax 中使用了一些铰接结构,但我真的不知道如何解决。任何帮助将不胜感激

更新

<script>
  $(function () {

    $('#formmatins').on('submit', function (e) {

      e.preventDefault();

      $.ajax({
        type: 'post',
        url: 'listmat.php',
        data: $('#formmatins').serialize(),
        success: function () {
        $("#matins").load('listmat.php');
          alert('form was submitted');
        }
      });

    });

  });
</script>

再次切换页面

更新

<?php
$user = "**";
$pass = "**";
$db = "**";
$host = "localhost";

$con = mysqli_connect($host,$user,$pass,$db);
        if (mysqli_connect_errno())
       {
           echo "Failed to connect to MySQL: " . mysqli_connect_error();
       }
$m = $_POST['Mat']; //the text box in the form
$ins = $con->query("INSERT INTO mattemp (Material) VALUES ('$m')");
$query = $con->query("SELECT Material FROM mattemp");
while ($row = $query->fetch_assoc()) {
  echo $row['Material']."<br>";
    }
?>

它打印每次更新的表格,但仍然在一个新页面中......我做错了什么?

自己解决

感谢所有试图帮助我的人。在帖子上给我 -1 的解决方案不正确,这里是我的代码的解决方案,以防有人遇到同样的问题

`<script>
  $(function () {
    $('#matbutton').on('click', function(event){
      event.preventDefault();
      $.ajax({
        type: 'post',
        url: 'listmat.php',
        data: $('#formmatins').serialize(),
        success: function (data) {
        $("#matins").load('listmat.php');}
      });

    });

  });
</script>`

【问题讨论】:

  • 该问题有大量重复项,请学习使用 Google
  • 我认为这是不同的,因为它调用了两个不同的函数,一个 div 中的显示值和一个插入到表中的函数
  • $('#formmatins').on('submit', function (e) { 它缺少# 所以是data: $('formmatins').serialize(),
  • 完成,没有任何改变
  • 看起来 e.preventDefault() 不起作用...在 php 文件中一切正常问题是表格的回声正在新页面中显示(相对于 php 文件的页面) 而不是在 div 中

标签: php jquery html mysql ajax


【解决方案1】:

你需要$.ajax

例如:

$.ajax({
    url: "your_url.php",
    type: "POST",
    data: $('#formmatins').serialize(),
    success: function(response){
        // Do something, or not...
    }
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-26
    • 2014-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多