After getting help from #juhana (thank you again) I ended up with theese codes to validate email input:
validate email:
function validateEmail(){
var a = $("#email").val();
$.ajax({
type: "POST",
url: "check_email.php",
data: "email="+a,
success: function(rsp){
//if it's valid email
if(rsp == "ok"){
email.removeClass("error");
emailInfo.text("");
emailInfo.removeClass("error");
return true;
}
else
//if it exists
if(rsp == "exists" ){
email.addClass("error");
emailInfo.text("E-mail already in use");
emailInfo.addClass("error");
return false;
}
else
//if it's NOT valid
if(rsp == "invalid"){
email.addClass("error");
emailInfo.text("Please type a valid E-mail");
emailInfo.addClass("error");
return false;
}
}
});
}
check_email.php
<?php
require_once('db_conn.php');
require_once('is_email.php');
$email = mysql_real_escape_string($_POST['email']);
if (is_email($_POST['email'])){
echo 'ok';
$checkemail = mysql_query("SELECT E_mail FROM orders WHERE E_mail='$email'");
$email_exist = mysql_num_rows($checkemail);
if($email_exist>0){
echo 'exists';
}
}else{
echo 'invalid';
}
?>
Now 2 out of 3 are working the "ok" and the "invalid" ones... the "exists" doesn't.
What's wrong here???
Thank you
by reading your code above, if the email was valid, but existed in the database, it would return "okexists" which would cause your javascript to fail. You'd need to change it to something like this:
<?php
$email = mysql_real_escape_string($_POST['email']);
$checkemail = mysql_query("SELECT E_mail FROM orders WHERE E_mail='$email'");
$email_exist = mysql_num_rows($checkemail);
if (is_email($_POST['email'])){
if($email_exist) {
echo "exists";
}
else {
echo "ok";
}
} else {
echo "invalid";
}
?>
This allows it to return only the token "exists" when its a valid, but existing email. And only the token "ok" when its a valid, not previously existing email. And of course it returns invalid if it doesn't pass the is_email() test.
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
var email= $("#emailid").val();
if(!filter.test(email)){
alert('Plz enter valid email id');
return false;
}
Related
I have a problem with this my script.
$("#login").click(function(event) {
event.preventDefault();
var email = $("#email").val();
var pass = $("#password").val();
$.ajax({
url : "login.php",
method: "POST",
data: {userLogin:1, userEmail:email, userPassword:pass},
success : function(data){
if(data == "1"){
alert(data);
}
}
})
I want it to alert a value that I am getting from an echo in another php file
<?php
if(isset($_POST['userLogin'])){
$email = mysqli_real_escape_string($con, $_POST['userEmail']);
$password = md5($_POST['userPassword']);
$sql_login = "SELECT * from database where email = '$email' AND password = '$password'";
$query_login = mysqli_query($con, $sql_login);
$count_login = mysqli_num_rows($query_login);
if($count_login == 1){
$row_login = mysqli_fetch_assoc($query_login);
$_SESSION['uid'] = $row_login['user_id'];
$_SESSION['name'] = $row_login['first_name'];
echo "1";
}
}
?>
If I didn't put the alert(data) in an if condition, it displays the value I echo, but I need the condition to enable the right user logged in.
What can IF can also ELSE.
In your ajax add the else conditions to see if it helps uncover the issue:
if (data == "1") {
alert('youre in');
} else {
alert('try again');
}
And in your php, also account for the else condition (and do strict checking on that count of rows with ===):
if ($count_login === 1) {
// code ...
echo '1';
} else {
echo 'Sorry, the login is incorrect';
}
It works fine for me, if i always echo "1", the alert(data) show 1, in an if condition and out, pls, echo something else if isset($_POST['userLogin']) or $count_login == 1 are false, or put an
error : function(data) {
$('body').append("<div>"+data.responseText+"</div>")
}
in your ajax, to debug the prob. Because in your .php file, when you echo nothing, it returns a data in error, not in success, maybe that's your prob.
After send my form data to php file its return if any error found. But its also return success before ajax redirect page. I want display error message only and if success, redirect another page.
ajax:
$("#msform").submit(function(){
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
dataType : 'json',
success: function(data){
if ( ! data.success) {
$(".help-block").fadeIn().html(data.error);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});
php:
include_once ("db.php");
global $dbh;
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
$error ="* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
$error ="* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
$error ="* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}
$data = array();
$data['error'] = $error;
$data['success'] = $success;
if (!empty($data)) {
echo json_encode($data);
}
Solved the problem, in this way:
Ajax:
$("#msform").submit(function(){
// collect input name
ver name = var catag=$('#name').val();
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
success: function(data){
if ( data != 'success') {
$(".help-block").fadeIn().html(data);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + name;
}
}
});
});
php:
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
echo "* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
echo "* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
echo "* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
echo 'success';
}
EDIT
Set your variables $success and $error
$success = "";
$error= "";
If you doesn't init them, you cannot use them and the .=operator is for concatenation not for set.
Then you should encode the response in php in JSON.
Something like
$response = json_encode(
array(
'success'=> true,
'route' => "mypage/info?user=$_SESSION['username']"
)
);
And return this, then access your response like you already do :
var success = response.success;
UPDATE
change this code to add an else statement :
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}else{
$success = 'error';
}
and this line :
else {
return 1;
}
to :
else {
$error = 'none';
}
and in your javascript :
$("#msform").submit(function(){
$.ajax({
type :"post",
url :"pagesubmit.php",
data : $("#msform").serialize(),
dataType : 'json',
success : function(data){
if(data.success == 'error') {
$(".help-block").fadeIn().html(data.error);
}else{
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});
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 have writtin this code to check the email availability.
var email = $('#email_reg').val();
if(email && email.length > 0)
{
if(!isValidEmailAddress(email))
{
isValid = false;
$('#msg_email').html('Email is invalid').show();
}
else
{jQuery.ajax({
type: 'POST',
url: 'check_username.php',
data: 'email='+ email ,
cache: false,
success: function(response){
if(response == 1){
$('#msg_email').html('Email already Exists').show();
isValid=false;
}
else {
$('#msg_email').html('').hide();
}
}
});
}
}
else
{
isValid = false;
$('#msg_email').html('Please enter email').show();
}
The php Code is
<?php
require_once('Connections/connection.php');
$username= mysql_real_escape_string($_REQUEST["email"]);
if (!$con)
{
echo 0;
}
else {
mysql_select_db($database_connection, $connection);
$result = mysql_query("SELECT * FROM vendor_logiin WHERE username='" . $username . "'");
$num = mysql_num_rows($result);
echo $num; //it will always return 1 or 0 since we do not allow multiple users with the same user name.
}
mysql_close();
?>
Now all the others work well like when left it empty and give a wrong email format.But the problem is when i give an email Id that already exists. It didnot give error.
I have no idea what is going wrong.
Since you didn't specify dataType the response is probably treated as text or html and in that case it might be wise to do the comparison as a string:
if (response == "1") {...}
instead of a number. Or use parseInt(response, 10) == 1 if you compare it as a number.
I have a registration form which when filled and "Register" button pressed is being checked by js, to find empty fields and to check availability of username, or if email or mobile num was already used by sending info through ajax to php and receiving answer. But my js won't work all the way through. This is my js script:
$("#reg_button").click(function(){
user = $("#usr").val();
pass = $("#psw").val();
fname = $("#first_name").val();
sname = $("#second_name").val();
dateb = $("#date_birth").val();
email = $("#email").val();
mobnum = $("#mob_num").val();
if(user == ""){
alert("First name must be filled out");
$('#usr').focus();
return false;
}else if(pass == ""){
alert("Password must be filled out");
$('#psw').focus();
return false;
}else if(fname == ""){
alert("First name must be filled out");
$('#first_name').focus();
return false;
}else if(sname == ""){
alert("Second name must be filled out");
$('#second_name').focus();
return false;
}else if(dateb == ""){
alert("Date of birth must be filled out");
$('#date_birth').focus();
return false;
}else if(email == ""){
alert("Email must be filled out");
$('#email').focus();
return false;
}else if(mobnum == ""){
alert("Mobile number must be filled out");
$('#mob_num').focus();
return false;
}else{
ajaxCheck();
}
function ajaxCheck(){
$.ajax({
type: "POST",
url: "http://imes.*********.com/php/check_info_reg.php",
data: "usr="+user+"&email="+email+"&mob_num="+mobnum,
dataType: "json",
success: function(json){
if(json.success){
var user_conf = json.data.usr;
var email_conf = json.data.email;
var mob_conf = json.data.mob;
if(user_conf == "taken"){
alert("Username already taken. Choose another one.");
$('#usr').focus();
return false;
}
if(email_conf == "taken"){
alert("Email already registered. If you lost your password, retrieve it on login page.");
$('#email').focus();
return false;
}
if(mob_conf == "taken"){
alert("Mobile number already registered. If you lost your password, retrieve it on login page.");
$('#mob_num').focus();
return false;
}
}else{
//Here could go another ajax, for actualy sending the
//info into the php script which sends it to database.
}
},
beforeSend: function() { $.mobile.showPageLoadingMsg(); }, //Show spinner
complete: function() { $.mobile.hidePageLoadingMsg() }, //Hide spinner
});
return false;
}
});
And my php:
<?php
$username = mysql_real_escape_string($_POST['usr']);
$email = mysql_real_escape_string($_POST['email']);
$mob_num = mysql_real_escape_string($_POST['mob_num']);
include('mysql_connection.php');
mysql_select_db("jzperson_imesUsers", $con);
$sql1 = mysql_query("SELECT * FROM registered_user WHERE username='$username'");
$sql2 = mysql_query("SELECT * FROM registered_user WHERE email='$email'");
$sql3 = mysql_query("SELECT * FROM registered_user WHERE mobile_num='$mob_num'");
$res1 = mysql_num_rows($sql1);
$res2 = mysql_num_rows($sql2);
$res3 = mysql_num_rows($sql3);
if(isset($username) && !empty($username){
if($res1 >= 1){
//JSON message: Username already taken. Choose different.
echo json_encode(array('success'=>true, 'usr'=>"taken"));
}
}
elseif(isset($email) && !empty($email)){
if($res2 >= 1){
//JSON message: Email already registered. Retrieve on "login"(login => link).
echo json_encode(array('success'=>true, 'email'=>"taken"));;
}
}
elseif(isset($mob_num) && !empty($mob_num)){
if($res3 >= 1){
//JSON message: Mobile number already registered. Retrieve on "login"(login => link).
echo json_encode(array('success'=>true, 'mob'=>"taken"));
}
}
else{
echo json_encode(array('success'=>false));
}
?>
You are missing a parenthesis in your php file:
if(isset($username) && !empty($username){
Should be
if(isset($username) && !empty($username)){