使用Ajax、PHP、MYSQL更新表单

4
我找到了一个自动提交表单数据的教程,但我只想添加一个提交按钮来将数据传递给ajax。我的目标是创建一个包含多个输入框的表单,当用户点击提交按钮时,通过ajax发送数据并更新页面,而不重新加载页面。另外一个关键点是它将所有输入框中的输入都发布到一个数组中,以便在运行更新脚本时,输入字段的名称属性与数据库中的列匹配。我认为我已经接近成功了,但我搜索了很久也没有找到完全符合我的解决方案。谢谢您提前的帮助。
<script type="text/javascript" src="/js/update.js"></script>

<form method="POST" action="#" id="myform">

    <!-- start id-form -->
    <table border="0" cellpadding="0" cellspacing="0"  id="id-form">
    <tr>
        <th valign="top">Business Name:</th>
        <td><input type="text" name="company_name" class="inp-form" /></td>
        <td></td>
    </tr>
    <tr>
        <th valign="top">Address 1:</th>
        <td><input type="text" name="address_1" class="inp-form" /></td>
        <td></td>
    </tr>
    <tr>
        <th valign="top">Address 2:</th>
        <td><input type="text" name="address_2" class="inp-form" /></td>
        <td></td>
    </tr>



<tr>
    <th>&nbsp;</th>
    <td valign="top">
            <input id="where" type="hidden" name="customer_id" value="1" />
            <button id="myBtn">Save</button>

<div id="alert">    
    </td>
    <td></td>
</tr>
</table>
<!-- end id-form  -->
</form>

update.js

var myBtn = document.getElementById('myBtn'); 
myBtn.addEventListener('click', function(event) {

updateform('form1'); }); 

function updateform(id){
        var data = $('#'+id).serialize();
       // alert(data);
         $.ajax({
            type: 'POST',
            url: "/ajax/update_company_info.php",
            data: data,
             success: function(data) {
                 $('#id').html(data);


                 $('#alert').text('Updated');
                 $('#alert').fadeOut().fadeIn();

              },
              error: function(data) { // if error occured
                    alert("Error occured, please try again");
                },
                        }); }

update_customer_info.php

<?php

include($_SERVER['DOCUMENT_ROOT'] . '/load.php');

// FORM: Variables were posted
if (count($_POST))
{
$data=unserialize($_POST['data']);
// Prepare form variables for database
foreach($data as $column => $value)
    ${$column} = clean($value);

// Perform MySQL UPDATE
$result = mysql_query("UPDATE customers SET ".$column."='".$value."'
    WHERE ".$w_col."='".$w_val."'")
    or die ('Error: Unable to update.');
}


?>

“culumn”变量应包含什么内容? - Amin Jafari
@AminJafari 应该是数据库中的一个列,例如有一个名为 company_name、address_1、address_2 的列,然后从表单提交的值将被更新到数据库中。 - Chad Priddle
好的,我明白了,正在处理中。 - Amin Jafari
你正在将 col: column 设置为提交按钮 $(".submit").click(function() { var input = $(this); var column = input.attr('name'); 的名称属性,但根据你的表单代码,它并没有被设置。 - Sean
危险:您正在使用过时的数据库API,应该使用现代替代品。您还容易受到SQL注入攻击,而现代API可以更容易地保护您自己。 - Quentin
3个回答

2

最终我解决了问题。感谢大家的帮助。

<p id="alert"></p>    
<form id="form" method="post" action="/ajax/update_company_info.php">

    <!-- start id-form -->
    <table border="0" cellpadding="0" cellspacing="0"  id="id-form">
    <tr>
        <th valign="top">Business Name:</th>
        <td><input type="text" name="company_name" class="inp-form" /></td>
        <td></td>
    </tr>
    <tr>
        <th valign="top">Address 1:</th>
        <td><input type="text" name="address_1" class="inp-form" /></td>
        <td></td>
    </tr>
    <tr>
        <th valign="top">Address 2:</th>
        <td><input type="text" name="address_2" class="inp-form" /></td>
        <td></td>
    </tr>



<tr>
    <th>&nbsp;</th>
    <td valign="top">
            <input id="where" type="hidden" name="customer_id" value="1" />
            <input type="submit" value="Save" id="submit">

    </td>
    <td></td>
</tr>
</table>
<!-- end id-form  -->
</form>

update.js

$(document).ready(function() {

$('form').submit(function(evt) {
  evt.preventDefault();

   $.each(this, function() {
            // VARIABLES: Input-specific
            var input = $(this);
            var value = input.val();
            var column = input.attr('name');

            // VARIABLES: Form-specific
            var form = input.parents('form');
            //var method = form.attr('method');
            //var action = form.attr('action');

            // VARIABLES: Where to update in database
            var where_val = form.find('#where').val();
            var where_col = form.find('#where').attr('name');

  $.ajax({
      url: "/ajax/update_company_info.php",
      data: {
                        val: value,
                        col: column,
                        w_col: where_col,
                        w_val: where_val
      },
      type: "POST",
      success: function(data) {         

      $('#alert').html("<p>Sent Successfully!</p>");

                        }

  }); // end post
  });// end each input value
}); // end submit
}); // end ready

update_customer_info.php

    <?php

include($_SERVER['DOCUMENT_ROOT'] . '/load.php');

function clean($value)
{
    return mysql_real_escape_string($value);
}
// FORM: Variables were posted
if (count($_POST))
{

    // Prepare form variables for database
    foreach($_POST as $column => $value)
        ${$column} = clean($value);

    // Perform MySQL UPDATE
    $result = mysql_query("UPDATE customers SET ".$col."='".$val."'
        WHERE ".$w_col."='".$w_val."'")
        or die ('Error: Unable to update.');
}
?>

0
  1. 我认为你想在提交表单时更新表单,所以你应该用下面给出的按钮替换提交按钮。

    <button id="myBtn">保存</button>。
    
  2. 你应该在js文件中添加以下代码。

    var myBtn = document.getElementById('myBtn'); 
    myBtn.addEventListener('click', function(event){ 
        Updateform('给出表单的id'); 
    }); 
    function updateform(id){
        var data = $('#'+id).serialize();
        // alert(data);
        $.ajax({
            type: 'POST',
            url: "/ajax/update_company_info.php",
            data: data,
            success: function(data) {
                $('#id').html(data);
                // alert(data);
                //alert(data);
            },
            error: function(data) { // 如果发生错误
                alert("发生错误,请重试");
            },
        });
    
    1. 你可以使用unserialize()将输入值作为数组在php代码中检索。因此,你可以将数据保存到数据库中并进行任何操作。希望你能得到答案。因此,你的代码将变成

         <form method="POST" action="#" id="form1">
          <!-- start id-form -->
         <table border="0" cellpadding="0" cellspacing="0"  id="id-form">
         <tr>
          <th valign="top">商业名称:</th>
          <td><input type="text" name="company_name" class="inp-form" /></td>
          <td></td>
      </tr>
      <tr>
          <th valign="top">地址 1:</th>
          <td><input type="text" name="address_1" class="inp-form" /></td>
          <td></td>
      </tr>
      <tr>
          <th valign="top">地址 2:</th>
          <td><input type="text" name="address_2" class="inp-form" /></td>
          <td></td>
      </tr>
         <tr>
      <th>&nbsp;</th>
      <td valign="top">
              <input id="where" type="hidden" name="customer_id" value="1" />
          <button id="myBtn">保存</button>
      </td>
      <td></td> </tr> </table> <!-- end id-form  --> </form> 
      

      你的js代码变成了

       var myBtn = document.getElementById('myBtn'); 
       myBtn.addEventListener('click', function(event)
      {   Updateform('form1'); }); 
      function updateform(id){
                  var data = $('#'+id).serialize();
                 // alert(data);
                   $.ajax({
                      type: 'POST',
                      url: "/ajax/update_company_info.php",
                      data: data,
                       success: function(data) {
                           $('#id').html(data);
                     // alert(data);
                       //alert(data);
                        },
                        error: function(data) { // 如果发生错误
                              alert("发生错误,请重试");
                          },
                                  }); }
      

    update_company_info.php将变成

           $data=unserialize($_POST['data']);
            // 你可以从数据数组中检索所有值并保存所有值。
    

    ?>


我根据您的建议更新了我的原始问题,并将$data值重新添加到foreach函数中。 - Chad Priddle

0

不要:

$(".submit").click(function() {

将表单设置一个 id,例如 'myform': <form method="POST" action="#" id="myform"> 使用以下代码来阻止默认的表单提交行为:
$("#myform").submit(function(e) {
 e.preventDefault();
 //your code
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接