[英]$_POST is not working in ajax form submit?
当我尝试通过ajax表单提交检查用户输入名称时已经存在!但是它只能在sessions.php
获取Undefined index: username
,缺少什么?
<form action="" method="POST" id="saveuser" enctype="multipart/form-data">
<input type="text" name="username"><br>
<input type="password" name="pass"><br>
<input type="file" name="fileupload"><br>
<input type="submit" name="submit" value="Confirm" id="confirm">
</form>
<script type="text/javascript">
$('#confirm').click(function(e){
e.preventDefault();
$.ajax({
type:'POST',
url :"sessions.php",
data:$("#saveuser").serialize(),
contentType : false,
processData: false,
success: function(d){
console.log(d);//[error] :Undefined index: username
}
});
});
</script>
sessions.php
<?php
$exist = "david";
if($_POST['username'] == $exist){
echo json_encode("Already exist");
}
else{
echo json_encode("You can succesfully add");
}
?>
如果将contentType设置为false ,则不发送ajax标头,如果发送somehing type:POST
,则结果type:POST
标头不包含您的数据,因此服务器无法看到它。 如果您使用GET
来执行此操作,它将起作用,因为数据是使用GET
(在url之后)而不是在标头中发送的。
只需删除contentType即可
$.ajax({
type:'POST',
url :"sessions.php",
data: $("#saveuser").serialize(),
success: function(d){
console.log(d);
}
});
内容类型
(默认:'application / x-www-form-urlencoded; charset = UTF-8')
类型:布尔值或字符串将数据发送到服务器时,请使用此内容类型。 默认为“application / x-www-form-urlencoded; charset = UTF-8”,这在大多数情况下都适用。 如果您明确地将内容类型传递给$ .ajax(),那么它总是被发送到服务器(即使没有数据发送)。 从jQuery 1.6开始,你可以传递false来告诉jQuery不要设置任何内容类型标题。 注意:W3C XMLHttpRequest规范规定字符集始终为UTF-8; 指定另一个字符集不会强制浏览器更改编码。 注意:对于跨域请求,将内容类型设置为application / x-www-form-urlencoded,multipart / form-data或text / plain以外的任何内容将触发浏览器向服务器发送预检OPTIONS请求。
processData用于按原样发送数据 - Ajax文档
将数据发送到服务器
默认情况下,使用GET HTTP方法发送Ajax请求。 如果需要POST方法,可以通过为type选项设置值来指定方法。 此选项会影响数据选项的内容如何发送到服务器。 根据W3C XMLHTTPRequest标准,POST数据将始终使用UTF-8字符集传输到服务器。
data选项可以包含形式为key1 = value1&key2 = value2的查询字符串,或者包含{key1:'value1',key2:'value2'}形式的对象。 如果使用后一种形式,则在发送之前使用jQuery.param()将数据转换为查询字符串。 通过将processData设置为false可以避免此处理。 如果您希望将XML对象发送到服务器,则可能不希望进行处理; 在这种情况下,将contentType选项从application / x-www-form-urlencoded更改为更合适的MIME类型。
您的代码几乎没有问题,例如:
...它只在sessions.php中获得Undefined index:username
问题是由于以下两行,
contentType : false, processData: false,
从文档中 ,
contentType (默认值:
'application/x-www-form-urlencoded; charset=UTF-8'
)
类型:Boolean
或String
将数据发送到服务器时,请使用此内容类型。 默认为“application / x-www-form-urlencoded; charset = UTF-8”,这在大多数情况下都适用。 如果您明确地将内容类型传递给$.ajax()
,那么它总是被发送到服务器(即使没有数据发送)。 从jQuery 1.6开始,你可以传递false
来告诉jQuery不要设置任何内容类型标题。
和
processData (默认值:
true
)
类型:Boolean
默认情况下,作为对象传入数据选项的数据(技术上,不是字符串)将被处理并转换为查询字符串,适合默认内容类型“application / x-www-form-urlencoded” 。 如果要发送DOMDocument或其他未处理的数据,请将此选项设置为false
。
因此, $_POST
如果你设置阵列将是sessions.php页空contentType
和processData
,以false
,这就是为什么你得到这个不确定的指标:用户名错误。 但话说回来,既然你发送了一个包含AJAX请求的文件,可以将这些设置设置为false
,这将在下面的内容中进一步说明。
.serialize()
方法通过序列化表单控件值(例如<input>
, <textarea>
和<select>
.serialize()
创建URL编码的文本字符串。 但是,在序列化表单时它不包含文件输入字段,因此远程AJAX处理程序根本不会接收文件。 因此,如果您通过AJAX上传文件,请使用FormData对象。 但请记住,旧浏览器不支持FormData对象。 FormData支持从以下桌面浏览器版本开始:IE 10 +,Firefox 4.0 +,Chrome 7 +,Safari 5 +,Opera 12+。
由于您期望从服务器获取json对象,因此将此设置dataType:'json'
到您的AJAX请求中。 dataType
是您期望从服务器返回的数据类型。
所以解决方案是这样的:
保持HTML表单不变,并按以下方式更改jQuery / AJAX脚本,
$('#confirm').click(function(e){
e.preventDefault();
var formData = new FormData($('form')[0]);
$.ajax({
type: 'POST',
url : 'sessions.php',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function(d){
console.log(d.message);
}
});
});
在sessions.php页面上,处理您的表单,如下所示:
<?php
$exist = "david";
if(isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['pass']) && !empty($_POST['pass'])){
if($_POST['username'] == $exist){
echo json_encode(array("message" => "Already exist"));
}else{
echo json_encode(array("message" => "You can succesfully add"));
// get username and password
$username = $_POST['username'];
$password = $_POST['pass'];
// process file input
// Check whether user has uploaded any file or not
if(is_uploaded_file($_FILES['fileupload']['tmp_name'])){
// user has uploaded a file
}else{
// no file has been uploaded
}
}
}else{
echo json_encode(array("message" => "Invalid form inputs"));
}
?>
您将contentType设置为false,这就是PHP无法解析您的帖子正文的原因
使用$ .post()表示ajax:
$('#confirm').click(function(e){
e.preventDefault();
$.post("sessions.php", $.param($("#saveuser").serializeArray()), function(data) { // use this ajax code
console.log(data);
});
});
在html代码中使用以下代码并删除contentType:false,processData:false
<form action="" method="POST" id="saveuser" enctype="multipart/form-data">
<input type="text" name="username"><br>
<input type="password" name="pass"><br>
<input type="file" name="fileupload"><br>
<input type="submit" name="submit" value="Confirm" id="confirm">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>
<script type="text/javascript">
$('#confirm').click(function(e){
e.preventDefault();
$.ajax({
type:'POST',
url :"sessions.php",
data: $('#saveuser').serialize(),
success: function(d){
console.log(d);//[error] :Undefined index: username
}
});
});
</script>
考虑到这是您的HTML表单
<form method="POST" id="saveuser" enctype="multipart/form-data"> <input type="text" name="username" id="username"><br> <input type="password" name="pass" id="pass"><br> <input type="file" name="fileupload"><br> <input type="submit" name="submit" value="Confirm" id="confirm"> </form>
你可以像这样调用jQuery函数
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script> jQuery("#saveuser").submit(function () { //Validate the input here jQuery.ajax({ type: 'POST', url: 'sessions.php', data: jQuery('#saveuser').serialize(), success: function (msg) { msg = jQuery.trim(msg); if (msg == 'Success') { //Do Whatever //jQuery("#thanks_message").show('slow'); } } }); return false; });
您将获得session.php文件中的所有参数
<?php
$username = trim($_POST['username']);
$pass = trim($_POST['pass']);
//rest of the params of the form
$exist = "david";
if ($username == $exist) {
echo json_encode("Already exist");
} else {
echo json_encode("You can succesfully add");
}
?>
我希望这可以解决你的问题。
<form method="POST" id="saveuser" enctype="multipart/form-data">
<input type="text" name="username"/><br>
<input type="password" name="pass"/><br>
<input type="file" name="fileupload"/><br>
<input type="button" name="save" id="save" value="save"/>
</form>
<script type="text/javascript">
$('#save').click(function(e){
var form = new FormData(document.getElementById('#saveuser'));
$.ajax({
url :"sessions.php",
type : 'POST',
dataType : 'text',
data : form,
processData : false,
contentType : false,
success: function(d){
console.log(d);//[error] :Undefined index: username
}
});
});
</script>
您需要更改脚本:
尝试使用new FormData
而不是.serialize()
。
<script type="text/javascript">
$('#confirm').click(function(e){
e.preventDefault();
var formData = new FormData($("#saveuser")[0]);
$.ajax({
type:'POST',
url :"tt.php",
data:formData,
contentType : false,
processData: false,
success: function(d){
console.log(d);//[error] :Undefined index: username
}
});
});
</script>
注意:您使用的contentType
为false
表示jQuery不添加Content-Type标头。 您正在使用jQuery的.serialize()方法,该方法使用标准URL编码表示法创建文本字符串。 使用“contentType:false”时,需要传递未编码的数据。
将脚本更改为
<script type="text/javascript">
$(function(){
$('#confirm').click(function(e){
e.preventDefault();
$.ajax({
type:'POST',
url :"sessions.php",
data:$("#saveuser").serialize(),
contentType : false,
processData: false,
success: function(d){
console.log(d);//[error] :Undefined index: username
}
});
});
});
</script>
您的编码是正确的。从Ajax移除processData和contentType它将起作用
processData : false,
contentType : false,
从表单标记中删除该方法,操作:post和blank,因为您只需要在ajax方法中提供所有详细信息。
或者你可以删除表单标签本身,因为ajax方法将负责邮件调用。
这将有希望解决
<form id="saveuser" enctype="multipart/form-data">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.