使用 jQuery 和 PHP 序列化和提交表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15173965/
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
Serializing and submitting a form with jQuery and PHP
提问by Dan Dinu
I'm trying to send a form's data using jQuery. However, data does not reach the server. Can you please tell me what I'm doing wrong?
我正在尝试使用 jQuery 发送表单数据。但是,数据不会到达服务器。你能告诉我我做错了什么吗?
My HTML form:
我的 HTML 表单:
<form id="contactForm" name="contactForm" method="post">
<input type="text" name="nume" size="40" placeholder="Nume">
<input type="text" name="telefon" size="40" placeholder="Telefon">
<input type="text" name="email" size="40" placeholder="Email">
<textarea name="comentarii" cols="36" rows="5" placeholder="Message"></textarea>
<input id="submitBtn" type="submit" name="submit" value="Trimite">
</form>
JavaScript (in the same file as the above form):
JavaScript(与上述表单在同一个文件中):
<script type="text/javascript">
$(document).ready(function(e) {
$("#contactForm").submit(function() {
$.post("getcontact.php", $("#contactForm").serialize())
// Serialization looks good: name=textInNameInput&&telefon=textInPhoneInput etc
.done(function(data) {
if (data.trim().length > 0) {
$("#sent").text("Error");
} else {
$("#sent").text("Success");
}
});
return false;
})
});
</script>
Server side PHP (/getcontact.php):
服务器端 PHP ( /getcontact.php):
$nume = $_REQUEST["nume"]; // $nume contains no data. Also tried $_POST
$email = $_REQUEST["email"];
$telefon = $_REQUEST["telefon"];
$comentarii = $_REQUEST["comentarii"];
Can you please tell me what I am doing wrong?
你能告诉我我做错了什么吗?
UPDATE
更新
Checked var_dump($_POST)and it returned an empty array.
检查var_dump($_POST)并返回一个空数组。
The weird thing is that the same code tested on my local machine works fine. If I upload the files on my hosting space it stops working. I tried doing an old-fashioned form without using jQuery and all data was correct.
奇怪的是,在我的本地机器上测试的相同代码工作正常。如果我将文件上传到我的托管空间,它就会停止工作。我尝试在不使用 jQuery 的情况下做一个老式的表单,所有数据都是正确的。
I don't see how this would be a server configuration problem. Any ideas?
我不明白这会是一个服务器配置问题。有任何想法吗?
Thank you!
谢谢!
回答by zamil
You can use this function
你可以使用这个功能
var datastring = $("#contactForm").serialize();
$.ajax({
type: "POST",
url: "your url.php",
data: datastring,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handling here');
}
});
return type is json
返回类型是 json
EDIT: I use event.preventDefaultto prevent the browser getting submitted in such scenarios.
编辑:我event.preventDefault用来防止浏览器在这种情况下被提交。
Adding more data to the answer.
为答案添加更多数据。
dataType: "jsonp"if it is a cross-domain call.
dataType: "jsonp"如果是跨域调用。
beforeSend:// this is a pre-request call back function
beforeSend:// 这是一个预请求回调函数
complete:// a function to be called after the request ends.so code that has to be executed regardless of success or error can go here
complete:// 请求结束后要调用的函数。所以不管成功还是错误都必须执行的代码可以放在这里
async:// by default, all requests are sent asynchronously
async:// 默认情况下,所有请求都是异步发送的
cache:// by default true. If set to false, it will force requested pages not to be cached by the browser.
cache:// 默认为真。如果设置为 false,它将强制请求的页面不被浏览器缓存。
Find the official page here
在这里找到官方页面
回答by MrBii
You can add extra data with form data
您可以使用表单数据添加额外的数据
use serializeArray and add the additional data:
使用 serializeArray 并添加附加数据:
var data = $('#myForm').serializeArray();
data.push({name: 'tienn2t', value: 'love'});
$.ajax({
type: "POST",
url: "your url.php",
data: data,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
回答by Aniket
<script type="text/javascript">
$(document).ready(
function() {
populateUser();
$("#user").submit(
function(e) {
e.preventDefault();
jQuery.ajaxSetup({
async : false
});
if ($("#roleId").val() != 'Select role') {
$.post($(this).attr("action"), $(this)
.serialize(), function(response) {
alert(response.message);
$("#user")[0].reset();
populateUser();
jQuery.ajaxSetup({
async : true
});
});
} else {
alert("Please Select the role of user");
}
})
});
回答by Jan.J
Have you checked in console if data from form is properly serialized? Is ajax request successful? Also you didn't close placeholder quote in, which can cause some problems:
如果表单中的数据正确序列化,您是否在控制台中检查过?ajax请求成功了吗?您也没有关闭占位符引用,这可能会导致一些问题:
<textarea name="comentarii" cols="36" rows="5" placeholder="Message>
回答by A. M. Mérida
Have you looked in firebug if POST or GET?.
如果 POST 或 GET,您是否查看过萤火虫?
check the console display.
检查控制台显示。
Put in the test script:
放入测试脚本:
console.log(data);
You can see the response from the server, if it shows something.
如果显示某些内容,您可以看到来自服务器的响应。
回答by dxb_dev
The problem can be PHP configuration:
问题可能是PHP配置:
Please check the setting max_input_varsin the php.ini file.
请检查php.ini 文件中的max_input_vars设置。
Try to increase the value of this setting to 5000 as example.
例如,尝试将此设置的值增加到 5000。
max_input_vars = 5000
Then restart your web-server and try.
然后重新启动您的网络服务器并尝试。
回答by Thor Aryliah
See the answer from this previous post. Than you can use .post() or .get() to send serialized data to server.
请参阅上一篇文章的答案。您可以使用 .post() 或 .get() 将序列化数据发送到服务器。
Convert form data to JavaScript object with jQuery
使用 jQuery 将表单数据转换为 JavaScript 对象
Anyway, it is very confusing your situation caused by this lack of details.
无论如何,由于缺乏细节而导致您的情况非常混乱。
If you're using a web server (non-local) this code can be wrong if you forget to setup the actual jquery link. I don't know even if you refer jquery on absolute path or relative path!?
如果您使用的是网络服务器(非本地),如果您忘记设置实际的 jquery 链接,则此代码可能是错误的。即使你在绝对路径或相对路径上引用jquery,我也不知道!?
回答by rahulbhondave
$("#contactForm").submit(function() {
$.post(url, $.param($(this).serializeArray()), function(data) {
});
});
回答by Zigri2612
Two End Registration or Users Automatically Registered to "Shouttoday" by ajax when they Complete Registration by form submission.
两个结束注册或用户在通过表单提交完成注册时通过ajax自动注册到“Shouttoday”。
var deffered = $.ajax({
url:"code.shouttoday.com/ajax_registration",
type:"POST",
data: $('form').serialize()
});
$(function(){
var form;
$('form').submit( function(event) {
var formId = $(this).attr("id");
form = this;
event.preventDefault();
deffered.done(function(response){
alert($('form').serializeArray());alert(response);
alert("success");
alert('Submitting');
form.submit();
})
.error(function(){
alert(JSON.stringify($('form').serializeArray()).toString());
alert("error");
form.submit();
});
});
});

