Access POST values sent by Ajax in PHP - javascript

I'm using Ajax to get POST values from a form. However, when I try to insert the form values in a database on submit, it doesn't get inserted. I still have no idea why it does not work.
Here is my HTML
<form method="post" action="" id="home-sign-up-form">
<input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input">
<input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input">
<input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input">
<input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
<input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
<input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input">
<br><font class="text-error" id="sign-up-error-text"></font><br>
<label><input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox"><font id="sign-up-remember-me-text">Remember me</font></label>
<input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>
My JS (the first console.log does go through and work):
if (validForm)
{
console.log("valid form");
console.log(JSON.stringify($('#home-sign-up-form')[0].seriaize()));
$.ajax(
{
type:'POST',
url:'form-submit.php',
data:$('#home-sign-up-form')[0].serialize(),
success:function(response)
{
$suForm.hide();
$tosppText.hide();
$mailSentIcon.show();
$emailSentText.show();
$emailSentTextEmail.text($suEmail);
$suBox.css("padding-left", "10px");
$suBox.css("padding-right", "10px");
}
});
}
And my PHP/MySQL:
<?php require 'dbconnect.php'; ?>
if (isset($_POST['suEmail']))
{
echo "<script type='text/javascript'>alert('got');</script>";
$suFirstName = mysqli_real_escape_string($_POST['suFirstName']);
$suLastName = mysqli_real_escape_string($_POST['suLastName']);
$suEmail = mysqli_real_escape_string($_POST['suEmail']);
$suPassword = mysqli_real_escape_string($_POST['suPassword']);
$suDisplayName = mysqli_real_escape_string($_POST['suDisplayName']);
$code = substr(md5(mt_rand()),0,15);
$query = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName,confirmCode,verified)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}','{$confirmCode},'{$verified}')");
}
The alert in the PHP code so I would assume that it isn't getting the 'signUp' POST variable. Thanks so much! Any help is appreciated! :D

$("#home-sign-up-form").submit(function(event) {
alert("Handler for .submit() called.");
event.preventDefault();
$.ajax({
type: 'POST',
url: 'form-submit.php',
data: $('#home-sign-up-form').serialize(),
success: function(response) {
console.log(response);
var data = JSON.parse(response);
$suForm.hide();
$tosppText.hide();
$mailSentIcon.show();
$emailSentText.show();
//$emailSentTextEmail.text($suEmail);
$emailSentTextEmail.text(data.suEmail);
$suBox.css("padding-left", "10px");
$suBox.css("padding-right", "10px");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<form method="post" action="" id="home-sign-up-form">
<input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input">
<input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input">
<input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input">
<input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
<input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
<input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input">
<br><font class="text-error" id="sign-up-error-text"></font>
<br>
<label>
<input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox"><font id="sign-up-remember-me-text">Remember me</font>
</label>
<input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>
<?php
if (isset($_POST['suEmail']))
{
$con=mysqli_connect("localhost","root","cakpep","backoffice");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$suFirstName = mysqli_real_escape_string($con,$_POST['suFirstName']);
$suLastName = mysqli_real_escape_string($con,$_POST['suLastName']);
$suEmail = mysqli_real_escape_string($con,$_POST['suEmail']);
$suPassword = mysqli_real_escape_string($con,$_POST['suPassword']);
$suDisplayName = mysqli_real_escape_string($con,$_POST['suDisplayName']);
$code = substr(md5(mt_rand()),0,15);
$query = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName,confirmCode,verified)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}','{$confirmCode},'{$verified}')");
echo json_encode($_POST);
}
?>
add this to trigger when submit form
$("#home-sign-up-form").submit(function(event) {
and then on php return the response with json string
echo json_encode($_POST);
and then in the response ajax parse json text to object like this
var data = JSON.parse(response);
$emailSentTextEmail.text(data.suEmail);
i hope this what you want..

Related

The $_POST unable to retrieve data from the text field in the html file

There is a discovery.html file that links to a validate_signup.php file through action in the html form. When in the I am in the validate_signup.php and try to retrieve the values with $_POST['XXX'] of the text fields in the form namely regFName, regSName, regEName, regPName it returns an error that states undefined index XXX.
File directory(not sure if it could play a part)
Folder-- HTML, PHP, ect
HTML-- discovery.html, ect
PHP-- validate_signup.php, ect
I create an other html and php file that works similarly and in this example it worked.
HTML FROM:
<form class="modal-content animate" onsubmit="return validate();" action="../PHP/validate-signup.php" methode="post">
<div class="containerL">
<label><b>First name</b></label>
<input type="text" class="LoginFromPage" id="regFName" placeholder="Enter Frist name" name="regFName" required>
<label><b>Surname</b></label>
<input type="text" class="LoginFromPage" id="regSName" placeholder="Enter Surname" name="regSName" required>
<labelb>Email</b></labelb>
<input type="text" class="LoginFromPage" id="regEName" placeholder="Enter Email" name="regEName" required>
<label><b>Password</b></label>
<input type="password" id="regPName" placeholder="Enter Password" name="regPName"required>
<button type="submit">Register</button>
<button type="button" onclick="document.getElementById('id02').style.display='none'" id="cancelbtn">Cancel</button>
<div id="error_para" ></span>
</div>
</form>
PHP:
$password = $_POST["regPName"];
$email = $_POST["regEName"];
$surname = $_POST["regSName"];
$firstname = $_POST["regFName"];
JS-validate data
var error="";
var name = document.getElementById( "regFName" );
if(valPass() == false)
{
error = "Password must contain an UpperCase, LowerCase, Number and Symbol character";
document.getElementById( "error_para" ).innerHTML = error;
return false;
}
var email = document.getElementById( "regEName" );
if( email.value == "" || email.value.indexOf( "#" ) == -1 )
{
error = " You Have To Write Valid Email Address. ";
document.getElementById( "error_para" ).innerHTML = error;
return false;
}
else
{
return true;
}
the correct method not methode
<form class="modal-content animate" onsubmit="return validate();" action="../PHP/validate-signup.php" method="post">
<div class="containerL">
<label><b>First name</b></label>
<input type="text" class="LoginFromPage" id="regFName" placeholder="Enter Frist name" name="regFName" required>
<label><b>Surname</b></label>
<input type="text" class="LoginFromPage" id="regSName" placeholder="Enter Surname" name="regSName" required>
<labelb>Email</b></labelb>
<input type="text" class="LoginFromPage" id="regEName" placeholder="Enter Email" name="regEName" required>
<label><b>Password</b></label>
<input type="password" id="regPName" placeholder="Enter Password" name="regPName" required>
<button type="submit">Register</button>
<button type="button" onclick="document.getElementById('id02').style.display='none'" id="cancelbtn">Cancel</button>
<div id="error_para"></span>
</div>
</form>

Submitting form with ajax and formspree using VuesJS

I'm trying to submit a form using formspree I get two different errors. When I try to submit the form after I refresh the page I get an error on a new page saying
Cannot POST /Contact
When I go back and try to submit the form again I get an error in the console saying:
POST https://formspree.io/sheabathandbody#mail.com 400 () jquery.min.js:4
send # jquery.min.js:4
ajax # jquery.min.js:4
(anonymous) # main.js:8
dispatch # jquery.min.js:3
r.handle # jquery.min.js:3
I've used this method/code to submit my forms before so i don't know what the problem could be
Contact.vue form
<form id="contact" name="contact-form" method="post" action = "">
<fieldset>
<input placeholder="Your name" name="name" type="text" id="name" tabindex="1" required="required">
</fieldset>
<fieldset>
<input placeholder="Your Email Address" name="email" id="email" type="email" tabindex="2" required="required">
</fieldset>
<fieldset>
<input placeholder="Your Phone Number (optional)" type="tel" tabindex="3">
</fieldset>
<fieldset>
<textarea placeholder="Type your message here...." tabindex="5" name="message" id="message" required="required"></textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="submit_btn" >Submit</button>
</fieldset>
</form>
Here's my main.js
(function($) {
$(window).on("load", function() {
// Contact form
var form = $("#contact");
form.submit(function(event) {
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: "https://formspree.io/sheabathandbody#mail.com",
method: "POST",
data: $(this).serialize(),
dataType: "json",
beforeSend: function() {
form.prepend(
form_status
.html(
'<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>'
)
.fadeIn()
);
}
}).done(function(data) {
form_status
.html(
'<p class="text-success">Thank you for contacting us. We will be in touch.</p>'
)
.delay(3000)
.fadeOut();
});
});
});
})(jQuery);
Guess this has nothing to do with VueJS since it does not use at all vue in that chunks of code you shared, this is pure jQuery.
Said that, the problem sending the form was because you were not listening correctly to submit event.
form.on('submit', function () { ... })
On the other hand, ajax call is not working correctly; you should check documentation of formspree.io and correct it.
Check next code
$(document).ready(function() {
// Contact form
var form = $("#contact");
form.on('submit', function(event) {
alert('Hola hola. This is working now!');
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: "https://formspree.io/sheabathandbody#mail.com",
method: "POST",
data: $(this).serialize(),
dataType: "json",
beforeSend: function() {
form.prepend(
form_status
.html(
'<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>'
)
.fadeIn()
);
}
}).done(function(data) {
form_status
.html(
'<p class="text-success">Thank you for contacting us. We will be in touch.</p>'
)
.delay(3000)
.fadeOut();
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="contact" name="contact-form" method="post" action="">
<fieldset>
<input placeholder="Your name" name="name" type="text" id="name" tabindex="1" value="blah" required="required">
</fieldset>
<fieldset>
<input value="email#email.com" placeholder="Your Email Address" name="email" id="email" type="email" tabindex="2" required="required">
</fieldset>
<fieldset>
<input value="123123123" placeholder="Your Phone Number (optional)" type="tel" tabindex="3">
</fieldset>
<fieldset>
<textarea placeholder="Type your message here...." tabindex="5" name="message" id="message" required="required">Damn</textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="submit_btn">Submit</button>
</fieldset>
</form>
You can create a method for example postNow.
methods: {
postNow() {
const link = "https://formspree.io/sheabathandbody#mail.com"
var data = new FormData();
data.append('_replyto',this.email)
data.append('message',this.message)
this.axios.post(link,data , {
headers: {
'Accept': 'application/json',
},
// body: data,
}).then(res =>{
console.log("response ===" ,res)
this.email = "" ;this.message=""; //don't forget to create your data
}).catch(err =>{
console.log(err)
});
}
},
And in your template you can use the simple HTML form with few tweaks ofc,
<form #submit.prevent="postNow" method="POST" >
<label>
Your email:
<input type="email" name="_replyto" v-model="email" />
</label>
<label>
Your message:
<textarea name="message" v-model="message"></textarea>
</label>
<button type="submit">Send</button>
</form>

Redirecting a form with multiple submit inputs

I have a form which has 3 separate input with a type of "submit".
The first two inputs output a message once they are clicked, but the final one is supposed to redirect to another page however it is not doing this. I think this is because the form is submitting and refreshing the page before it gets to the JavaScript for redirection.
Here is my code:
FORM.php
<form class="form" id="form" method="POST" enctype="application/x-www-form-urlencoded">
<br>
<input type="email" name="email" id="email" maxlength="80" value="<?php echo $email ?>" placeholder="Enter Your Email" /><br /><br>
<input id="button4" type="submit" value="Get Security Question" name="submit2" style="cursor:pointer;"/><br>
<br><input type="password" name="securitya"id="securitya" maxlength="20" value="<?php echo $securitya ?>" placeholder="Enter Your Security Answer" /> <br />
<br>
<input id="button3"type="submit" value="Check Answer" name="submit" style="cursor:pointer;"/>
<br>
<br><input type="password" name="newpassword" id="newpassword" maxlength="20" placeholder="Enter Your New Password" /> <br />
<br><input type="password" name="confirmpassword" id="confirmpassword" maxlength="20" placeholder="Re-Enter Your New Password" /> <br />
<br>
<input id="button2" type="submit" value="Change Password" disabled="disabled" name="submit" style="cursor:pointer;"/>
JavaScript
jQuery(function(){
$("#button2").click(function(){
$(".error").hide();
var hasError = false;
var passwordVal = $("#newpassword").val();
var checkVal = $("#confirmpassword").val();
if (passwordVal == '') {
$("#newpassword").after('<span class="error" >Please enter a password.</span>');
hasError = true;
} else if (checkVal == '') {
$("#confirmpassword").after('<span class="error">Please re-enter your password.</span>');
hasError = true;
} else if (passwordVal != checkVal ) {
$("#confirmpassword").after('<span id = "pass" class="error">Passwords do not match.</span>');
hasError = true;
}
if(hasError == true) { return false; }
else {
$("#button2").after('<span class="error">Passwords accepted.</span>');
window.location.href='adminsignin.php';
}
});
});
What is weird about this is the message 'Passwords accepted' appears on screen for a split second, but there is no redirection to 'adminsignin.php'
Can anyone help?
In your javascript, pass the event into the click handler, and preventDefault().
$("#butotn2").click(function(e) {
e.preventDefault();
...
}
the submit button has default behavior, so you'll want to prevent its default behavior so that you can perform your operations and then redirect with your window.location.href.
please try changing to document.location = 'your URL';

Submit a Form with jQuery and Ajax

Trying to get my register page posting the data to the database using Ajax and jQuery but having great difficulty.
I'm very new to ajax and cane seem to get my head around how to do this insert.
Would be very grateful of any advice regarding how to do this. Im not sure if what i have got is even remotely close at the moment.
As current when I click the submit button the page refreshes but there is no change to the database.
*html code
<html>
<head>
<title>Register</title>
<link rel="stylesheet" type="text/css" href="../css/stylesheet.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="../js/validation.js"></script>
<script type="text/javascript" src="../js/registerpost.js"></script>
</head>
<body>
<div id="container">
<div id="mainContent")>
<form class="basic-grey" method="post">
<h1>Registration Form<span>Please complete all fields.</span></h1>
<p>
<label><span>First Name:</span>
<input name="firstname" id="firstname" type="text" size="40" maxlength="40" placeholder="First Name" required/>
</label>
<label><span>Surname:</span>
<input name="lastname" id="lastname" type="text" size="40" maxlength="40" placeholder="Surname" required/>
</label>
<label><span>Username:</span>
<input name="username" id="username" oninput="checkUsername();" type="text" size="40" maxlength="40" placeholder="Username" required/>
</label>
<label><span>Email:</span>
<input name="email" id="email" oninput="checkEmail();" type="email" size="40" maxlength="40" placeholder="Email" required/>
</label>
<label><span>Password:</span>
<input name="password1" id="password1" type="password" size="40" maxlength="40" placeholder="********" required/>
</label>
<label><span>Confirm Password:</span>
<input name="password2" id="password2" oninput="checkPassword();" type="password" size="40" placeholder="********" required/>
</label>
</p>
<div align="center"><span align = "center" id="user-result"></span><br><br><br>
</div>
<div align="center">
<span> </span><input type="submit" class="button" id="submit_btn" value="Submit" />
</div>
</form>
</form>
</div>
</div>
</body>
</html>
php code
<?php
include 'connection.php';
$hash = password_hash($_POST['password2'], PASSWORD_DEFAULT, ['cost' => 11]);
$sql = "INSERT INTO members(firstname, lastname, username, email, password )
VALUES(:firstname, :lastname, :username, :email, :password )";
$stmt = $db->prepare($sql);
$stmt->bindParam(':firstname', $_POST['firstname'], PDO::PARAM_STR);
$stmt->bindParam(':lastname', $_POST['lastname'], PDO::PARAM_STR);
$stmt->bindParam(':username', $_POST['username'], PDO::PARAM_STR);
$stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
$stmt->bindParam(':password', $hash, PDO::PARAM_STR);
$results->$stmt->execute();
if($results) {
echo 'Welcome new member, and thanks you for registering with the website.';
echo '<br><br>Click here to return to the login page';
} else {
echo 'Did not work.';
}
?>
js code
$(document).ready(function() {
$('#submit_btn').click(function(){
var data = {};
data.firstname = $('#firstname').val();
data.lastname = $('#lastname').val();
data.username = $('#username').val();
data.email = $('#email').val();
data.password2 = $('#password2').val();
$.ajax({
type: "POST",
url: "../php/newuser.php",
data: data,
cache: false,
success: function (response) {
}
});
return false;
});
});
Any help would be greatly appreciated.
Thanks
Solved it was a simple error that i had made in the PHP file.
This
$results->$stmt->execute();
To this
$results = $stmt->execute();
Thanks all
You can do something like this. See details here:
https://webdevideas.wordpress.com/2013/07/30/n-forms-one-javascript/
$(document).ready(function(){
$(".ajaxform").bind("submit",function(e){
e.preventDefault();
var ajaxurl = $(this).attr("action");
var data = $(this).serialize();
$.post(ajaxurl,data,function(res){
$("#message").html(res.message);
},'json');
});
});

preventDefault() won't work with form.submit()

I'm trying to get my login form to either close my lightbox, or change the text of an errorbox depending on whether or not the login attempt was a success. I'm not sure, but i think it has to do with my
onclick="formhash(this.form, this.form.password);"
which is a JS function that hashes a password, then continues the form submit. it ends with
form.submit();
Here's my code:
HTML:
<form action="includes/process_login.php" method="post" name="login_form">
Email: <input class="searchform" type="text" name="email" size="20"/><br />
Password: <input class="searchform" type="password" name="password" id="password" size="20"/><br />
<input type="button" class="searchform"
value="Submit" size="40" style="height:45px; width:90px"
onclick="formhash(this.form, this.form.password);" />
<input type="text" id="errorbox" style="height:45px; width:180px" value=""><br>
</form>
JS:
<script>
!(function($){
$(function() {
$('form[name="login_form"]').on('submit', function(event){
event.preventDefault();//don't reload the page
$.post('includes/process_login.php', $(this).serialize(), function(data){
//data is a json object which contans the reponse
data = $.parseJSON(data);
$("fade").fadeOut();
$("light").fadeOut();
},
function(data){//error callback
data = $.parseJSON(data);
if(data.forbidden){
$("#errorBox").html("Error!");
}
else if(data.error){
$("#errorBox").html("Invalid request!");
}
});
});
return false;
});
})(window.jQuery);
</script>
PHP:
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start(); // Our custom secure way of starting a PHP session.
$response = array();
if (isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = $_POST['p'];
if (login($email, $password, $mysqli) == true) {
http_response_code(200);//HTTP OK, requires php 5.4
$response['success'] = true;
} else {
// Login failed
$response['error'] = true;
http_response_code(401);//HTTP forbidden
}
} else {
// The correct POST variables were not sent to this page.
$response['error'] = true;
http_response_code(400);//HTTP bad request
}
echo json_encode($response);
When I log in, the preventDefault() doesn't work. It opens process_login.php in a new page and displays "{"success":true}" on a blank page. Any suggestions? (keeping in mind that it needs to be as secure as possible)
You could try moving it all into a single handler call. By changing the type="button" to type="submit" on your form.
<form action="includes/process_login.php" method="post" name="login_form">
Email: <input class="searchform" type="text" name="email" size="20"/><br />
Password: <input class="searchform" type="password" name="password" id="password" size="20"/><br />
<input type="submit" class="searchform" value="Submit" size="40" style="height:45px; width:90px" />
<input type="text" id="errorbox" style="height:45px; width:180px" value=""><br>
Then you could move your formhash function into the submit function
!(function($){
$(function() {
$('form[name="login_form"]').on('submit', function(event){
event.preventDefault();//don't reload the page
formhash(var1, var2);
$.post('includes/process_login.php', $(this).serialize(), function(data){
//data is a json object which contans the reponse
data = $.parseJSON(data);
$("fade").fadeOut();
$("light").fadeOut();
},
...//the rest of your code

Categories

Resources