javascript - $_POST is not working in ajax form submit?
Get the solution ↓↓↓Solution:
If you set contentType to false, ajax header is not send, in result if you send somehingtype:POST
header doesn't contain your data, so server can't see it. If you useGET
to do it, it will work, because data is sended withGET
(after url) not in header.
Just remove contentType
$.ajax({
type:'POST',
url :"sessions.php",
data: $("#saveuser").serialize(),
success: function(d){
console.log(d);
}
});
contentType
(default: 'application/x-www-form-urlencoded; charset=UTF-8')
Type: Boolean or String When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header. Note: The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. Note: For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server.
processData is used to send data as it is - Ajax documentation
Sending Data to the Server
By default, Ajax requests are sent using the GET HTTP method. If the POST method is required, the method can be specified by setting a value for the type option. This option affects how the contents of the data option are sent to the server. POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard.
The data option can contain either a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}. If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent. This processing can be circumvented by setting processData to false. The processing might be undesirable if you wish to send an XML object to the server; in this case, change the contentType option from application/x-www-form-urlencoded to a more appropriate MIME type.
Answer
Solution:
There are few issues with your code, such as:
... it only get Undefined index: username in sessions.php
The problem is because of the following two lines,
contentType : false, processData: false,
From the documentation,
contentType (default:
'application/x-www-form-urlencoded; charset=UTF-8'
)
Type:Boolean
orString
When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to$.ajax()
, then it is always sent to the server (even if no data is sent). As of jQuery 1.6 you can passfalse
to tell jQuery to not set any content type header.and
processData (default:
true
)
Type:Boolean
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option tofalse
.Hence,
$_POST
array would be empty in sessions.php page if you setcontentType
andprocessData
tofalse
, and that's why you're getting this undefined index: username error. But having said that, since you're sending a file with your AJAX request, it's okay to set these settings asfalse
, which is further explained in the following point.method creates a URL encoded text string by serializing form control values, such as
<input>
,<textarea>
and<select>
. However, it doesn't include file input field while serializing the form, and hence your remote AJAX handler won't receive the file at all. So if you're uploading file through AJAX, use FormData object. But keep in mind that old browsers don't support FormData object. FormData support starts from the following desktop browsers versions: IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+.Since you're expecting a json object from server, add this setting
dataType:'json'
to your AJAX request.dataType
is the type of data you're expecting back from the server.
So the solution would be like this:
Keep your HTML form as it is, and change your jQuery/AJAX script in the following way,
$('#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);
}
});
});
And on sessions.php page, process your form like this:
<?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"));
}
?>
Answer
Solution:
You are setting contentType to false, that is why PHP can not parse your post body
Answer
Solution:
Use $.post() for ajax :
$('#confirm').click(function(e){
e.preventDefault();
$.post("sessions.php", $.param($("#saveuser").serializeArray()), function(data) { // use this ajax code
console.log(data);
});
});
Answer
Solution:
Use the following code in your html code and remove 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>
Answer
Solution:
Considering this is your HTML form
<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>
Answer
Solution:
<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>
Answer
Solution:
You need to change your script:
Try usingnew FormData
instead of.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>
Note : You are usedcontentType
tofalse
that mean jQuery not to add a Content-Type header. You are using jQuery's .serialize() method which creates a text string in standard URL-encoded notation. You need to pass un-encoded data when using "contentType: false".
Answer
Solution:
Change your script to
<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>
Answer
Solution:
Your coding is correct.Remove processData and contentType from Ajax it will work
processData : false,
contentType : false,
Answer
Solution:
Remove that method,action: post and blank from your form tag as you need to give all details in ajax method only.
or you can delete the form tag itself as ajax method will take care of the post call.
this will solve hopefully
<form id="saveuser" enctype="multipart/form-data">
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: warning: undefined array key
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
About the technologies asked in this question
PHP
PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
JavaScript
JavaScript is a multi-paradigm language that supports event-driven, functional, and mandatory (including object-oriented and prototype-based) programming types. Originally JavaScript was only used on the client side. JavaScript is now still used as a server-side programming language. To summarize, we can say that JavaScript is the language of the Internet.
https://www.javascript.com/
JQuery
JQuery is arguably the most popular JavaScript library with so many features for modern development. JQuery is a fast and concise JavaScript library created by John Resig in 2006. It is a cross-platform JavaScript library designed to simplify client-side HTML scripting. Over 19 million websites are currently using jQuery! Companies like WordPress, Facebook, Google, IBM and many more rely on jQuery to provide a kind of web browsing experience.
https://jquery.com/
HTML
HTML (English "hyper text markup language" - hypertext markup language) is a special markup language that is used to create sites on the Internet.
Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone.
https://www.w3.org/html/
Welcome to programmierfrage.com
programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.
Get answers to specific questions
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Help Others Solve Their Issues
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.