使用php表单将记录添加到mysql数据库而无需离开/刷新页面

Aci*_*don 4 html php mysql forms ajax

我使用这个文件input.php将记录添加到数据库:

$order = "INSERT INTO wp_userdata
            (username, product_name, product_brand)
            VALUES
            ('$_POST[username]',
                        '$_POST[name]',
            '$_POST[brand]')";


$result = mysql_query($order);  
if($result){
    header( 'Location: http://page-with-form.php' ) ;
} else{
    echo("<br>Input data is fail");
}
Run Code Online (Sandbox Code Playgroud)

而我的页面带有表单page-with-form.php

<table border="1">
  <tr>
    <td align="center">Add Products</td>
  </tr>
  <tr>
    <td>
      <table>
        <form method="post" action="input.php">
<input type="hidden" name="username" value="[insert_php]echo $username;[/insert_php]">
        <tr>
          <td>Product Name</td>
          <td><input type="text" name="name" size="50">
          </td>
        </tr>
        <tr>
          <td>Brand</td>
          <td><input type="text" name="brand" size="50">
          </td>
        </tr>
        <tr>
          <td></td>
          <td align="right"><input type="submit" name="submit" value="Send"></td>
        </tr>
</form>
        </table>
      </td>
    </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

一切正常:当我单击“发送”按钮时,input.php 添加记录并重定向回 page-with-form.php。您甚至看不到 input.php 加载,但是您确实看到 page-with-form.php 得到刷新。

有没有办法在不刷新page-with-form.php的情况下进行所有操作?我认为这与 Ajax 有关,但也许还有另一种方式?期待您的建议!

小智 5

您想使用 AJAX 提交表单,

您可以使用 JQuery 来帮助实现这一点,您需要做的第一件事是确保您的表单不会刷新页面,并为您的按钮指定一个 ID,这样可以更轻松地通过 JQuery 找到该按钮

首先让我们从导致服务器端重定向的 PHP 代码中删除该行,而是让它生成一个字符串,说明数据已成功保存,该脚本在 HTTP 响应中打印的任何内容都将被该项目的 ajax 部分使用

$order = "INSERT INTO wp_userdata
            (username, product_name, product_brand)
            VALUES
            ('$_POST[username]',
                        '$_POST[name]',
            '$_POST[brand]')";


$result = mysql_query($order);  
if($result){
    echo ("DATA SAVED SUCCESSFULLY");
} else{
    echo("Input data is fail");
}
Run Code Online (Sandbox Code Playgroud)

然后让我们修改 HTML,让 Jquery 更容易找到我们需要的元素并输出状态(这不是唯一的方法,如果你有多个表单,不推荐这样做,Jquery 有更复杂的方法来查找表单元素http: //api.jquery.com/input-selector/ )

我只想简单地说明这个想法,而不是过多地了解 Jquery 细节。

<table border="1">
      <tr>
        <td align="center">Add Products</td>
      </tr>
      <tr>
        <td>
          <table>
            <!-- THIS TELLS THE FORM TO NOT REFRESH THE PAGE -->
            <form onsubmit="return false">
    <input type="hidden" name="username" id="hdn_username" value="[insert_php]echo $username;[/insert_php]">
            <tr>
              <td>Product Name</td>
              <td><input type="text" id="txt_name" name="name" size="50">
              </td>
            </tr>
            <tr>
              <td>Brand</td>
              <td><input type="text" id="txt_brand" name="brand" size="50">
              </td>
            </tr>
            <!-- THIS ROW WILL DISPLAY THE RESULT OF THE LAST ENTRY -->`
            <tr>
                <td></td>
                <td><div id="status_text" /></td>
            </tr>
            <tr>
              <td></td>
              <td align="right">
                <!-- I GAVE THE BUTTON AN ID THAT WILL MAKE IT EASIER TO FIND WITH JQUERY -->
                <input type="submit" id="btn_submit" name="submit" value="Send"></td>
            </tr>
    </form>
            </table>
          </td>
        </tr>
    </table>
Run Code Online (Sandbox Code Playgroud)

现在对于将使用 Jquery 的帮助实现 AJAX 的 Javascript 版本

Javascript 会做的是,当您单击按钮时,它会发布到您的 input.php 并且输入 PHP 将返回一个结果文本。

//on the click of the submit button 
$("#btn_submit").click(function(){
 //get the form values
 var username = $('#hdn_username').val();     
 var name = $('#txt_name').val();     
 var brand = $('#txt_brand').val(); 

 //make the postdata
 var postData = 'username='+username+'&name='+name+'&brand='+brand;

 //call your input.php script in the background, when it returns it will call the success function if the request was successful or the error one if there was an issue (like a 404, 500 or any other error status)

 $.ajax({
    url : "input.php",
    type: "POST",
    data : postData,
    success: function(data,status, xhr)
    {
        //if success then just output the text to the status div then clear the form inputs to prepare for new data
        $("#status_text").html(data);
        $('#name').val('');
        $('#brand').val('');
    },
    error: function (jqXHR, status, errorThrown)
    {
        //if fail show error and server status
        $("#status_text").html('there was an error ' + errorThrown + ' with status ' + textStatus);
    }
});
Run Code Online (Sandbox Code Playgroud)

应该发生的情况是,您将数据输入到表单中,您将看到显示成功或错误的状态,如果成功,表单将清除以供您添加更多输入。