php 使用php表单将记录添加到mysql数据库而无需离开/刷新页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25245272/
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
Add records to mysql database with php form without leaving/refreshing the page
提问by Acidon
I use this file input.phpto add record to database:
我使用这个文件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");
}
And my page with form page-with-form.php:
我的页面带有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>
Everything works fine: When I click "Send" button, input.php adds record and redirects back to page-with-form.php. You can't even see input.php loading, however you do see the page-with-form.php getting refreshed.
一切正常:当我单击“发送”按钮时,input.php 添加记录并重定向回 page-with-form.php。您甚至看不到 input.php 加载,但是您确实看到 page-with-form.php 得到刷新。
Is there a way to make all the operation without refreshing the page-with-form.php? I think it has to do with Ajax, but maybe there is another way? looking forward for your suggestions!
有没有办法在不刷新page-with-form.php的情况下进行所有操作?我认为这与 Ajax 有关,但也许还有另一种方式?期待您的建议!
回答by Oluwakayode Dagbo
You want to use AJAX to submit your form,
您想使用 AJAX 提交表单,
You can use JQuery to aid in this, the first thing you need to do is make sure your form does not refresh the page, and give your button an ID, this makes it easier to find the button through JQuery
您可以使用 JQuery 来帮助实现这一点,您需要做的第一件事是确保您的表单不会刷新页面,并为您的按钮指定一个 ID,这样可以更轻松地通过 JQuery 找到该按钮
first lets remove that line from your PHP code that causes a server side redirect, and instead have it produce a string stating that the data was saved succesfully, whatever this script prints in the HTTP response will be used by the ajax portion of this project
首先让我们从导致服务器端重定向的 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");
}
Then lets modify the HTML to make it easier for Jquery to find the elements we need and output a status (this is not the only way, if you have multiple forms this is not recommended, Jquery has more sophisticated ways of finding form elements http://api.jquery.com/input-selector/)
然后让我们修改 HTML,让 Jquery 更容易找到我们需要的元素并输出状态(这不是唯一的方法,如果你有多个表单,不推荐这样做,Jquery 有更复杂的查找表单元素的方法http: //api.jquery.com/input-selector/)
I just want to simply illustrate the idea rather then getting too much into Jquery details.
我只想简单地说明这个想法,而不是过多地了解 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>
now for the Javascript version that will implement AJAX using the help of Jquery
现在对于将使用 Jquery 的帮助实现 AJAX 的 Javascript 版本
What the Javascript will do is, when you click the button, it will post to your input.php and input PHP will return a result text.
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);
}
});
What should happen is, you enter data into your form and you will see a status appear of it being successful or an error, if successful the form will clear for you to add more input.
应该发生的是,您在表单中输入数据,您将看到成功或错误的状态,如果成功,表单将清除以供您添加更多输入。
回答by Pradeep Khodke
you have to use ajax to insert data into mysql without page refreh
您必须使用ajax将数据插入mysql而无需页面刷新
<form method='post' id='SaveForm' action="#">
<table class='table table-bordered'>
<tr>
<td>Name</td>
<td><input type='text' name='name' /></td>
</tr>
<tr>
<td>Employee Department</td>
<td><input type='text' name='dept' ></td>
</tr>
<tr>
<td colspan="2">
<button type="submit" name="btn-save" id="btn-save"></button>
</td>
</tr>
</table>
and the PHP code would be :
PHP代码将是:
<?php
if($_POST)
{
$emp_name = $_POST['name'];
$emp_dept = $_POST['dept'];
try{
$stmt = $db_con->prepare("INSERT INTO tbl_employees(emp_name,emp_dept) VALUES(:ename, :edept)");
$stmt->bindParam(":ename", $emp_name);
$stmt->bindParam(":edept", $emp_dept);
if($stmt->execute())
{
echo "Successfully Added";
}
else{
echo "Query Problem";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
and the jquery ajax code is :
和 jquery ajax 代码是:
/* Data Insert Starts Here */
$(document).on('submit', '#emp-SaveForm', function() {
$.post("create.php", $(this).serialize())
.done(function(data){
$("#dis").fadeIn('slow', function(){
$("#dis").html('<div class="alert alert-info">'+data+'</div>');
$("#emp-SaveForm")[0].reset();
});
});
return false;
});
/* Data Insert Ends Here */
click the following link to get detailed article :
点击以下链接获取详细文章:
回答by Adsy2010
You want
你要
Button.click(function(){
$.Ajax(
Data: data,
Success:
What you want to do on success
Such as set HTML to div element
)
})
Just look up the jQuery API for Ajax, its all there.
只需查找 Ajax 的 jQuery API,就可以了。
Written on mobile so can expand answer later if you want me to.
写在手机上,所以如果你想要我以后可以扩展答案。
回答by Belal Khan
You will have to use ajax for achieving your goal Lets take example of this simple html form
您将不得不使用 ajax 来实现您的目标让我们以这个简单的 html 表单为例
<form id='myform' action='insert.php' method='post'>
Name: <input type='text' name='name' />
Address: <input type='text' name='address' />
</form>
And the php is
而 php 是
$name = $_POST['name'];
$address= $_POST['address'];
$sql = "insert into peoples (name,address) values('$name','$address')";
if(mysql_query($sql)){
echo 'successfully inserted';
}else{
echo 'could not insert';
}
And your Javascript with jQuery is
你的 Javascript 和 jQuery 是
$('#myform').submit(function(){ return false; });
$('#submit').click(function(){
$.post($('#myform').attr('action'),
$('#myform :input').serializeArray(),
function(output){ $('#result').html(output); }); });