PHP Ajax response is empty using jQuery - javascript

At the moment I create a register "page". Here is the html code of the form
<form class="register_form" method="POST" action="insert.php">
<label class="label_register">Benutzername*:</label>
<div class="input_group">
<input class="input_register" id="register_username" name="username" type="text"/><span class="register_span">-</span>
</div>
<label class="label_register">Passwort*:</label>
<div class="input_group">
<input class="input_register" id="register_password_1" name="password" type="password"/><span class="register_span">-</span>
</div>
<label class="label_register">Passwort wdh.*:</label>
<div class="input_group">
<input class="input_register" id="register_password_2" name="password2" type="password"/><span class="register_span">-</span>
</div>
<label class="label_register">E-Mail Adresse*:</label>
<div class="input_group">
<input class="input_register" id="register_email" name="email" type="text"/><span class="register_span">-</span>
</div>
<button class="button button_register">Jetzt kostenlos registrieren</button>
<p class="register_hint">
* Pflichtfeld
</p>
</form>
Here is my jquery code
var username_bool = true;
var password_bool = true;
var email_bool = true;
$('.register_form').on('submit', function(){
if(username_bool == true && password_bool == true && email_bool == true){
$.ajax({
type: "POST",
url: "insert.php",
data: $(this).serialize(),
success: function(response){
console.log(response);
alert(response);
},
});
}
else{
alert("---");
}
return false;
});
And here is the php code
<?php
if(isset($_POST["username"]) && isset($_POST["password_1"]) && isset($_POST["email"])){
echo "response";
}
?>
Now I have sent the form, but the respone is empty. I use Firebug to debugg. What is my mistake? And I made also other mistakes?
Thanks for you help.

You seem to be checking for a field named password_1
isset($_POST["password_1"])
while it's named password
<input class="input_register" id="register_password_1" name="password" type="password"/><span class="register_span">-</span>
You'll have to make sure the name attribute matches the value you're checking

The problem i see is you check on isset($_POST["password_1"]) and that is not in the form as you named your password field "password"
<input class="input_register" id="register_password_1" name="password" type="password"/><span class="register_span">-</span>
you need to check using isset($_POST["password"])

Related

Multiple file upload using jquery serialization works only at the second call

I experience a strange problem:
Form ajax call with multiple files and form values works perfect, but only on the second call. First call ends up the the success: function(result) "else" condition. Second call works perfect and sends all data to the php. So I hit the submit button once and it shows up an empty error box and I hit the submit button again and everything works perfect.
How is that possible and how to solve that?
UPDATE #1: Found workaround, but not the solution. It works when I put if (result==="") { $(".form-application").submit(); } below the success function. But thats very dirty! ... and it upload all files twice! :-(
PROBLEM SOLVED David Knipe provided the solution!! Thank you so much!!
JQUERY:
$(".form-application").submit(function(e) {
e.preventDefault();
$("#btnSubmit2").text("Please wait...");
$("#btnSubmit2").attr("disabled", true);
var files = $('#files')[0].files;
var form = $(this);
var error='';
var formData = new FormData(this);
grecaptcha.ready(function() {
grecaptcha.execute('6Le4Qb0UAAAAAHUPcsmVYIk7zc4XCsiBnf6oE-fP', {action: 'create_comment'}).then(function(token) {
$('<input>').attr({
type: 'hidden',
value: token,
name: 'token'
}).appendTo('form');
for(var count = 0; count<files.length; count++)
{
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
error += "Invalid " + count + " Image File"
}
else
{
formData.append("files[]", document.getElementById('files').files[count]);
}
}
if(error == '')
{
$.ajax({
url: form.attr("action"),
method: form.attr("method"),
data: formData,
processData: false,
contentType: false,
success: function(result) {
if (result == "0") {
$("#btnSubmit2").text("Thank you!");
$("#btnSubmit2").attr("disabled", true);
$(".output_message").text("");
$(':input','.form-application')
.not(':button, :submit, :reset, :hidden')
.val('')
.prop('checked', false)
.prop('selected', false);
$(".output_message").append("<div class='alert alert-success alert-dismissible fade show' role='alert'>We have received your application!</div>");
} else {
$(".output_message").text("");
$(".output_message").append("<div class='alert alert-danger alert-dismissible fade show' role='alert'>"+result+"</div>");
$("#btnSubmit2").attr("disabled", false);
$("#btnSubmit2").text("try again");
}
}
});
}
else
{
alert(error);
}
});
});
return false;
});
HTML:
<form class="form-application" id="applicationform" method="post" action="https://<?PHP echo $_SERVER['HTTP_HOST']; ?>/include/process-application.php" enctype="multipart/form-data">
<input type="hidden" name="crsf" value="<?=$_SESSION['crsf']?>"/>
<input type="hidden" name="crsf-expire" value="<?=$_SESSION['crsf-expire']?>"/>
<div class="space40"></div>
<h6>Name</h6>
<input name="name" type="text" class="form-control" placeholder="Your Name">
<div class="space30"></div>
<h6>Email</h6>
<input name="email" type="text" class="form-control" placeholder="Your Email Address">
<div class="space30"></div>
<h6>Instagram Name</h6>
<input name="instagram" type="text" class="form-control" placeholder="Your Instagram Name">
<div class="space30"></div>
<h6>City & Country</h6>
<input name="from" type="text" class="form-control" placeholder="Where do you live?">
<div class="space30"></div>
<h6>Tell us more about you</h6>
<textarea name="message" class="form-control" rows="3" placeholder="Write some details about you, so we know you better."></textarea>
<div class="space30"></div>
<h6>Upload some photos of yourself</h6>
<div class="file-field">
<div class="btn btn-aqua">
<input name="files" id="files" type="file" accepts="image/*" multiple>
</div>
<div class="file-path-wrapper">
</div>
<div class="space20"></div>
</div>
</div>
<div class="col-12 text-center">
<button id="btnSubmit2" type="submit" class="btn btn-full-rounded btn-aqua">Submit Application</button>
<div class="space10"></div>
<span class="output_message"></span>
</div>
</form>
PHP Script /include/process-application.php
<?PHP
echo "0";
?>
OK, I think I've figured this out. $('<input>').attr(...); sets the token attribute on a new <input> element. But this is after var formData = new FormData(this);, so the token doesn't get included in formData. Then I guess you get an authentication error, and I guess it does the authentication before it even gets to the PHP part. It would just be a HTTP401 response with no body, hence "". But then, on the second attempt, the <input> has already been created with the correct token, and this ends up being used to authenticate.
Either keep onsubmit or action. Remove action from form tag, it will work

Jquery Not Sending the Form to HTTP

I'm having some problems with Jquery/Ajax.
This is my code for the form :
<form class="form-auth-small" method="POST" id="form" enctype="multipart/form-data">
<div class="form-group">
<label for="signin-email" class="control-label sr-only">Email</label>
<input type="email" class="form-control" name="email" value="samuel.gold#domain.com" placeholder="Email">
</div>
<div class="form-group">
<label for="signin-email" class="control-label sr-only">Name</label>
<input type="text" class="form-control" name="name" value="John">
</div>
<div class="form-group">
<label for="signin-email" class="control-label sr-only">Phone</label>
<input type="text" class="form-control" name="phone" placeholder="938434928">
</div>
<div class="form-group">
<label for="signin-email" class="control-label sr-only"></label>
<input type="password" class="form-control" name="password" placeholder="****">
</div>
<div class="form-group">
<input name="image" type="file" />
</div>
<button type="submit" id="submit" class="btn btn-primary btn-lg btn-block">Register</button>
</form>
And this is my code to AJAX/Jquery:
<script>
$(".submit").on("click", function(e) {
var form = $("#form");
// you can't pass Jquery form it has to be javascript form object var formData = new FormData(form[0]);
console.log(formData);
$.ajax({
type: "POST",
url: '/user/signup/',
data: formData,
contentType: false, //this is requireded please see answers above processData: false, //this is requireded please see answers above //cache: false, //not sure but works for me without this error: function (err) { console.log(err);
success: function(res) {
console.log(res);
},
});
});
</script>
When i do console.log to check that from form i don't receive any value, and when i check in network i dont see any HTTP callback.
Your code doesn't work because you were using the class selector token . (dot) instead of the id selector token # hashtag. Further details can be found on the documentation
Change this instruction
$(".submit").on("click", function(e) // …
to
$("#submit").on("click", function(e) // …
You dont have submit class. You have id="submit"
$("#submit").on("click", function(e) {
Use this and it should work.
Also change type="submit" to type="button" or in your js code you need to add
e.preventDefault();

php javascript form serialize get data undefined index

I want to call input value from javascript
My home page code :
<form method="post" id="form">
<div class="row">
<div class="col-md-6">
<label for="f_name">First Name</label>
<input type="text" class="form-control" name="f_name "id="f_name" value="">
</div>
<div class="col-md-6">
<label for="l_name">Last Name</label>
<input type="text" class="form-control" name="l_name" id="l_name" value="">
</div>
</div>
....
javascript code :
$("#singup_btn").click(function(event){
event.preventDefault();
$.ajax({
url : "register.php",
method : "POST",
data : $("form").serialize(),
success : function(data){
alert(data);
}
})
})
...calling page code :
<?php
include "db.php";
$fname = $_POST["f_name"];
$lname = $_POST["l_name"];
...
echo $fname;
...error while click button, only last name (input) value defined
<br />
<b>Notice</b>: Undefined index: f_name in <b>D:\xampp\htdocs\shop\register.php</b> on line <b>5</b><br />
<br />
<b>Notice</b>: Undefined index: email in <b>D:\xampp\htdocs\shop\register.php</b> on line <b>7</b><br />
<br />
<b>Notice</b>: Undefined index: password in <b>D:\xampp\htdocs\shop\register.php</b> on line <b>8</b><br />
please someone help me?
I stuck like more than 4 hours on this. Im learning javascript n php, n still newbie. Please help. thanks.
You are missing a # You also have an error in your first input field.
<input name="f_name ">
shouldbe
<input name="f_name">
$("#singup_btn").click(function(event){
event.preventDefault();
$.ajax({
url : "register.php",
method : "POST",
data : $("#form").serialize(),
success : function(data){
alert(data);
}
})
})
try this code
$(document).on('click', '#singup_btn', function() {
$.ajax({
url : "register.php",
type : "POST",
data : $("#form").serialize(),
success : function(data){
alert(data);
}
});
});
Please remove type="submit" from submit button and add type="button". It will work!
Serializing the form with a space in name="f_name "id="f_name" forces a + to be appended to the serialized value. This is why its not being picked up correctly server side.
Expected server side value
f_name=asd&l_name=asd
Actual server side value
f_name+=asd&l_name=asd
see test below
$("button").click(function()
{
//output values before serialization
console.log( "Result of f_name");
console.log ($("#f_name").val() );
console.log( "Result of l_name");
console.log ($("#l_name").val() );
//output values after serialization
var serialized = $("form").serialize();
console.log( "Result: Notice how f_name has an appended + in its key");
console.log( "'" + serialized + "'");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="form">
<div class="row">
<div class="col-md-6">
<label for="f_name">First Name</label>
<input type="text" class="form-control" name="f_name "id="f_name" value="">
</div>
<div class="col-md-6">
<label for="l_name">Last Name</label>
<input type="text" class="form-control" name="l_name" id="l_name" value="">
</div>
</div>
<button type="button"> test </button>
</form>
Credit to Chris

Ajax submit Form serialized data in php are null

I ve been searching all relative questions here and still cant figure out the problem I have.
I am using a simple modal form :
<p id="messages">Let's make today a great day!</p>
<form id="myloginform" name="myloginform" action="scripts/login.php" method="post" >
<div class="form-group">
<label for="username" class="">Enter username</label>
<input type="text" class="form-control input-lg c-square" id="username" name="username" placeholder="Username" required> </div>
<div class="form-group">
<label for="password" class="">Enter pass</label>
<input type="password" class="form-control input-lg c-square" id="password" name="password" placeholder="Password" required> </div>
<div class="form-group">
<div class="c-checkbox">
<input type="checkbox" id="login-rememberme" class="c-check">
<label for="login-rememberme" class="c-font-thin c-font-17">
<span></span>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn c-theme-btn btn-md c-btn-uppercase c-btn-bold c-btn-square c-btn-login" id="check">login</button>
</div>
</form>
I am using ajax to pass the form to a php file :
<script>
$(document).ready(function(){
$('form#myloginform').submit(function(e) {
var my_data = $('form#myloginform').serialize();
$.ajax({
type : 'POST',
url : 'scripts/login.php',
cache : false,
data : my_data,
contentType : false,
processData : false,
dataType: 'json',
success: function(response) {
//TARGET THE MESSAGES DIV IN THE MODAL
if(response.type == 'success') {
$('#messages').addClass('alert alert-success').text(response.message);
} else {
$('#messages').addClass('alert alert-danger').text(response.message);
}
}
});
e.preventDefault();
});
});
</script>
The login.php file is very simple and returns an json $output response
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "Test"){
$success = true;
}
if($success == true) {
$output = json_encode(array('type'=>'success', 'message' => $username));
} else {
$output = json_encode(array('type'=>'error', 'message' => $username));
}
die($output);
?>
The $output in every case returns null. I checked with firebug, and everything is OK , no errors, POST perfect still I cannot get the variables in php to work. Any ideas ??? Is something wrong with my approach or do I need to deserialize the data in the php file , somehow...???
Don't use die.
Use echo or print.
Also set contentType to true.

jQuery .submit() .ajax() have to click send button two times to get the correct response

I have a form with 5 fields that i am sending with AJAX to a PHP Script that does some simple validation and returns a string.
I have made a little jQuery script for the actual submission, and when i try to send the form i have to click the send button two times.
Update: Url to live site: http://www.dan-levi.no/new/#!/Kontakt
Here are some code:
HTML
<form id="contact_form" class="form-horizontal" action"includes/contact.php" method"post">
<div class="control-group">
<label class="control-label" for="contact_name">Ditt navn og evt. bedrift</label>
<div class="controls">
<input type="text" class="input-large" id="contact_name" name="contact_name" placeholder="Ditt navn og evt. bedrift" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="contact_email">E-post</label>
<div class="controls">
<input type="email" class="input-large" id="contact_email" name="contact_email" placeholder="E-post" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="contact_tel">Telefon</label>
<div class="controls">
<input type="tel" class="input-large" id="tel" name="contact_tel" placeholder="Telefon" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="contact_subject">Emne</label>
<div class="controls">
<input type="text" class="input-large" id="subject" name="contact_subject" placeholder="Emne for melding" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="contact_desc">Din beskjed</label>
<div class="controls">
<textarea rows="10" class="input-large" id="contact_desc" name="contact_desc" placeholder="Din beskjed"></textarea>
</div>
</div>
<div class="text-error pull-right" id="error_message"></div><br>
<input class="btn btn-large pull-right" type="submit" name="" value="Send" /><br>
</form>
javaScript
$(document).ready(function() {
$('#contact_form').submit(function(e) {
data = $('#contact_form').serialize();
$.ajax({
url: 'includes/contact.php',
type: 'POST',
data: data,
})
.done(function(response) {
if (response == 'empty') {
$('#error_message').text('Noen av feltene er tomme.')
} else {
$('.message').html(response);
$('#contact_form').fadeOut('400');
$('#info_line').fadeIn('400').text('Takk for din henvendelse');
};
})
e.preventDefault();
});
});
PHP
$contact_name = $_POST['contact_name'];
$contact_email = $_POST['contact_email'];
$contact_tel = $_POST['contact_tel'];
$contact_subject = $_POST['contact_subject'];
$contact_desc = $_POST['contact_desc'];
if ($contact_name == '' || $contact_email == '' || $contact_tel == '' || $contact_subject == '' || $contact_desc == '') {
echo "empty";
die();
}
echo $contact_name.'<br><br>';
echo $contact_email.'<br><br>';
echo $contact_tel.'<br><br>';
echo $contact_subject.'<br><br>';
echo $contact_desc.'<br><br>';
I cant find out why i have to click the button two times, i have tried some trial and error, read the forum for answers. I tried to serialize the form outsite the submit function, i just cant get this to behave the way i want. All help is greatly appreciated.
Oh, worth to mention. The actual response is that the fields are empty (php validation) the first time i click, but the second time it works as it should.
Make the ajax call using a regular input button instead of a submit button.
$("#button").click(function () { ... ajax ... }
I'm not sure if it makes a difference but have you tried putting what you want to happen afterwards in a success callback?
$(document).ready(function() {
$('#contact_form').submit(function(e) {
data = $('#contact_form').serialize();
$.ajax({
url: 'includes/contact.php',
type: 'POST',
data: data,
success: function(response) {
if (response == 'empty') {
$('#error_message').text('Noen av feltene er tomme.')
} else {
$('.message').html(response);
$('#contact_form').fadeOut('400');
$('#info_line').fadeIn('400').text('Takk for din henvendelse');
};
}
});
e.preventDefault();
});
});
I'm guessing it's because the default action (submit the form) is processing before your $.ajax request. Try making e.preventDefault() first in your submit callback.
$(document).ready(function() {
$('#contact_form').submit(function(e) {
e.preventDefault();
data = $('#contact_form').serialize();
$.ajax({
url: 'includes/contact.php',
type: 'POST',
data: data,
success: function(response) {
if (response == 'empty') {
$('#error_message').text('Noen av feltene er tomme.')
} else {
$('.message').html(response);
$('#contact_form').fadeOut('400');
$('#info_line').fadeIn('400').text('Takk for din henvendelse');
};
}
});
});
});

Categories

Resources