javascript 使用 Ajax、PHP、MYSQL 更新表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24858331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Update form using Ajax, PHP, MYSQL
提问by Chad Priddle
I found a tutorial that auto submits the form data but all I want to do is add a submit button to pass the data to ajax.
我找到了一个自动提交表单数据的教程,但我想要做的就是添加一个提交按钮将数据传递给 ajax。
My goal is to have a form with multiple inputs and when the user clicks the submit button it sends it through ajax and updates the page without reloading the page. Also, another key piece is the way it post all the inputs into an array so that when the update script is ran the name attributes from the input fields match the columns in the database.
我的目标是拥有一个具有多个输入的表单,当用户单击提交按钮时,它会通过 ajax 发送它并更新页面而不重新加载页面。此外,另一个关键部分是它将所有输入发布到数组中的方式,以便在运行更新脚本时,输入字段中的名称属性与数据库中的列匹配。
I think I'm close. I've searched and haven't found my exact solution. Thanks in advance.
我想我很接近了。我已经搜索过,但没有找到我的确切解决方案。提前致谢。
<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> </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
更新.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
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.');
}
?>
采纳答案by Chad Priddle
Ended up figuring it out. Thanks for everyones help.
终于想通了。谢谢大家的帮助。
<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> </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
更新.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
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.');
}
?>
回答by Rashid
I think that you want to update form when submit.so you should remove submit with a button given below.
<button id="myBtn">Save</button>.
You should add the given below code in ur js file.
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"); }, });
You can retrieve input value in your php code by using unserialize() as an array.So you can save data to database and whatever you want to.i hope you get the answer.Hence,your code will become
<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> </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>
Your js code become
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 will become
$data=unserialize($_POST['data']); // you can retrieve all values from data array and save all .
?>
我认为您想在提交时更新表单。所以您应该使用下面给出的按钮删除提交。
<button id="myBtn">Save</button>.
您应该在您的 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"); }, });
您可以通过使用 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">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> </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 .
?>
回答by Manwal
Instead of:
代替:
$(".submit").click(function() {
Give your form a id like 'myform': <form method="POST" action="#" id="myform">
给你的表单一个像“myform”这样的id: <form method="POST" action="#" id="myform">
And use this for preventing default submission of form:
并使用它来防止表单的默认提交:
$("#myform").submit(function(e) {
e.preventDefault();
//your code
}