$_POST is not working in ajax form submit? - javascript

When I try to check user input name is already exist by ajax form submit !But it only get Undefined index: username in sessions.php ,what is missing ?
<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");
}
?>

If you set contentType to false, ajax header is not send, in result if you send somehing type:POST header doesn't contain your data, so server can't see it. If you use GET to do it, it will work, because data is sended with GET (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.

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 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.
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 to false.
Hence, $_POST array would be empty in sessions.php page if you set contentType and processData to false, 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 as false, which is further explained in the following point.
.serialize() 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"));
}
?>

You are setting contentType to false, that is why PHP can not parse your post body

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);
});
});

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>

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>
You can call the jQuery function like this
<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;
});
You will get all the params in your session.php file like
<?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");
}
?>
I hope this resolves your problem.

<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>

You need to change your script:
Try using new 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 used contentType to false 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".

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>

Your coding is correct.Remove processData and contentType from Ajax it will work
processData : false,
contentType : false,

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">

Related

jQuery ajax not passing post data to php page

I try to get post data from using alert() and its worked problem is that data is not passing to php page result is always {"success":false,"result":0}
What I want is send password to php page and hash it using password_hash() and return result
$('#spass').on('submit',function(){
var that=$(this),
contents=that.serialize();
alert(contents);
$.ajax({
url:'passwordhashing.php',
dataType:'json',
data:contents,
success:function(data){
alert(JSON.stringify(data));
console.log(data);
}
});
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="spass" >
<h4>Change Your Password</h4>
<input type='password'name="passc" >
<!--<input type='password' name="cpass" id="cpass"> -->
<input type="submit">
</form>
**this my php code**
<?php
header('Content-type: text/javascript');
$json=array(
'success'=>false,
'result'=>0
);
if(isset($_POST['passc']) && !empty($_POST['passc'])) {
$pass=password_hash($_POST['passc'],PASSWORD_DEFAULT);
$json['success']=true;
$json['result']=$pass;
}
echo json_encode($json);
?>
You can test that your data has not actually been passed to a PHP page.
In the PHP code, do the following: echo $ _POST ['YOUR_VARIABLE'].
Check the INSPECT_ELEMENT / NETWORK browser to make sure you actually send data to the correct link. Your link may be relative, so you may be sending data to the wrong link.
So, try to put the entire link in the ajax url
$ .ajax ({
url: 'HTTP: //WHOLE_LINK_IN_HERE.COM/passwordhashing.php',
});
SET method in Ajax: type: "POST"
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
**i used $.post() instead of using $.ajax() and it fix my problem**
$('#spass').on('submit',function(){
var that=$(this),
contents=that.serialize();
alert(contents);
$.post({
url:'passwordhashing.php',
dataType:'json',
data:contents,
success:function(data){
alert(JSON.stringify(data));
console.log(data);
}
});
return false;
});

Why is this ajax code not working?

I'm trying to submit a form with ajax with the code below, but apparently doesn't seem to work.
Any suggestion to fix this problem?
$(".dialog-set-new-message").on('keyup', '.ctxtareados', function(b){
if(b.keyCode == 8){return false;}
if(b.keyCode == 13){
//
$("#submit_new_message_cbox").submit(function(eventmsg){
$(".loader-wait-gif-con").fadeIn(500);
eventmsg.preventDefault();
$.ajax({
url: "https://www.mypage.com/success/set_new_cbox_message.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs representing form fields and values
contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
success: function(data) // A function to be called if request succeeds
{
$(".dialog-new-chat-open-con").load("../success/refresh_new_cbox.php", function(){
$(".loader-wait-gif-con").fadeOut(500);
$(".con-sub-nav-chat h3").html("Messages updated.");
$(".con-sub-nav-chat").css("display", "block");
$(".con-sub-nav-chat").fadeOut(7000);
$(".all-msg-new-chat-box").animate({scrollTop: $("#sldum").offset().top}, 1000);
});
$('#submit_new_message_cbox')[0].reset();
}
});
});
//
}
});
--FIXED--
I Added a input[submit] in the php file and modified the code as follow:
PHP Code added:
<input style="visibility: hidden;" id="submitnmcbox" type="submit">
JS Code Modified (same as above):
$(".dialog-set-new-message").on('keyup', '.ctxtareados', function(b){
if(b.keyCode == 8){return false;}
if(b.keyCode == 13){
$("#submitnmcbox").click();
}
});
//Set new msg chat
$("#submit_new_message_cbox").on('submit', function(eventmsg){
$(".loader-wait-gif-con").fadeIn(500);
eventmsg.preventDefault();
$.ajax({
url: "https://www.dudoby.com/success/set_new_cbox_message.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs representing form fields and values
contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
success: function(data) // A function to be called if request succeeds
{
$(".dialog-new-chat-open-con").load("../success/refresh_new_cbox.php", function(){
$(".loader-wait-gif-con").fadeOut(500);
$(".con-sub-nav-chat h3").html("Se han actualizado los mensajes.");
$(".con-sub-nav-chat").css("display", "block");
$(".con-sub-nav-chat").fadeOut(7000);
$(".all-msg-new-chat-box").animate({scrollTop: $("#sldum").offset().top}, 1000);
});
$('#submit_new_message_cbox')[0].reset();
}
});
});
//
I think you are using FormData() constructor wrongly. According to MDN, FormData() constructor accept HTML DOM form element (optional). Example:
<form name="myForm">
<input type="text" name="text_field_1" value="test1" /><br /><br />
<input type="text" name="text_field_2" value="test2" /><br /><br />
<input type="text" name="text_field_3" value="test3" /><br />
</form>
<script type="text/javascript">
var myForm = document["myForm"];
var formData = new FormData(myForm);
console.log(formData.get("text_field_2")); // returns "test2"
</script>

Accessing type="file" input from POST method on server side

Having some difficulty understanding how to access type="file" input on the server side. Below is the code I'm using. I use AJAX because I want my web app to not require refreshing, and am using a slightly roundabout way of submitting my form so I can have a better UI.
My HTML:
<form id="updateProfileImageForm" enctype="multipart/form-data">
<div class="updateProfileImageContainer">
<img src="images/profile/generic.png" class="updateProfileImage">
<div class="updateProfileImageOverlay" onclick="changeImageToUpload()">
<div class="updateProfileImageOverlayText">Upload new image</div>
</div>
<input type="file" id="imageToUpload" name="image" style="display: none;" onChange="$(this).closest('form').trigger('submit');"></input>
</div>
</form>
My JS:
function changeImageToUpload() {
$('#imageToUpload').trigger('click');
}
$('#updateProfileImageForm').submit(function(e) {
e.preventDefault();
var form_data = new FormData(this);
$.ajax({
type: 'POST',
url: '/changeProfile',
data: form_data,
processData: false,
success: function(response) {
if(response.message != null) {
alert(response.message);
} else {
// Change profile image displayed
$('.updateProfileImage').attr("src", response.newProfileImage);
alert('Profile picture successfully updated! Refresh your browser to update your window!');
}
}
})
});
My Server PHP:
if (isset($_FILES['image'])) {
$image = $_FILES['image'];
}
Var_dump on $_FILES shows an empty array, while var_dump on $_POST shows a lot of information (which I'm assuming is my data file). However, accessing the 'image' property on either $_POST or $_FILES (through either $_POST['image'] or $_FILES['image']) gives me either "undefined index" or "undefined variable".
Would you guys be so kind as to educate me on:
What's the difference between $_POST and $_FILES?
How should I be accessing the file in this case?
Thanks!
You're missing a necessary config option in your ajax request, you need to set contentType to false
$.ajax({
type: 'POST',
url: '/changeProfile',
data: form_data,
processData: false,
contentType: false,
success: function(response) {
if(response.message != null) {
alert(response.message);
} else {
// Change profile image displayed
$('.updateProfileImage').attr("src", response.newProfileImage);
alert('Profile picture successfully updated! Refresh your browser to update your window!');
}
}
})
jQuery.ajax sets the content type by default to application/x-www-form-urlencoded which is incorrect for your FormData object, if you set it to false it will be set correctly by the underlying XMLHTTTPRequest object.
Idea behind it.
Instead of using file as post to PHP, simply convert image to base64 and receive that string using ajax in php.
Refer to this URL

Ajax POST format with PHP

I have a form, inside which I want to have a "virtual form", which handles file attachments. I have a File-input and a button to send the file.
The problem is that my PHP backed gets only POST and that with structure:
"file"; filename="xxx.jpg"
Content-type: image/jpeg
.
.
.
where the dots represent the binary data from the file.
From what I have read it should be $_FILES and $_POST variables but I don't get them.
Here are the relevant codelines in HTML and in Javascript:
<input type="file" id="file-to-append" name="file-attachment">
<input type="button" onClick="append_file()" value="Add file">
function append_file() {
var formData = new FormData();
console.log(jQuery('#file-to-append'));
formData.append('file', jQuery(":file")[0].files[0]);
jQuery.ajax({
url : 'file_upload.php',
type : 'POST',
data : formData,
processData: false,
success : function(data) {
console.log(data);
alert("Added");
}
});
}
Could somebody spot or know where the problem lies?
The data is passing properly so there is no problem with your Ajax call.
You get the file object in PHP using the super global $_FILES.
In your case, you would use it like:
$file = $_FILES['file'];
echo $file['name'];
echo $file['tmp_name'];
.
.
.
To take a look at the $_FILES array you could:
echo "<pre>";
print_r($_FILES);
echo "</pre>";
Things are getting stranger and stranger. I got it working, but only on IE 11 by setting contentType: 'multipart/form-data' With Chrome it doesn't work at all with that setting.
I have tried with contentType: false, but it doesn't work on either platform though it should be the right thing(TM) to do :/.
I have also added enctype-setting in the outer form, but I wonder how it could help, because I am not submitting (whole form) but only adding things "inside" the main form (that I handle myself). Apparently it didn't help either.
This shouldn't be a problem but for some reason I am stuck with this ajax implementation, though I have used file upload since long time ago (two figure number)...
hank
Use right encrypte in your form
<form id="data" enctype="multipart/form-data" method="post" >
<input type="submit" value="Add file">
</form>
use ajax submit
$("form#data").submit(function()
{var formData = new FormData($(this)[0]);
$.ajax({
url: "filename.php",
type: 'POST',
data: formData,
async: false,
success: function (data)
{
var jsonData = $.parseJSON(data);
var errFlag =jsonData.errorFlag;
var errMsg =jsonData.errorMessage;
if(errFlag == 1)
{
//successmessage;
}
else
{
//errormessage;
}
},
cache: false,
contentType: false,
processData: false
});
return false;
});

AJAX to PHP without page refresh

I'm having some trouble getting my form to submit data to my PHP file.
Without the AJAX script that I have, the form takes the user through to 'xxx.php' and submits the data on the database, however when I include this script, it prevents the page from refreshing, displays the success message, and fades in 'myDiv' but then no data appears in the database.
Any pointers in the right direction would be very much appreciated. Pulling my hair out over this one.
HTML
<form action='xxx.php' id='myForm' method='post'>
<p>Your content</p>
<input type='text' name='content' id='content'/>
<input type='submit' id='subbutton' name='subbutton' value='Submit' />
</form>
<div id='message'></div>
JavaScript
<script>
$(document).ready(function(){
$("#subbutton").click(function(e){
e.preventDefault();
var content = $("#content").attr('value');
$.ajax({
type: "POST",
url: "xxx.php",
data: "content="+content,
success: function(html){
$(".myDiv").fadeTo(500, 1);
},
beforeSend:function(){
$("#message").html("<span style='color:green ! important'>Sending request.</br></br>");
}
});
});
});
</script>
A couple of small changes should get you up and running. First, get the value of the input with .val():
var content = $("#content").val();
You mention that you're checking to see if the submit button isset() but you never send its value to the PHP function. To do that you also need to get its value:
var submit = $('#subbutton').val();
Then, in your AJAX function specify the data correctly:
$.ajax({
type: "POST",
url: "xxx.php",
data: {content:content, subbutton: submit}
...
quotes are not needed on the data attribute names.
On the PHP side you then check for the submit button like this -
if('submit' == $_POST['subbutton']) {
// remainder of your code here
Content will be available in $_POST['content'].
Change the data atribute to
data:{
content:$("#content").val()
}
Also add the atribute error to the ajax with
error:function(e){
console.log(e);
}
And try returning a var dump to $_POST in your php file.
And the most important add to the ajax the dataType atribute according to what You send :
dataType: "text" //text if You try with the var dump o json , whatever.
Another solution would be like :
$.ajax({
type: "POST",
url: "xxxwebpage..ifyouknowhatimean",
data: $("#idForm").serialize(), // serializes the form's elements.
dataType:"text" or "json" // According to what you return in php
success: function(data)
{
console.log(data); // show response from the php script.
}
});
Set the data type like this in your Ajax request: data: { content: content }
I think it isnt a correct JSON format.

Categories

Resources