Javascript 带有 PHP 的 jQuery Ajax POST 示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5004233/
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
jQuery Ajax POST example with PHP
提问by Thew
I am trying to send data from a form to a database. Here is the form I am using:
我正在尝试将数据从表单发送到数据库。这是我正在使用的表格:
<form name="foo" action="form.php" method="POST" id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
The typical approach would be to submit the form, but this causes the browser to redirect. Using jQuery and Ajax, is it possible to capture all of the form's data and submit it to a PHP script (an example, form.php)?
典型的方法是提交表单,但这会导致浏览器重定向。使用 jQuery 和Ajax是否可以捕获所有表单数据并将其提交给 PHP 脚本(例如form.php)?
回答by mekwall
Basic usage of .ajax
would look something like this:
的基本用法.ajax
如下所示:
HTML:
HTML:
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
jQuery:
jQuery:
// Variable to hold request
var request;
// Bind to the submit event of our form
$("#foo").submit(function(event){
// Prevent default posting of form - put here to work in case of errors
event.preventDefault();
// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// Fire off the request to /form.php
request = $.ajax({
url: "/form.php",
type: "post",
data: serializedData
});
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Hooray, it worked!");
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});
});
Note: Since jQuery 1.8, .success()
, .error()
and .complete()
are deprecated in favor of .done()
, .fail()
and .always()
.
注意:自 jQuery 1.8 起,.success()
,.error()
和.complete()
被弃用,而支持.done()
,.fail()
和.always()
。
Note: Remember that the above snippet has to be done after DOM ready, so you should put it inside a $(document).ready()
handler (or use the $()
shorthand).
注意:请记住,上面的代码片段必须在 DOM 准备好后完成,因此您应该将它放在$(document).ready()
处理程序中(或使用$()
速记)。
Tip: You can chainthe callback handlers like this: $.ajax().done().fail().always();
提示:您可以像这样链接回调处理程序:$.ajax().done().fail().always();
PHP (that is, form.php):
PHP(即 form.php):
// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$bar = isset($_POST['bar']) ? $_POST['bar'] : null;
Note: Always sanitize posted data, to prevent injections and other malicious code.
注意:始终清理发布的数据,以防止注入和其他恶意代码。
You could also use the shorthand .post
in place of .ajax
in the above JavaScript code:
您还可以使用简写.post
代替.ajax
上面的 JavaScript 代码:
$.post('/form.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
Note: The above JavaScript code is made to work with jQuery 1.8 and later, but it should work with previous versions down to jQuery 1.5.
注意:上述 JavaScript 代码适用于 jQuery 1.8 及更高版本,但它应该适用于 jQuery 1.5 之前的版本。
回答by NullPoiиteя
To make an Ajax request using jQueryyou can do this by the following code.
要使用jQuery发出 Ajax 请求,您可以通过以下代码执行此操作。
HTML:
HTML:
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
<!-- The result of the search will be rendered inside this div -->
<div id="result"></div>
JavaScript:
JavaScript:
Method 1
方法一
/* Get from elements values */
var values = $(this).serialize();
$.ajax({
url: "test.php",
type: "post",
data: values ,
success: function (response) {
// You will get response from your PHP page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
Method 2
方法二
/* Attach a submit handler to the form */
$("#foo").submit(function(event) {
var ajaxRequest;
/* Stop form from submitting normally */
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get from elements values */
var values = $(this).serialize();
/* Send the data using post and put the results in a div. */
/* I am not aborting the previous request, because it's an
asynchronous request, meaning once it's sent it's out
there. But in case you want to abort it you can do it
by abort(). jQuery Ajax methods return an XMLHttpRequest
object, so you can just use abort(). */
ajaxRequest= $.ajax({
url: "test.php",
type: "post",
data: values
});
/* Request can be aborted by ajaxRequest.abort() */
ajaxRequest.done(function (response, textStatus, jqXHR){
// Show successfully for submit message
$("#result").html('Submitted successfully');
});
/* On failure of request this function will be called */
ajaxRequest.fail(function (){
// Show error
$("#result").html('There is error while submit');
});
The .success()
, .error()
, and .complete()
callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use .done()
, .fail()
, and .always()
instead.
的.success()
,.error()
和.complete()
回调不赞成使用的jQuery 1.8。要准备的代码为他们的最终消除,使用.done()
,.fail()
和.always()
来代替。
MDN: abort()
. If the request has been sent already, this method will abort the request.
MDN: abort()
. 如果请求已经发送,此方法将中止请求。
So we have successfully send an Ajax request, and now it's time to grab data to server.
所以我们已经成功发送了一个 Ajax 请求,现在是时候向服务器抓取数据了。
PHP
PHP
As we make a POST request in an Ajax call (type: "post"
), we can now grab data using either $_REQUEST
or $_POST
:
当我们在 Ajax 调用 ( type: "post"
)中发出 POST 请求时,我们现在可以使用$_REQUEST
或获取数据$_POST
:
$bar = $_POST['bar']
You can also see what you get in the POST request by simply either. BTW, make sure that $_POST
is set. Otherwise you will get an error.
您还可以通过简单地查看您在 POST 请求中获得的内容。顺便说一句,请确保$_POST
已设置。否则你会得到一个错误。
var_dump($_POST);
// Or
print_r($_POST);
And you are inserting a value into the database. Make sure you are sensitizingor escapingAll requests (whether you made a GET or POST) properly before making the query. The best would be using prepared statements.
您正在向数据库中插入一个值。在进行查询之前,请确保您正确地敏感或转义所有请求(无论是 GET 还是 POST)。最好的方法是使用准备好的语句。
And if you want to return any data back to the page, you can do it by just echoing that data like below.
如果你想将任何数据返回到页面,你可以通过像下面这样回显数据来实现。
// 1. Without JSON
echo "Hello, this is one"
// 2. By JSON. Then here is where I want to send a value back to the success of the Ajax below
echo json_encode(array('returned_val' => 'yoho'));
And then you can get it like:
然后你可以得到它:
ajaxRequest.done(function (response){
alert(response);
});
There are a couple of shorthand methods. You can use the below code. It does the same work.
有几种速记方法。您可以使用以下代码。它做同样的工作。
var ajaxRequest= $.post("test.php", values, function(data) {
alert(data);
})
.fail(function() {
alert("error");
})
.always(function() {
alert("finished");
});
回答by Mr. Alien
I would like to share a detailed way of how to post with PHP + Ajax along with errors thrown back on failure.
我想分享如何使用 PHP + Ajax 发布以及失败时返回的错误的详细方法。
First of all, create two files, for example form.php
and process.php
.
首先,创建两个文件,例如form.php
和process.php
。
We will first create a form
which will be then submitted using the jQuery
.ajax()
method. The rest will be explained in the comments.
我们将首先创建一个form
,然后使用该jQuery
.ajax()
方法提交。其余的将在评论中解释。
form.php
form.php
<form method="post" name="postForm">
<ul>
<li>
<label>Name</label>
<input type="text" name="name" id="name" placeholder="Bruce Wayne">
<span class="throw_error"></span>
<span id="success"></span>
</li>
</ul>
<input type="submit" value="Send" />
</form>
Validate the form using jQuery client-side validation and pass the data to process.php
.
使用 jQuery 客户端验证来验证表单并将数据传递给process.php
.
$(document).ready(function() {
$('form').submit(function(event) { //Trigger on form submit
$('#name + .throw_error').empty(); //Clear the messages first
$('#success').empty();
//Validate fields if required using jQuery
var postForm = { //Fetch form data
'name' : $('input[name=name]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php', //Your form processing file URL
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
if (!data.success) { //If fails
if (data.errors.name) { //Returned if any error from process.php
$('.throw_error').fadeIn(1000).html(data.errors.name); //Throw relevant error
}
}
else {
$('#success').fadeIn(1000).append('<p>' + data.posted + '</p>'); //If successful, than throw a success message
}
}
});
event.preventDefault(); //Prevent the default submit
});
});
Now we will take a look at process.php
现在我们来看看 process.php
$errors = array(); //To store errors
$form_data = array(); //Pass back the data to `form.php`
/* Validate the form on the server side */
if (empty($_POST['name'])) { //Name cannot be empty
$errors['name'] = 'Name cannot be blank';
}
if (!empty($errors)) { //If errors in validation
$form_data['success'] = false;
$form_data['errors'] = $errors;
}
else { //If not, process the form, and return true on success
$form_data['success'] = true;
$form_data['posted'] = 'Data Was Posted Successfully';
}
//Return the data back to form.php
echo json_encode($form_data);
The project files can be downloaded from http://projects.decodingweb.com/simple_ajax_form.zip.
项目文件可以从http://projects.decodingweb.com/simple_ajax_form.zip下载。
回答by Mr. Alien
You can use serialize. Below is an example.
您可以使用序列化。下面是一个例子。
$("#submit_btn").click(function(){
$('.error_status').html();
if($("form#frm_message_board").valid())
{
$.ajax({
type: "POST",
url: "<?php echo site_url('message_board/add');?>",
data: $('#frm_message_board').serialize(),
success: function(msg) {
var msg = $.parseJSON(msg);
if(msg.success=='yes')
{
return true;
}
else
{
alert('Server error');
return false;
}
}
});
}
return false;
});
回答by DDeme
HTML:
HTML:
<form name="foo" action="form.php" method="POST" id="foo">
<label for="bar">A bar</label>
<input id="bar" class="inputs" name="bar" type="text" value="" />
<input type="submit" value="Send" onclick="submitform(); return false;" />
</form>
JavaScript:
JavaScript:
function submitform()
{
var inputs = document.getElementsByClassName("inputs");
var formdata = new FormData();
for(var i=0; i<inputs.length; i++)
{
formdata.append(inputs[i].name, inputs[i].value);
}
var xmlhttp;
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest;
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
}
}
xmlhttp.open("POST", "insert.php");
xmlhttp.send(formdata);
}
回答by Shaiful Islam
I use the way shown below. It submits everything like files.
我使用如下所示的方式。它提交所有文件,如文件。
$(document).on("submit", "form", function(event)
{
event.preventDefault();
var url = $(this).attr("action");
$.ajax({
url: url,
type: 'POST',
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
console.log("error");
}
});
});
回答by Juned Ansari
If you want to send data using jQuery Ajax then there is no need of form tag and submit button
如果您想使用 jQuery Ajax 发送数据,则不需要表单标记和提交按钮
Example:
例子:
<script>
$(document).ready(function () {
$("#btnSend").click(function () {
$.ajax({
url: 'process.php',
type: 'POST',
data: {bar: $("#bar").val()},
success: function (result) {
alert('success');
}
});
});
});
</script>
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input id="btnSend" type="button" value="Send" />
回答by john
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<form method="post" id="form_content" action="Javascript:void(0);">
<button id="desc" name="desc" value="desc" style="display:none;">desc</button>
<button id="asc" name="asc" value="asc">asc</button>
<input type='hidden' id='check' value=''/>
</form>
<div id="demoajax"></div>
<script>
numbers = '';
$('#form_content button').click(function(){
$('#form_content button').toggle();
numbers = this.id;
function_two(numbers);
});
function function_two(numbers){
if (numbers === '')
{
$('#check').val("asc");
}
else
{
$('#check').val(numbers);
}
//alert(sort_var);
$.ajax({
url: 'test.php',
type: 'POST',
data: $('#form_content').serialize(),
success: function(data){
$('#demoajax').show();
$('#demoajax').html(data);
}
});
return false;
}
$(document).ready(function_two());
</script>
回答by pawan sen
Handling Ajax errors and loader before submit and after submitting success shows an alert boot box with an example:
在提交之前和提交成功之后处理 Ajax 错误和加载程序显示了一个带有示例的警报引导框:
var formData = formData;
$.ajax({
type: "POST",
url: url,
async: false,
data: formData, // Only input
processData: false,
contentType: false,
xhr: function ()
{
$("#load_consulting").show();
var xhr = new window.XMLHttpRequest();
// Upload progress
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
$('#addLoad .progress-bar').css('width', percentComplete + '%');
}
}, false);
// Download progress
xhr.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
}
}, false);
return xhr;
},
beforeSend: function (xhr) {
qyuraLoader.startLoader();
},
success: function (response, textStatus, jqXHR) {
qyuraLoader.stopLoader();
try {
$("#load_consulting").hide();
var data = $.parseJSON(response);
if (data.status == 0)
{
if (data.isAlive)
{
$('#addLoad .progress-bar').css('width', '00%');
console.log(data.errors);
$.each(data.errors, function (index, value) {
if (typeof data.custom == 'undefined') {
$('#err_' + index).html(value);
}
else
{
$('#err_' + index).addClass('error');
if (index == 'TopError')
{
$('#er_' + index).html(value);
}
else {
$('#er_TopError').append('<p>' + value + '</p>');
}
}
});
if (data.errors.TopError) {
$('#er_TopError').show();
$('#er_TopError').html(data.errors.TopError);
setTimeout(function () {
$('#er_TopError').hide(5000);
$('#er_TopError').html('');
}, 5000);
}
}
else
{
$('#headLogin').html(data.loginMod);
}
} else {
//document.getElementById("setData").reset();
$('#myModal').modal('hide');
$('#successTop').show();
$('#successTop').html(data.msg);
if (data.msg != '' && data.msg != "undefined") {
bootbox.alert({closeButton: false, message: data.msg, callback: function () {
if (data.url) {
window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
} else {
location.reload(true);
}
}});
} else {
bootbox.alert({closeButton: false, message: "Success", callback: function () {
if (data.url) {
window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
} else {
location.reload(true);
}
}});
}
}
}
catch (e) {
if (e) {
$('#er_TopError').show();
$('#er_TopError').html(e);
setTimeout(function () {
$('#er_TopError').hide(5000);
$('#er_TopError').html('');
}, 5000);
}
}
}
});
回答by Uchiha Itachi
I am using this simple one line code for years without a problem (it requires jQuery):
我多年来一直在使用这个简单的一行代码而没有问题(它需要 jQuery):
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
function ap(x,y) {$("#" + y).load(x);};
function af(x,y) {$("#" + x ).ajaxSubmit({target: '#' + y});return false;};
</script>
Here ap() means an Ajax page and af() means an Ajax form. In a form, simply calling af() function will post the form to the URL and load the response on the desired HTML element.
这里 ap() 表示 Ajax 页面,而 af() 表示 Ajax 表单。在表单中,只需调用 af() 函数即可将表单发布到 URL 并在所需的 HTML 元素上加载响应。
<form id="form_id">
...
<input type="button" onclick="af('form_id','load_response_id')"/>
</form>
<div id="load_response_id">this is where response will be loaded</div>