Broke my javascript with if else - javascript

I feel like I'm missing something really simple, so I've decided to get over my stubbornness and actually ask a question here instead of wasting any more time.
I've started making my personal blog from scratch (for the personal challenge and learning experience of it) not too long ago and I'm currently on writing the code for email validation; the standard send email with token & email GET variables. It works properly (hooray), but there's one problem that was introduced when I decided to add email validation to the back end. The ajax call is still successful and returns the right string; however, once I added an else if statement to my javascript to handle showing error messages for invalid email that gets (or is forced) through, it seems to act as though there isn't a curly bracket--my success boolean which determines the success/failure of my alert is set to false and the string displayed to the user is also not as I intended. Here's my code and a screenshot to illustrate:
*I changed the if..else to a switch to see if it would change anything--it didn't.
//JAVASCRIPT
$("form").submit(function(event) {
if(request) request.abort;
var message = "";
var success = false;
var formMessageBox = document.getElementById("form-message");
var form = $(this);
var inputs = form.find("input");
var data = inputs.serialize();
inputs.prop("disabled", true);
request = $.ajax({
url: "php/form.php",
type: "post",
data: data
});
request.done(function(data) {
var submission = data;
switch (submission) {
case "success":
message = "You're good to go! You'll be receiving an email shortly from <strong>my_email</strong>, just to make sure everything's in the green";
$("form").innerHTML = "";
success = true;
break;
case "fail":
message = "Seems this email is already in my database; you may have submitted twice, or somebody might have hijacked your email--don't worry, it's more than likely the former.";
success = false;
break;
default:
message = submission;
success = false;
break;
}
});
request.always(function() {
inputs.prop("disabled", false);
if(success) {
formMessageBox.classList.add("alert-success");
if (formMessageBox.classList.contains("alert-danger")) formMessageBox.classList.remove("alert-danger");
}
else {
formMessageBox.classList.add("alert-danger");
if (formMessageBox.classList.contains("alert-success")) formMessageBox.classList.remove("alert-success");
}
formMessageBox.innerHTML = message;
});
event.preventDefault();
})
//PHP
<?php
if(!$_POST["email"]) {
echo "Please enter an email address";
exit(0);
}
if($_POST["email"] AND !filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
echo "Please enter a valid email address";
exit(0);
}
$dbconn = mysqli_connect("localhost","username", "password", "db");
if (mysqli_connect_error()) die("There seems to be something wrong. Sorry, try again later");
require_once('CryptoLib.php');
$token = CryptoLib::randomString(16);
$name = isset($_POST['name']) ? $_POST['name'] : "user";
$email = $_POST['email'];
$emailTo="$email";
$subject="Web Devs' Corner Verification";
$body="http://www.allen-mcintoshii.com/webdevscorner/php/verify.php?conf-token=".$token."&email=".$email;
$headers="From: my_email";
$query = "INSERT INTO `users` (`name`, `email`, `conf_token`) VALUES ('$name', '$email', '$token')";
$result = mysqli_query($dbconn, $query);
if ($result AND mail($emailTo, $subject, $body, $headers)) echo "success";
else echo "fail"; ?>
My 'successful error'
To be honest, it's not all that critical, but it definitely is not what I intend to happen, so why not use this little quirk as a chance to learn something? Thanks in advance to everyone who decides to help me out.

Well, while I was trying to do something similar for another small project, I actually found my own soloution. I'll just leave it here in case anyone finds themselves in a similar predicament.
//PHP
<?php
session_start();
$errors = array();
$errors[] = "You have been successfully signed up! Welcome to your diary!";
$min_chars = 8;
$email = $_POST['email'];
$password = $_POST['password'];
if (!$email) {
$errors[] = "Please enter an email address.";
}
if ($email AND !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Please enter a valid email address";
}
if (!$password) {
$errors[] = "Please enter a password.";
}
else {
if (strlen($password) < $min_chars) $errors[] = "Your password must be at least $min_chars characters";
if (!preg_match('`[A-Z]`', $password)) $errors[] = "Your password is required to have at least on capital letter";
}
if (!$errors[1]) {
$dbconn = mysqli_connect(args) //just hiding what needs to be hidden here;
if (mysqli_connect_error()) die("There seems to be something wrong. Sorry, try again later");
$query = "SELECT * FROM users WHERE `email` ='".mysqli_real_escape_string($dbconn, $email)."'";
$results = mysqli_num_rows(mysqli_query($dbconn, $query));
if ($results != 0) $errors[] = "We're sorry, that email is already in our database, did you mean to log in?";
else {
$query = "INSERT INTO `users` (`email`, `password`) VALUES ('".mysqli_real_escape_string($dbconn, $email)."', '".password."')";
$result = mysqli_query($dbconn, $query);
$_SESSION['id'] = mysqli_insert_id($dbconn);
}
}
if ($errors[1]) session_destroy();
echo json_encode($errors);
?>
//Javascript
$(document).ready(function() {
var msgBox = $("#message-box");
$("#signup").submit(function(e) {
e.preventDefault();
var formData = $(this).serialize();
$.post("signup.php", formData, function(data) {
var success = data.length == 1 ? true : null,
numErrors = data.length,
errors = "";
if (success != null) {
msgBox.addClass("alert-success");
msgBox.removeClass("alert-danger");
msgBox.html(data[0]);
}
else {
msgBox.addClass("alert-danger");
msgBox.removeClass("alert-success");
var i;
for (i = 1; i < numErrors; i++) {
errors = errors + "<li>" + data[i] + "</li>";
}
msgBox.html("<ul>" + errors + "</ul>");
}
}, "json")
})
$("#login").submit(function(e) {
$.post()
})
})
Instead of trying to return different strings in the event of pass/fail, I decided to let PHP return one JSON object at the end no matter what. By placing the success message at the very top and pushing any error messages as the code moves along, it becomes way easier to just check if the return data's length is only 1 or greater. If it's 1, there were no errors and everything went fine; else, a for loop iterates through all the returned messages starting from the second one, effectively printing out all errors occurred. I hope this helps anybody who found themselves in a similar bind

Related

jQuery AJAX check if email exists in database not working

I am trying to use jQuery, AJAX, PHP, and MySQL to check if an email entered into a form already exists in a database.
This is my current jQuery code :
$.post('check-email.php', {'suEmail' : $suEmail}, function(data) {
if(data=='exists') {
validForm = false;
$suRememberMeCheckbox.css('top', '70px');
$suRememberMeText.css('top', '68px');
$signUpSubmit.css('top', '102px');
$tosppText.css('top', '115px');
$suBox.css('height', '405px');
$suBox.css('top', '36%');
$errorText.text('The email has been taken.');
return false;
};
});
And this is my PHP code:
<?php include("dbconnect.php") ?>
<?php
$sql = "SELECT email FROM users WHERE email = " .$_POST['suEmail'];
$select = mysqli_query($connection, $sql);
$row = mysqli_fetch_assoc($select);
if (mysqli_num_rows($row) > 0) {
echo "exists";
}
?>
When I go through with the sign up form, when I use an email already in the database, the error text never changes to what I specified, but instead to some other error cases I have coded. Why is this not working! Thanks so much!
Use This Code: Working Perfectly:
<?php
include("dbconnect.php");
$sql = "SELECT email FROM users WHERE email = '" .$_POST['suEmail']."' ";
$select = mysqli_query($connection, $sql);
$row = mysqli_fetch_assoc($select);
if (mysqli_num_rows($select) > 0) {
echo "exists";
}
?>
If its not changing that means you might have a error with your query. Check developer options on your browser under network. There you can see all ajax calls being made. Click on look at the response. Check to see if there was an error with your query.
Also you have to validate the form submission.
Something like.
if($_SERVER['REQUEST_METHOD'] = 'POST')
{
//maybe send a token over with the form to prevent form spoofing
if($_POST['token'] === $_SESSION['token'])
{
// all your code goes in here
// you provably want to check that is a real email also
// check email input against regular expression
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
//if valid email to variable and escape data
$e = sanitizeString($_POST['email']);
}else
{
/// if not a real email to errors array
$reg_errors['email'] = 'Please enter a valid email address!';
}
}
}
You have to use prepare statements in your queries.

Inserting to database after validation has passed using ajax, php and javascript

This my signUp.php I dont know what is wrong here that prevents my form values from being inserted into the database
<?php
$errors = array();
$data = array();
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if(empty($_POST["full_Name"])){
$errors['full_Name'] = "Please fill in yor full name";
}
else{
$full_Name = test_Inputs($_POST['full_Name']);
//using regular expression to check if the name includes only letters and whitespaces
if(#!preg_match("/^[A-z\s]*$/", $full_Name)){
$errors['full_Name'] = "Only alphabets and whitespace";
}
}
if(empty($_POST['user_phoneNumber'])){
$errors['user_phoneNumber'] = "Mobile number is required";
}
else{
$mobileNumber = test_Inputs($_POST['user_phoneNumber']);
// using regex to make sure only numbers are inputted in the field
if(#!preg_match("/^[0-9]+$/", $mobileNumber)){
$errors['user_phoneNumber'] = "Only numbers allowed";
}
}
if(empty($_POST['user_Email'])){
$errors['user_Email'] = "Please fill in your email address";
}
else{
$Email = test_Inputs($_POST['user_Email']);
//using regex to validate email input
if(#!preg_match("/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/", $Email)){
$errors['user_Email'] = "Invalid Email address";
}
}
if(empty($_POST['userName'])){
$errors['userName'] = "User name field is blank";
}
else{
$userName = test_Inputs($_POST['userName']);
if(#!preg_match("/^[A-z0-9]+$/", $userName)){
$errors['userName'] = "Only letters and numbers allowed";
}
}
if(empty($_POST['password'])){
$errors['password'] = "Password field is blank";
}
else{
$password = test_Inputs($_POST['password']);
if(#!preg_match("/^[A-z0-9]+$/", $password)){
$errors['password'] = "Only letters and numbers allowed";
}
if(strlen($password) < 8){
$errors['password'] = "Password must be at least 8 characters long";
$valid = false;
}
}
if(empty($_POST['RPassword'])){
$errors['RPassword'] = "Confirm your password";
$valid = false;
}
else{
$RPassword = test_Inputs($_POST['RPassword']);
if($RPassword != $password){
$errors['RPassword'] = "Passwords do not match";
}
}
if(!isset($_POST['terms'])){
$errors['terms'] = "Agree to the terms";
}
else {
$Terms = test_Inputs($_POST['terms']);
}
// if there are any errors in our errors array, return a success boolean of false
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
// if there are no errors process our form, then return a message
// Inserting into the database
require_once ('insert_user.php');
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = 'Success!';
}
//return all our data on AJAX call
echo json_encode($data);
//creating the test_puts functions
function test_Inputs($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
This is my dbConn.php
<?php
$host = "localhost";
$db_name = "Interns";
$username = "root";
$password = "";
try {
$dbh = new PDO("mysql:host=$host;dbname=$db_name", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $ex){
echo "Failed to connect" .$ex->getMessage();
}
this is my insertUser.php code
<?php
require_once ('dbConn.php');
$salt = "cH!swe!retR:";
If(isset($_POST['submit'])) {
try {
$stmt = $dbh->prepare("INSERT INTO Users(FullName, MobileNumber, Email, Username, Password)
VALUES(:user_name, :user_mobile, :user_email, :user_username, :user_pass)");
$stmt->bindParam(":user_name", $full_Name);
$stmt->bindParam(":user_mobile", $mobileNumber);
$stmt->bindParam(":user_email", $Email);
$stmt->bindParam(":user_username", $userName);
$stmt->bindParam(":user_pass", $password);
$full_Name = $_POST['full_Name'];
$mobileNumber = $_POST['user_phoneNumber'];
$Email = $_POST['user_Email'];
$userName = $_POST['userName'];
$password = SHA1(($_POST['password']), $salt);
$stmt->execute();
echo "Query successful";
} catch (PDOException $ex) {
echo "Query Failed" . $ex->getMessage();
}
}
$dbh = null;
This is my signUp.js
// signUpValidation.js
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
$('.form-group').removeClass('has-error'); // remove the error class
$('.help-block').remove(); // remove the error text
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'full_Name' : $('input[name=full_Name]').val(),
'user_phoneNumber' : $('input[name=user_phoneNumber]').val(),
'user_Email' : $('input[name=user_Email]').val(),
'userName' : $('input[name=userName]').val(),
'password' : $('input[name=password]').val(),
'RPassword' : $('input[name=RPassword]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'signUpValidation.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
if ( ! data.success) {
// handle errors for name ---------------
if (data.errors.full_Name) {
$('#name-group').addClass('has-error'); // add the error class to show red input
$('#name-group').append('<div class="help-block">' + data.errors.full_Name + '</div>'); // add the actual error message under our input
}
// handle errors for email ---------------
if (data.errors.user_phoneNumber) {
$('#mobile-group').addClass('has-error'); // add the error class to show red input
$('#mobile-group').append('<div class="help-block">' + data.errors.user_phoneNumber + '</div>'); // add the actual error message under our input
}
// handle errors for superhero alias ---------------
if (data.errors.user_Email) {
$('#email-group').addClass('has-error'); // add the error class to show red input
$('#email-group').append('<div class="help-block">' + data.errors.user_Email + '</div>'); // add the actual error message under our input
}
if (data.errors.userName) {
$('#username-group').addClass('has-error'); // add the error class to show red input
$('#username-group').append('<div class="help-block">' + data.errors.userName + '</div>'); // add the actual error message under our input
}
if (data.errors.password) {
$('#password-group').addClass('has-error'); // add the error class to show red input
$('#password-group').append('<div class="help-block">' + data.errors.password + '</div>'); // add the actual error message under our input
}
if (data.errors.RPassword) {
$('#retypePassword-group').addClass('has-error'); // add the error class to show red input
$('#retypePassword-group').append('<div class="help-block">' + data.errors.RPassword + '</div>'); // add the actual error message under our input
}
} else {
// ALL GOOD! just show the success message!
$('form').append('<div class="alert alert-success">' + data.message + '</div>');
// usually after form submission, you'll want to redirect
// window.location = '/thank-you'; // redirect a user to another page
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
I would be glad if someone puts me through. Please note I sent the form through an AJAX call to the signUp.php.
Do you know about this in your AJAX code: url: 'signUpValidation.php',
sinse your file is signUp.php?
That is a lot of code but you are calling signUp.php then require_once ('insert_user.php'); in it and then in insert_user you are using $_POST["full_Name"] again even when you validated it already in signUp.php. Shouldn't insert_user.php just make the query in the DB?
And you are checking If(isset($_POST['submit'])) in insert_user.php. You should check it in signUp.php.
I would organize the code in functions at least if not classes: functionConnectToDB, fnInsertUser...
signUp.php:
require_once('functions.php');
if(isset($_POST['submit'])) {
validations you have
}
if (empty($errors)) {
fill $data array with $full_Name etc. cause you didn't do it!
insertUser($data);
}
functions.php:
function connectDB() {
...
}
function insertUser($data) {
connectDB();
insert DB query
...
}

How to convert object into HTML bullet list?

I have an object I retrieve via a JSON AJAX request, which looks like this:
{
"success":false,
"errors": {
"name":"Name you entered is not valid!",
"emailError":"The email address you entered is not valid"
}
}
Now I need to convert the errors property in to an HTML list. This is how I use these errors at this stage:
if (!data.success) { // If fails
if (data.errors.emailError) {
$('#messages').fadeIn(1000).append('<div class="response-output">' + data.errors.emailError + '</div>');
}
}
UPDATE:
My server side code look like this:
$errors = array(); //To store errors
$form_data = array(); //Pass back the data to `form.php`
if(isset($_POST['your_name'], $_POST['your_email'], $_POST['your_message'])) {
// Sanitize and validate the data passed in
if (preg_match ('/^[A-Z \'.-]{2,60}$/i', $_POST['your_name'])) {
$name = filter_input(INPUT_POST, 'your_name', FILTER_SANITIZE_STRING);
} else {
$errors['name'] = 'Name you entered is not valid!';
}
$email = filter_input(INPUT_POST, 'your_email', FILTER_SANITIZE_EMAIL);
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Not a valid email
$errors['emailError'] = 'The email address you entered is not valid';
}
// if form fields ok
if (empty($errors)) {
// --- my mail
$mail_sent = mail($sendTo, $subject , $emailbody, implode("\r\n", $headers));
if ($mail_sent == true){
// Success massege
$form_data['success'] = true;
$form_data['posted'] = 'Your requirement have been sent. We will get back to you soon.';
}
} else {
$form_data['success'] = false;
$form_data['errors'] = $errors;
}
//Return the data back to form.php
echo json_encode($form_data);
}
But I want to create HTML list inside my #messages div. Hope somebody may help me out.
You can use a for loop to iterate over the properties of the errors object when success is false, and from there create the needed ul and li elements:
if (!json.success) {
var $ul = $('<ul />').appendTo('#messages');
for (var key in json.errors) {
$('<li />', {
text: key + ': ' + json.errors[key]
}).appendTo($ul);
}
}
Example fiddle
Note that the response could be improved by making the errors property contain an array instead of an object. How you achieve that would be down to the way you generate the response from the AJAX request.

AJAX not returning a variable from php

I know there is a few questions like this on here. but I have done a lot of researching and bug fixing all day to try work out why my ajax does not return a response from the php file. All I want is for it to tell me a user has been registered so I can let the user move on with the signing up process. And I just need someones wise guidance to tell me what I am doing wrong!!
so I wont bore you with the validation part of the js file just the ajax
if(ValidationComplete == true){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(register, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url:url,
type:type,
data: data,
dataType: 'json',
success: function(result){
alert(result.status);
console.log(result.data);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
return false;
} else {
return false;
}
currently with this, if I remove the dataType bit the alert bit happens but currently with it there nothing does.
again I will just skip to the chase on the php file
$query = "INSERT INTO person
VALUES('','$first_Name','$surname','$email','$dob','$password',
'1','','0','1','','','','$emailCode')";
if($query_run =mysql_query($query)) {
echo json_encode(array("response"='true'));
Any help would be amazing!!!!!
updated code:
<?php
if( isset($_POST['firstname']) &&
isset($_POST['surname']) &&
isset($_POST['email']) &&
isset($_POST['day']) &&
isset($_POST['month']) &&
isset($_POST['year']) &&
isset($_POST['password']) &&
isset($_POST['re_type_password'])){
$first_Name = $_POST['firstname'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
$re_type_password = $_POST['re_type_password'];
$emailCode = md5($_POST['$first_Name'] + microtime());
if(!empty($first_Name)&&
!empty($surname)&&
!empty($email)&&
!empty($day) &&
!empty($month) &&
!empty($year) &&
!empty($password)&&
!empty($re_type_password)){
if(strlen($firstname)>30 || strlen($surname)>30 || strlen($email)>50){
echo 'the data enetered is to long';
} else {
if($password != $re_type_password){
echo 'passwords do not match, please try again.';
} else{
$query = "SELECT email FROM person WHERE email ='$email'";
$query_run = mysql_query($query);
if(mysql_num_rows($query_run)==1){
echo 'Email address already on databse';
} else{
if($day>31 || $month>12){
echo 'date of birth wrong';
} else{
$dob= $year.'-'.$day.'-'.$month;
$query = "INSERT INTO person
VALUES('','$first_Name','$surname','$email','$dob','$password'
,'1','','0','1','','','','$emailCode')";
if($query_run =mysql_query($query)) {
email($email, 'Email Confirmation', "hello ". $first_Name." ,
\n\n you need to activate your account so click the link ");
$return_data['status'] = 'success';
echo json_encode($return_data);
} else {
echo #mysql_error();
}
}
}
}
}
} else {
echo "<p id='error'> All fields are required. Please try again.</p>";
}
}
?>
<?php
} else if (loggedIn()) {
echo 'you are already registed and logged in';
}
?>
</body>
</html>
the last line it should be
echo json_encode(array("response"=>'true'));
see the added > in the array declaration, that is used to assign arrays with keys.
also in general you should put a error capture in your ajax statement, see this answer for more info
EDIT: Ok wow, that's some spaghetti code you have there, but after a little clean-up your problem is too many closing braces } you have to remove the } just before the following line also get rid of the closing and opening tags around this line, they serve no use.
} // <------- THIS ONE!
} else if (loggedIn()) {
echo 'you are already registed and logged in';
}
I should also mention two other issues with your code
You are accepting input from the user without cleaning it up and testing it properly. This is no no read here to find out more
You are using mysl_ functions, these are old and depreciated they are also security risks. Check out PDO instead
EDIT:
Add ini_set('error_reporting',1); to the top of your php script.

$.post callback return strange data

I think this might be the cause of why my code is not working.. The 'if(name.val().length > 3)' is never can execute so I put an alert to test the returned data, this is what it look like :
my js
$(document).ready(function(){
var form = $("#customForm");
var name = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var pass1 = $("#pass1");
var passInfo = $("#pass1Info");
var pass2 = $("#pass2");
var pass2Info = $("#pass2Info");
var state = false;
name.keyup(validateName);
function validateName(){
if(name.val().length <= 3){
name.removeClass("valid");
nameInfo.removeClass("valid");
name.addClass("error");
nameInfo.addClass("error");
nameInfo.text("Minimum 4 characters!");
state = false;
}else{
if(name.val().length > 3){
var username=name.val();
$.post('validate.php',{names: username},function(data){
alert(data);
if(data!=0){
name.removeClass("valid");
nameInfo.removeClass("valid");
name.addClass("error");
nameInfo.addClass("error");
nameInfo.text("The username is already taken!");
state = false;
}else{
name.removeClass("error");
nameInfo.removeClass("error");
name.addClass("valid");
nameInfo.addClass("valid");
nameInfo.text("username available");
state = true;
}
});
}
}
}
return state;
//end
});
my PHP code :
<?php
$name = $_POST['names'];
$email = $_POST['emails'];
if($name !=""){
mysql_connect("localhost","root","") or die("Fail to connect to database");
mysql_select_db("reglog");
$uname = mysql_query("SELECT username FROM users WHERE username='$name'");
$count = mysql_num_rows($uname);
if($count !=0){
echo 1;
}else{
echo 0;
}
}
if($email !=""){
mysql_connect("localhost","root","") or die("Fail to connect to database");
mysql_select_db("reglog");
$useremail = mysql_query("SELECT email FROM users WHERE email='$email'");
$countemail = mysql_num_rows($useremail);
if($countemail !=0){
echo 1;
}else{
echo 0;
}
}
?>
It is throwing an warning. Make a habit of checking if a index is available in an array, thus removing possibilities of such error.
$email = isset($_POST['emails']) ? $_POST['emails'] : '';
or do not display any errors to suppress such warning (not recommended).
And as mentioned by Kai, you haven't passed any variables as emails.
$.post('validate.php',{ names: username, 'emails' : email }, ... }
You aren't passing emails as a post variable.
$.post('validate.php',{names: username},function(data){
should be
$.post('validate.php',{names: username, emails: email},function(data){
AS starx says, you should check post values with isset before running processes on the variables
Make return type to html and it will work.

Categories