Ajax Form Not Doing Anything - javascript

I have a form using Ajax that is suppose to show an error to the user when something is incorrect when the login. When I click the submit button nothing happens. I hate asking Stack overflow but you got to do what you got to do. And yes, I have Apache configured to not need file extensions.
This is the tutorial I am following: https://www.youtube.com/watch?v=L7Sn-f36TGM
Login Script:
require("dbh.php");
if(isset($_POST['submit'])) {
$email = $_POST['email'];
$pwd = $_POST['pwd'];
$errorEmpty = false;
$errorEmail = false;
$errorWrong = false;
if(empty($email) || empty($pwd)) {
echo "<p class='loginText'>Please Enter an Email Address and Password!</p>";
$errorEmpty = true;
} else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<p class='loginText'>Please Enter a Valid Email Address!</p>";
$errorEmail = true;
} else {
echo "Success!";
}
} else {
echo "<p class='loginText'>An Error Occurred!</p>"
}
header("/login?test");
loginForm.js
$(document).ready(function() {
$("#loginFormInput").submit(function(event) {
event.preventDefault();
var email = $("#emailLogin").val();
var pwd = $("#pwdLogin").val();
$(".errorText").load("../php-scripts/login", {
email: email,
pwd: pwd
});
});
});
HTML Form:
<p class="errorText"></p>
<form action="../php-scripts/login.php" method="post" id="loginFormInput">
<input type="text" name="email" class="textInput" id="emailLogin" placeholder="Email" maxlength="512"> <br>
<input type="password" name="pwd" class="textInput" id="pwdLogin" placeholder="Password" maxlength="1024"> <br>
<p class="rememberText">Remember Me:</p>
<input type="checkbox" name="remember" class="rememberBox"> <br>
<input type="submit" value="Login" name="submit" class="submitInput" title="Login">
</form>

Your PHP code is doing if (isset($_POST['submit'])), but when you do the AJAX submission you don't provide a submit parameter. You need to add that to the parameters:
$(".errorText").load("../php-scripts/login", {
email: email,
pwd: pwd,
submit: 'Login'
});
Or you could remove that check from the PHP, if that script is only used to process the AJAX requests.

I think you're missing an element with class name errorText
Try adding a <div class="errorText"></div> somewhere

Related

Has Post request a limited number of parameters?

I'm trying to send to my server 5 parameters:
Action: will contain the name of the form, in this case "signin"
Name: Name of the person who wants to signin
Surname: Surname of the person who wants to signin
Email: Email of the person who wants to signin
Password: Password of the person who wants to signin
the problem is that my server reads only 4 parameters: Name, Surname, Email and Password, and it don't see Action!
Here's the code:
Javascript:
function signin() {
alert("OK");
var action = $(this).attr('name'); // puts in action the name of the form (this case "signin")
$.ajax({
type: "POST",
url: "submit.php",
data: {
Action: action, // the server don't see it!!
Name: document.getElementById('signin-name').value, // Name in the form
Surname: document.getElementById('signin-surname').value, // // Surname in the form
Email: document.getElementById('singin-email').value, // Email in the form
Password: document.getElementById('singin-password').value // // Password in the form
},
cache: false,
success: function() {
alert("success");
window.location.href = "index.php"; // load the index.php page, which contains the login form
}
});
}
PHP - Signin.php:
<!-- Signin Form -->
<?php
require('include/header.php');
?>
<div class="limiter">
<div class="form-container">
<div class="form-wrap">
<form action="submit.php" method="post" name="form-signin" id="form-signin" autocomplete="off">
<span class="form-title">Registration form</span>
<div class="form-field">
<label for="Name">Name</label>
<input type="text" name="Name" id="signin-name" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="Surname">Surname</label>
<input type="text" name="Surname" id="signin-surname" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="email">Email address</label>
<input type="email" name="Email" id="signin-email" class="form-control" required>
</div>
<div class="form-field">
<label for="Password">New password</label>
<input type="password" name="Password" id="signin-password" placeholder="Almeno 6 caratteri" class="form-control">
</div>
<div id="display-error" class="alert alert-danger fade in"></div><!-- Display Error Container -->
<div class="form-submit-container">
<div class="form-submit-wrap">
<button class="form-cancel-button" type="submit">Cancel</button>
<button class="form-submit-button" type="submit" onclick="signin()">Signin</button>
</div>
</div>
</form>
</div>
</div>
</div>
<?php require('include/footer.php');?>
PHP - Submit.php:
<?php
#Detect AJAX and POST request, if is empty exit
if((empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') or empty($_POST)){
exit("Unauthorized Acces");
}
require('inc/config.php');
require('inc/functions.php');
# Check if Login form is submitted
if(!empty($_POST) && $_POST['Action'] === 'form-login'){
# Define return variable. for further details see "output" function in functions.php
$Return = array('result'=>array(), 'error'=>'');
$email = $_POST['Email'];
$password = $_POST['Password'];
/* Server side PHP input validation */
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$Return['error'] = "Please enter a valid Email address.";
} else if($password === '') {
$Return['error'] = "Please enter Password.";
}
if($Return['error']!='') {
output($Return);
}
# Checking Email and Password existence in DB
# Selecting the email address of the user with the correct login credentials.
$query = $db->query("SELECT Email FROM USERS WHERE Email='$email' AND Password='$password'");
$result = $query->fetch(PDO::FETCH_ASSOC);
if($query->rowCount() == 1) {
# Success: Set session variables and redirect to Protected page
$Return['result'] = $_SESSION['UserData'] = $result;
} else {
# Failure: Set error message
$Return['error'] = 'Invalid Login Credential.';
}
output($Return);
}
# Check if Registration form is submitted
if(!empty($_POST) && $_POST['Action'] === 'form-signin') {
# Define return variable. for further details see "output" function in functions.php
$Return = array('result'=>array(), 'error'=>'');
$name = $_POST['Name'];
$surname = $_POST['Surname'];
$email = $_POST['Email'];
$password = $_POST['Password'];
# Server side PHP input validation
if($name === '') {
$Return['error'] = "Please enter Full name.";
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$Return['error'] = "Please enter a valid Email address.";
} else if($password === '') {
$Return['error'] = "Please enter Password.";
}
if($Return['error']!='') {
output($Return);
}
# Check Email existence in DB
$result = $db->query("SELECT Email FROM USERS WHERE Name='$name' AND Surname='$surname' AND Email='$email'");
if($result->rowCount() == 1){
# Email already exists: Set error message
$Return['error'] = 'You have already registered with us, please login.';
}else{
# Insert the new user data inside the DB
try{
$db->query("INSERT INTO `users` (`ID_user`, `Name`, `Surname`, `Email`, `Password`) VALUES (NULL, '$name', '$surname', '$email', '$password')");
}
catch (PDOException $e) {
echo $e->getMessage();
}
# Success: Set session variables and redirect to Protected page
$Return['result'] = $_SESSION['UserData'] = $result;
}
output($Return);
}
PHP - Functions.php
# Function to set JSON output
function output($Return=array()){
header('Content-Type: application/json; charset=UTF-8');
#exit(json_encode($Return)); # Final JSON response
echo json_encode($Return);
}
here is a screenshot of the debugger:
Debug Screenshot
function signin() {
alert("OK");
var action = $('#form-signin').attr('name'); // puts in action the name of the form (this case "signin")
// alert(action);
$.ajax({
type: "POST",
url: "submit.php",
data: {
Action: action, // the server don't see it!!
Name: $('signin-name').val(), // Name in the form
Surname: $('signin-surname').val(), // // Surname in the form
Email: $('singin-email').val(), // Email in the form
Password: $('singin-password').val() // // Password in the form
},
cache: false,
success: function() {
alert("success");
window.location.href = "index.php"; // load the index.php page, which contains the login form
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="limiter">
<div class="form-container">
<div class="form-wrap">
<form action="submit.php" method="post" name="form-signin" id="form-signin" autocomplete="off">
<span class="form-title">Registration form</span>
<div class="form-field">
<label for="Name">Name</label>
<input type="text" name="Name" id="signin-name" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="Surname">Surname</label>
<input type="text" name="Surname" id="signin-surname" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="email">Email address</label>
<input type="email" name="Email" id="signin-email" class="form-control" required>
</div>
<div class="form-field">
<label for="Password">New password</label>
<input type="password" name="Password" id="signin-password" placeholder="Almeno 6 caratteri" class="form-control">
</div>
<div id="display-error" class="alert alert-danger fade in"></div><!-- Display Error Container -->
<div class="form-submit-container">
<div class="form-submit-wrap">
<button class="form-cancel-button" type="submit">Cancel</button>
<button class="form-submit-button" type="submit" onclick="signin()">Signin</button>
</div>
</div>
</form>
</div>
</div>
</div>
The problem is with your scope for $this. Since your Javascript is called within a BUTTON element, $this has a scope relative to the button, not the form. In trying to check what $this returns by itself, it says [object Window].
function signin() {
console.log(this);
}
Console:
[object Window]
You need to either pass this via signin(this) and backtrack to the containing form element if you plan on reusing the Javascript for other forms or just use the form id in place of this.
HTML:
<button onclick="signin(this)">
JS:
function signin(element) {
var action = element.form.getAttribute("name");
}
or just simply change the this to the form's id as Lakmal pointed out:
function signin() {
var action = $("#form-signin").attr("name");
}

PHP and Javascript Validation of Password Match

Trying to get page to dynamically show if passwords match (echo 'Match' or 'Do not match'). (Similiar to previous question asked here.)
Looking to check if password1 and password2 are the same as you type in either the 'password' or 'confirm password' input boxes.
EDIT: Seems elseif ($password2 == $password1) isn't checking for the match as I intended. Posting of password1 and password2 works (#feedback changes to 'Do not match' as you type in either input box, but 'Match' never shows). Any help on how to fix this code is appreciated.
check.php
<?php
include __DIR__ . '/mysqli_connect.php';
$password2 = mysqli_real_escape_string($dbc, $_POST['password2']);
$password1 = mysqli_real_escape_string($dbc, $_POST['password1']);
if ($password2==NULL && $password1==NULL) {
echo '';
} elseif ($password2 == $password1) {
echo 'Match';
} else {
echo 'Do not match';
}
register.php
<script type="text/javascript" src="/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function() {
$('#feedback').load('/includes/check.php').show();
$('#password1').keyup(function() {
$.post('/includes/check.php', { password1: form.password1.value },
function(result) {
$('#feedback').html(result).show;
});
});
});
$(document).ready(function() {
$('#feedback').load('/includes/check.php').show();
$('#password2').keyup(function() {
$.post('/includes/check.php', { password2: form.password2.value },
function(result) {
$('#feedback').html(result).show;
});
});
});
</script>
<form action="register.php" method="post" name="form">
<input id="password1" class="signup_input_box" type="password" name="password1" maxlength="20" value="<?php if (isset($trimmed['password1'])) echo $trimmed['password1']; ?>">
<input id="password2" class="signup_input_box" type="password" name="password2" maxlength="20" value="<?php if (isset($trimmed['password2'])) echo $trimmed['password2']; ?>">
<div id="feedback"></div>
<p><center><input type="submit" name="submit" value="Register"></center>
</form>
Skipped using MySql posting and used JS only to check the value of the password inputs and show text upon keyup. Reference here.

Displaying form confirmation message on form submit

Thought you might be able to help with this, as I sort of know what I want and how to do it but I am not overally familiar with AJAX/JS and after a certain point I just stopped taking stuff in.
Basically, I am trying to have some text appear when a user submits a form, but obviously only when the form is successfully sent. My HTMl and PHP are below, but I have no idea what I am doing beyond this point so maybe someone can give me a little hand.
<form name="contactform" action="includes/contactprocess.php" method="post">
<div class="form-group">
<input type="text" class="form-control" id="fname" name="fname" required placeholder="First Name">
</div>
<div class="form-group">
<input type="text" class="form-control" id="sname" name="sname" required placeholder="Last Name">
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" required placeholder="Email Address">
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" required placeholder="Message Subject">
</div>
<div class="form-group">
<textarea rows="3" name="comment" class="form-control" required placeholder="Enter Comment"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
Here is the PHP thus far:
<?php
/* Set e-mail recipient */
$myemail = "myemailhere";
/* Check all form inputs using check_input function */
$fname = check_input($_POST['fname'], "Enter your first name");
$sname = check_input($_POST['sname'], "Enter your second name");
$subject = check_input($_POST['subject'], "Enter the message subject");
$email = check_input($_POST['email']);
$comment = check_input($_POST['comment'], "Enter the message you wish to be sent");
/* Error handling and sanitisation for email */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("The e-mail you have entered is not valid");
}
/* Let's prepare the message for the e-mail */
$message = "A contact form has been submitted by;
Name: $fname
Surname: $sname
E-mail: $email
Comments:
$comment
Message sent via myemailhere
";
/* Send message via mail function */
mail($myemail, $subject, $message);
if(mail($myemail, $subject, $message)) {
$data['success'] = true;
}
else{
$data['success'] = false;
}
// convert the $data to json and echo it
// so jQuery can grab it and understand what happend
echo json_encode($data);
/* Check input */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<b>Please correct the following error:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php
exit();
}
?>
The JS/AJAX I don't really understand:
<script>
$(document).ready(function() {
// hide the success message
$('#success').hide();
// process the form
$('form').submit(function(event) {
// get the form data before sending via ajax
var formData = {
'name' : $('input[name=name]').val(),
'number' : $('input[name=number]').val(),
'message' : $('input[name=message]').val(),
'contactSubmit' : 1
};
// send the form to your PHP file (using ajax, no page reload!!)
$.ajax({
type: 'POST',
url: 'file.php', // <<<< ------- complete with your php filename (watch paths!)
data: formData, // the form data
dataType: 'json', // how data will be returned from php
encode: true
})
// JS (jQuery) will do the ajax job and we "will wait that promise be DONE"
// only after that, we´ll continue
.done(function(data) {
if(data.success === true) {
// show the message!!!
$('#success').show();
}
else{
// ups, something went wrong ...
alert('Ups!, this is embarrasing, try again please!');
}
});
// this is a trick, to avoid the form submit as normal behaviour
event.preventDefault();
});
});
</script>

Validate email inside textarea

I made a form with only a textarea, so i want the form be validate only if the message has a valid email inside the textarea,
But if i use FILTER_VALIDATE_EMAIL, it's allows only email, without space or message.
How can i fix it?
My code:
<form action="contact.php" method="post">
<p>
<textarea rows="1" style="height:1em;" id="text" autofocus>Hello my name is M2PV,
</textarea>
</p>
<p>
<input value="send" type="submit" id="send">
</p>
</form>
$('form').submit(function(){
message = $(this).find('#text').val();
$.post('contact.php',{
message:message
}, function(data){
if(data.error=='ok'){
alert('formulaire ok');
}else{
alert('email invalid');
}
},"json");
return false;
});
});
<?php
$e= array();
$e['error'] = "Entrez votre email";
if(!filter_var($_POST['message'], FILTER_VALIDATE_EMAIL)){
$e['email_invalid'] = "email_invalid";
}else{
$e['error'] = 'ok';
$message = $_POST['message'];
$to = 'xxxx#xx.com';
$sujet = ' Contact site ';
$msg = $message;
//mail($to, $sujet, $msg);
}
echo json_encode($e)
?>
My suggestion is to parse all e-mail addresses and validate them
HERE you can find inspiration for parsing multiple e-mail addresses and put them in an array. After that you could iterate over the array and validate them

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