I was trying to have my form validate an email address onblur or onkeyup, to check to see if the email address already exists in my database.
Not sure if I'm almost there with this code, something isn't working though. Right now, as soon as I start typing in the field, the input box for email is flagged based on how I would want it flagged if an email address was entered if it was already in my database. The else statement in AJAX doesn't work, and if I submit the form anyway, I get a message on the page from an error box I created mentioning a syntax error.
Also, part of my php is using mysqli and mysql, does that make a difference with trying to get this input field to validate?
The input id is email and the name is Email; I think I have that correct in my code, not entirely sure though.
PHP:
define('DB_NAME', 'database');
define('DB_USER', 'user');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'host');
$first = Trim(stripslashes($_POST['First']));
$last = Trim(stripslashes($_POST['Last']));
$city = Trim(stripslashes($_POST['City']));
$state = Trim(stripslashes($_POST['State']));
$country = Trim(stripslashes($_POST['Country']));
$email = Trim(stripslashes($_POST['Email']));
$tempt = $_POST['tempt'];
$tempt2 = $_POST['tempt2'];
$link = mysqli_connect('host','user','password','members') or die("Error " . mysqli_error($link));
$stmt = mysqli_prepare($link, 'SELECT count(*) FROM members WHERE email =?');
mysqli_stmt_bind_param($stmt, 's', $_POST['Email']);
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $count);
/* fetch value */
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
if ($count == 0) {
echo 'true';
}else{
echo 'false';
}
if ($tempt == 'http://' && empty($tempt2)) {
$error_message = '';
$reg_exp = "/^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/";
if(!preg_match($reg_exp, $email)) {
$error_message .= "<p>A valid email address is required.</p>";
}
if (empty($first)) {
$error_message .= "<p>Please provide your first name.</p>";
}
if (empty($last)) {
$error_message .= "<p>Please provide your last name.</p>";
}
AJAX:
$(function() {
if (valid != '') {
$('form #response2').removeClass().addClass('error2')
.html('' +valid).fadeIn('fast');
}
var valid = '';
$('#email').keyup(function() {
$.post('script.php', { 'Email' : $(this).val() }, function(data) {
if(data !== 'true') {
$('#email').css('border','2px solid #ff0000');
$('#email').css('background-color','#ffcece');
valid += '<p>This email has already subscribed.</p>';
}else{
$('#email').css('background-color','green');
}
});
});
});
You don't need to fetch all the emails to check whether the posted email already exist.
U can do a simple count and test the amount of records. If its 0 then the email is not in the database
Something like this should work (not tested) :
HTML
<input type="text" name="txt_email" id="txt_email" />
Jquery
$(function() {
$('#txt_email').blur(function() {
$.post('location/to/script.php', { 'txt_email' : $(this).val() }, function(data) {
if(data !== 'true') {
$('#txt_email').css('background', 'red');
}else{
$('#txt_email').css('background', 'white');
}
});
});
});
script.php
$link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));
$stmt = mysqli_prepare($link, 'SELECT count(*) FROM user WHERE email =?');
mysqli_stmt_bind_param($stmt, 's', $_POST['txt_email']);
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $count);
/* fetch value */
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
if ($count == 0) {
echo 'true';
}else{
echo 'false';
}
$(function() {
$('#txt_email').blur(function() {
$.post('location/to/script.php', { 'txt_email' : $(this).val() }, function(data) {
if(data !== 'true') {
$('#txt_email').css('background', 'red');
}else{
$('#txt_email').css('background', 'white');
}
});
});
});
Related
So I was learning ajax and followed some codes I found online but didn't know how to pass the value from the PHP.
so this is my email.php
$conn = mysqli_connect($servername, $username, $password, $db);
$email = $_POST['email'];
$query = "SELECT * FROM registration WHERE email = '$email'";
$result = mysqli_query($conn,$query);
$count = mysqli_num_rows($result);
if ($count == 0) {
$data = json_encode(0);
} else {
$data= json_encode(1);
}
mysqli_close($conn);
return data;
and this is my ajax
$.ajax({
url: "email",
type: "POST",
data: {
email: email,
},
cache: false,
success: function(data) {
alert("data: " + data); // I tried this one to check what is in data but it's not the values from the echo in PHP
if (data == 0) {
$('#message').html('available');
} else if (data == 1) {
$('#message').html('not available');
}
}
});
Your help would be much appreciated! Thank you!
[!] EDIT [!]
Sorry my problem was different. I have a template.php file for the whole HTML and where all my PHP files are included. here is the part:
if (isset($_GET["route"])) {
if ($_GET["route"] == 'home' || $_GET["route"] == 'email' ||) {
include "modules/".$_GET["route"].".php";
}
}
now the value in alert(data) is the whole thing in the template.php and the 0 or 1 at the end. what I did to solve this problem is: data.slice(-1) lol not a good practice though. so if u have other solutions, I would really appreciate it. thank you!
You have to make changes to the PHP file
$data = json_encode(0);
Then return the encoded data in your PHP file like this:
return $data;
So whenever you make a request to the file it will have a return type that can be accessed in ajax.
You don't have to encode the number. Just pass the number as a string to the echo statement.
$conn = mysqli_connect($servername, $username, $password, $db);
$email = $_POST['email'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$query = "SELECT * FROM registration WHERE email = '$email'";
$result = mysqli_query($conn,$query);
$count = mysqli_num_rows($result);
if($count==0){
echo "0";
} else{
echo "1";
}
mysqli_close($conn);
} else {
echo "1";
}
I've tried to verify if an email already exists in the database.
The same system worked perfectly if I tried to verify a username.
I'm using AJAX and PHP.
This is the file that gets the $_POST variables.
<?php
require_once 'Config.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST['email'];
$password = $_POST['password'];
if (!empty($password) and !empty($email)) {
$notEmpty = true;
include 'validate.php';
if($notEmpty == true and validateEmail($email) == true){
$password = md5($password);
$stmt = $link->prepare("INSERT INTO `Users`(`user_password`, `user_email`) VALUES (?,?)");
$stmt->bind_param("ss",$email,$password);
$stmt->execute();
}
}else{
$notEmpty == false;
}
}
?>
and this is the file that verifies the email doesn't exist on the database.
function validateEmail($user_email){
include '../Backend/Config.php';
$sql = "SELECT `user_password`, `user_email` FROM `Users` WHERE `user_email` = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("s",$user_email);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$row = $result->fetch_assoc();
if ($result->num_rows > 0) {
echo 1;
return false;
}
else{
// echo json_encode(array('status' => 'OK'));
echo 0;
return true;
}
}
Js code(ajax):
$('#form').submit(function(e) {
//Don't refresh the page
e.preventDefault();
//Collecting data for the server call
post_data = {
'email' : $('input[name=email]').val(),
'password': $('input[name=password]').val()
};
//AJAX server call to signup.php,which calls validate.php
$.ajax({
method: "POST",
url: "../Backend/signup.php",
data: post_data
})
//Server response and setting the input values to ""
.then(function( msg ) {
if(msg == 0){
console.log("Success, user data inserted. Code: " + msg);
}
//Failed
if(msg == 1){
console.log("Inserting failed. Error code:" + msg);
document.getElementById("error").innerHTML = "This email already exists.";
}
$('input[name=email]').val("");
$('input[name=password]').val("");
});
});
It inserts it anyway, what is the problem here?
If you immediately call num_rows() after executing a prepared statement, it will usually return 0 as it has no way to know how many rows are in the result set, since the result set is not saved in memory yet. You must first call store_result() to buffer the results so that the subsequent call to num_rows() will contain the correct results.
This is explained in the "User Notes" section at the bottom of the PHP documentation for num_rows().
i wanna make register form.But i cant insert datas into my db table "yeni"
and get "Error....!!".I really need to solve this problem guys pls help me.
http://i.stack.imgur.com/SoCNK.png
registration.js
$(document).ready(function() {
$("#register").click(function() {
var name = $("#name").val();
var tc = $("#tc").val();
var tel = $("#tel").val();
var password = $("#password").val();
var cpassword = $("#cpassword").val();
if (name == '' || tc == '' || tel == '' || password == '' || cpassword == '') {
alert("Please fill all fields...!!!!!!");
}
else if ((password.length) < 8) {
alert("Password should atleast 8 character in length...!!!!!!");
}
else if (!(password).match(cpassword)) {
alert("Your passwords don't match. Try again?");
}
else {
$.post("sign.php", {
name1: name,
tc1:tc,
tel1: tel,
password1: password
}, function(data) {
if (data == 'You have Successfully Registered.....') {
$("form")[0].reset();
}
alert(data);
});
}
});
});
sign.php
<?php
$connection = #mysql_connect("localhost", "root", "");
$db = mysql_select_db("babo", $connection);
$name = $_POST['name1']; // Fetching Values from URL.
$tc = $_POST['tc1'];
$tel = $_POST['tel1'];
$password = sha1($_POST['password1']);
$query = mysql_query("insert into yeni(adi, tc_no, password, tel) values ('$name', '$tc', '$password', '$tel')");
if($query) {
echo "You have Successfully Registered.....";
} else {
echo "Error....!!";
}
mysql_close ($connection);
?>
As allready suggested use mysqli_ function in favor of mysql_ functions
You should use prepered statements
To get a better starting point on whats actually wrong replace echo "Error....!!"; with echo mysqli_error($connection);
I have a form that will be validated client side before being submitted via an ajax request to the server for server-side validation. Should the validation fail server side then a postback will need to be made containing all the error messages. Is there some way I can do this?
For example:
if ((!empty($nameError) && (!empty($emailError)) {
$_POST['nameError'] = $nameError;
$_POST['emailError'] = $emailError;
// send postback with values
}
else {
echo 'No errors';
}
UPDATE ------------------------------------------------
Here is the javascript that handles the submission of the form:
$(".button").click(function() {
$(".error").hide();
var name = $(":input.name").val();
if ((name == "") || (name.length < 4)){
$("label#nameErr").show();
$(":input.name").focus();
return false;
}
var email = $(":input.email").val();
if (email == "") {
$("label#emailErr").show();
$(":input.email").focus();
return false;
}
var phone = $(":input.phone").val();
if (phone == "") {
$("label#phoneErr").show();
$(":input.phone").focus();
return false;
}
var comment = $.trim($("#comments").val());
if ((!comment) || (comment.length > 100)) {
$("label#commentErr").show();
$("#comments").focus();
alert("hello");
return false;
}
var info = 'name:' + name + '&email:' + email + '&phone:' + phone + '&comment:' + comment;
var ajaxurl = '<?php echo admin_url("admin-ajax.php"); ?>';
alert(info);
jQuery.ajax({
type:"post",
dataType:"json",
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(response) {
if (response.type == "success") {
alert("success");
}
else {
alert("fail");
}
}
});
$(":input").val('');
return false;
});
And here is the php function that the ajax posts to:
function submit_data() {
$nameErr = $emailErr = $phoneErr = $commentErr = "";
$full = explode("&", $_POST["info"]);
$fname = explode(":", $full[0]);
$name = $fname[1];
$femail = explode(":", $full[1]);
$email = $femail[1];
$fphone = explode(":", $full[2]);
$phone = $fphone[1];
$fcomment = explode(":", $full[3]);
$comment = $fcomment[1];
if ((empty($name)) || (strlen($name) < 4)){
$nameErr = "Please enter a name";
}
else if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Please ensure you have entered your name and surname";
}
if (empty($email)) {
$emailErr = "Please enter an email address";
}
else if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$emailErr = "Please ensure you have entered a valid email address";
}
if (empty($phone)) {
$phoneErr = "Please enter a phone number";
}
else if (!preg_match("/(?:\(?\+\d{2}\)?\s*)?\d+(?:[ -]*\d+)*$/",$phone)) {
$phoneErr = "Please ensure you have entered a valid phone number";
}
if ((empty($nameErr)) && (empty($emailErr)) && (empty($phoneErr)) && (empty($commentErr))) {
$conn = mysqli_connect("localhost", "John", "Change9", "plugindatadb");
mysqli_query($conn, "INSERT INTO data (Name, Email, Phone, Comment) VALUES ('$name', '$email', '$phone', '$comment')");
}
else {
// display error messages
}
die();
}
Your answer will be in two parts:
Pseudo code:
Part1: PHP
if ($error) {
$reply["status"]=false;
$reply["message"]="Fail message"; //Here you have to put your own message, maybe use a variable from the validation you just did before this line: $reply["message"] = $fail_message.
}
else {
$reply["status"]=true;
$reply["message"]="Success message"//$reply["message"] = $success_message;
}
echo json_encode($reply);//something like {"status":true, "message":"Success message"}
Part2 AJAX: modify you ajax response to this.
success: function(response) {
if (response.status == true) {
alert("success: "+response.message);
}
else {
alert("fail: " + response.message);
}
}
Use json ajax request. In case error exists show the error message. I generally put a flag for success or fail .
$message='';
if ((!empty($nameError) && (!empty($emailError)) {
$errorArray=array();
$errorArray['nameError'] = $nameError;
$errorArray['emailError'] = $emailError;
// send postback with values
}
else {
$message='No errors';
}
echo json_encode(array(
"message"=>$message,
"errors"=>$errorArray
));
I want to be able to set the following:
1) If the email already exists to return an error
2) If successful to return an error
3) if error to return error
At the moment it works, but allows you to add same email address and sends successful response but need to add one for existing email
$('form').submit(function(){
// check if passwords match; you might want to do more thorough validation
var hasError = false;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#email").val();
if(emailaddressVal == '') {
$("#email").after('<span class="error">Please enter your email address.</span>');
hasError = true;
}
else if(!emailReg.test(emailaddressVal)) {
$("#email").after('<span class="error">Enter a valid email address.</span>');
hasError = true;
} else if(hasError == false) {
// make ajax post request and store the response in "response" variable
$.post('submit.php', $(this).serialize(), function(response){
// process response here (assume JSON object has boolean property "ok"
if(response.ok==true){
// sweet, it worked!
alert('OK!');
}else{
// handle error
alert('Ooops');
}
}, 'json');
}
// stop the form from being submitted
return false;
});
And the php is:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$con = mysql_connect("localhost","root",""); //Replace with your actual MySQL DB Username and Password
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("table", $con); //Replace with your MySQL DB Name
$first_name=mysql_real_escape_string($_POST['firstname']);
$last_name=mysql_real_escape_string($_POST['lastname']);
$email=mysql_real_escape_string($_POST['email']);
$sql="INSERT INTO email_list (first_name,last_name,email) VALUES ('$first_name','$last_name','$email')";
if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); }
echo "The form data was successfully added to your database.";
mysql_close($con);
?>
Thanks!
$sql="SELECT email FROM email_list WHERE email = '$email'";
$result = mysql_query($sql, $con) or die('Error: ' . mysql_error());
if (mysql_num_rows($result) > 0)
{
// Error - Email already exists
echo "Error: The email address already exists.";
} else {
$sql="INSERT INTO email_list (first_name,last_name,email) VALUES ('$first_name','$last_name','$email')";
if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); }
echo "The form data was successfully added to your database.";
}
mysql_close($con);
I have added a check to see if the email address already exists, and output an error if it does. There are also error outputs for mysql errors.
If you need the output to be formatted in a certain way, use JSON. But the above should get you started.
Just check for the email in the db before u add.
Hope This Helps.
<?php
$first_name=mysql_real_escape_string($_POST['firstname']);
$last_name=mysql_real_escape_string($_POST['lastname']);
$email=mysql_real_escape_string($_POST['email']);
$sql = "SELECT * FROM email_list WHERE `email`='$email'";
$res= #mysql_query($sql);
if(#mysql_num_rows($res)>0)
{
echo "Email Already Exists" ;
}
else
{
$sql="INSERT INTO email_list (first_name,last_name,email) VALUES ('$first_name','$last_name','$email')";
if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); }
echo "The form data was successfully added to your database.";
}
?>
jquery
$('form').submit(function(){
// check if passwords match; you might want to do more thorough validation
var hasError = false;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#email").val();
if(emailaddressVal == '') {
$("#email").after('<span class="error">Please enter your email address.</span>');
hasError = true;
}
else if(!emailReg.test(emailaddressVal)) {
$("#email").after('<span class="error">Enter a valid email address.</span>');
hasError = true;
} else if(hasError == false) {
// make ajax post request and store the response in "response" variable
$.post('submit.php', $(this).serialize(), function(response){
// process response here (assume JSON object has boolean property "ok"
if(response.ok=='0'){
alert('required fields empty');
}else if(response.ok=='1'){
alert('email already exists');
}
else if(response.ok=='2')
{
alert('thankyou for your input');
}
}, 'json');
}
// stop the form from being submitted
return false;
});
php code
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$con = mysql_connect("localhost","root",""); //Replace with your actual MySQL DB Username and Password
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("table", $con); //Replace with your MySQL DB Name
$first_name=mysql_real_escape_string($_POST['firstname']);
$last_name=mysql_real_escape_string($_POST['lastname']);
$email=mysql_real_escape_string($_POST['email']);
if(empty($first_name) || empty($last_name) || empty($email) ) {
echo json_encode( array('ok'=> '0' ) );
exit();
}
$sql="Select * from email_list where email='".$email."' ";
$sqll=mysql_query($sql) or die($sql."<br/><br/>".mysql_error());
$data=mysql_fetch_array($sqll);
if($data['email']) {
echo json_encode( array('ok'=> '1' ) );
exit();
}
$sql="INSERT INTO email_list (first_name,last_name,email) VALUES ('$first_name','$last_name','$email')";
mysql_query($sql) or die($sql."<br/><br/>".mysql_error());
$value = mysql_insert_id() > 0;
if($value)
echo json_encode( array('ok'=> '2' ) );
mysql_close($con);
exit();
?>
just add following line in end of you php file
$value = mysql_insert_id() > 0;
echo json_encode( array('ok'=> $value ) );