使用Ajax, PHP, MYSQL更新表单

Update form using Ajax, PHP, MYSQL

本文关键字:更新 表单 MYSQL PHP Ajax 使用      更新时间:2023-09-26

我找到了一个教程,自动提交表单数据,但我想做的就是添加一个提交按钮,将数据传递给ajax。

我的目标是有多个输入的表单,当用户单击提交按钮时,它通过ajax发送并更新页面,而无需重新加载页面。另外,另一个关键部分是它将所有输入发送到一个数组中的方式,以便在运行更新脚本时,输入字段中的name属性与数据库中的列匹配。

我想我接近了。我已经搜索过了,但还没有找到确切的解。提前谢谢。

<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.');
}

?>

最后弄明白了。谢谢大家的帮助。

<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.');
}
?>
  1. 我认为你想在提交时更新表单。所以你应该使用下面的按钮删除提交。

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

    var myBtn = document.getElementById('myBtn'); 
    myBtn.addEventListener('click', function(event){ 
        Updateform('give id of the form'); 
    }); 
    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) { // if error occured
                alert("Error occured, please try again");
            },
        });
    
    1. 你可以在你的php代码中使用unserialize()来检索输入值作为数组。所以你可以保存数据到数据库和任何你想要的。我希望你能得到答案。因此,您的代码将变成

         <form method="POST" action="#" id="form1">
          <!-- 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>
      </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) { // if error occured
                              alert("Error occured, please try again");
                          },
                                  }); }
      

    update_company_info.php将变成

           $data=unserialize($_POST['data']);
            // you can retrieve all values from data array and save all .
    

    ?>

而不是:

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

给你的表单一个id像'myform': <form method="POST" action="#" id="myform">

并使用这个来防止表单的默认提交:

$("#myform").submit(function(e) {
 e.preventDefault();
 //your code
}