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
));
Related
I need some help. I try to do registration and because I need to refresh only the registration part on page, I must use ajax. And here is the problem. When I submit the form, ajax loads different file, where is registration part in php. In php I have some variables, which I use to change color of particular inputs, if there was an error. But, because the php is in other file, I cant access the variables from file, where the ajax is and change the colors. And if I try place script, which changes the colors, in the file, where php is, it dont execute, because I somewhere stop php with for example "return false".
Do you know please, what I can do with this? Thank you very much and sorry for my bad english.
This is the ajax part
<script>
$(document).ready(function(){
$("#registerUser").submit(function(event){
event.preventDefault();
var typedEmail = $("#registerEmail").val(),
typedPassword = $("#registerPassword").val(),
typedRepeatedPassword = $("#registerRepeatedPassword").val();
submittedForm = $("#registerSubmit").val();
$("#registerMessage").load("accountRegistration.php", {
email: typedEmail,
password: typedPassword,
repeatedPassword: typedRepeatedPassword,
submit: submittedForm
});
});
});
</script>
This is the php file
if(isset($_POST["submit"])){
require_once "autoload.php";
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$password = $_POST["password"];
$repeatedPassword = $_POST["repeatedPassword"];
$emailError = false;
$passwordError = false;
$repeatedPasswordError = false;
if(empty($email)){
$emailError = true;
}
if(empty($password)){
$passwordError = true;
}
if(empty($repeatedPassword)){
$repeatedPasswordError = true;
}
if(strlen($password) < 8){
$passwordError = true;
}
if($password != $repeatedPassword){
$repeatedPasswordError = true;
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailError = true;
}
if($emailError == true || $passwordError == true || $repeatedPasswordError == true){
echo("<span class='errorMessage'>Vyplňte správně všechna políčka!</span>");
return false;
}
$registration = new DatabaseOperations;
if($registration->selectOneRow("users", "userID", "email", $email, PDO::PARAM_STR)){
echo("<span class='errorMessage'>Tento email už někdo používá.</span>");
return false;
}
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
if($registration->insertOneRow("users", array("email", "password"), array($email, $passwordHash))){
echo("<span class='successMessage'>Registrace proběhla úspěšně.</span>");
return true;
} else{
echo("<span class='errorMessage'>Něco se pokazilo. Zkuste to prosím znovu.</span>");
return false;
}
} else{
echo ("Stala se chyba. Zkuste to prosím znovu.");
}
<script>
$("#registerEmail, #registerPassword, #registerRepeatedPassword").removeClass("inputError");
var emailError = "<?php echo(isset($emailError) ? $emailError : '') ?>";
var passwordError = "<?php echo(isset($registerPassword) ? $registerPassword : '') ?>";
var repeatedPasswordError = "<?php echo(isset($registerRepeatedPassword) ? $registerRepeatedPassword : '') ?>";
console.log(emailError);
console.log(passwordError);
console.log(repeatedPasswordError);
if(emailError == true){
$("#registerEmail").addClass("inputError");
}
if(passwordError == true){
$("#registerPassword").addClass("inputError");
}
if(repeatedPasswordError == true){
$("#registerRepeatedPassword").addClass("inputError");
}
if(passwordError == true || repeatedPasswordError == true){
$("#registerPassword").val("");
$("#registerRepeatedPassword").val("");
}
</script>
And here is the HTML
<div class="signUp">
<h1>registrace</h1>
<form method='POST' name="register" id="registerUser">
<p id="registerMessage"></p>
<input type='email' id='registerEmail' name='email' placeholder='Váš email'>
<input type='password' id='registerPassword' name='password' placeholder='Vaše heslo (min. 8 znaků)'>
<input type='password' id='registerRepeatedPassword' name='repeatedPassword' placeholder='Ověření hesla'>
<input type='submit' id='registerSubmit' name='' value='REGISTROVAT'>
</form>
<p>MÁM ÚČET A CHCI SE PŘIHLÁSIT<p>
</div>
Ajax with html does the same. It returns only what is in "echo"
$.ajax({
method: "POST",
url: "accountRegistration.php",
data: {
email: typedEmail,
password: typedPassword,
repeatedPassword: typedRepeatedPassword,
submit: submittedForm
},
dataType: "html",
success: function(errors){
console.log("Errors: " + errors);
}
})
Finally, I did it like this..
<script>
$(document).ready(function(){
$("#registerUser").submit(function(event){
event.preventDefault();
var typedEmail = $("#registerEmail").val(),
typedPassword = $("#registerPassword").val(),
typedRepeatedPassword = $("#registerRepeatedPassword").val();
submittedForm = $("#registerSubmit").val();
$.ajax({
method: "POST",
url: "accountRegistration.php",
data: {
email: typedEmail,
password: typedPassword,
repeatedPassword: typedRepeatedPassword,
submit: submittedForm
},
dataType: "json",
success: function(results){
$("#registerMessage").html(results["message"]);
$("#registerEmail, #registerPassword, #registerRepeatedPassword").removeClass("inputError");
var emailError = results["emailError"];
var passwordError = results["passwordError"];
var repeatedPasswordError = results["repeatedPasswordError"];
if(emailError == true){
$("#registerEmail").addClass("inputError");
}
if(passwordError == true){
$("#registerPassword").addClass("inputError");
}
if(repeatedPasswordError == true){
$("#registerRepeatedPassword").addClass("inputError");
}
if(passwordError == true || repeatedPasswordError == true){
$("#registerPassword").val("");
$("#registerRepeatedPassword").val("");
}
}
});
});
});
</script>
<?php
if(isset($_POST["submit"])){
registerUser();
}
function registerUser(){
require_once "autoload.php";
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$password = $_POST["password"];
$repeatedPassword = $_POST["repeatedPassword"];
$emailError = false;
$passwordError = false;
$repeatedPasswordError = false;
if(empty($email)){
$emailError = true;
}
if(empty($password)){
$passwordError = true;
}
if(empty($repeatedPassword)){
$repeatedPasswordError = true;
}
if(strlen($password) < 8){
$passwordError = true;
}
if($password != $repeatedPassword){
$repeatedPasswordError = true;
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailError = true;
}
if($emailError == true || $passwordError == true || $repeatedPasswordError == true){
echo (json_encode(
array("emailError" => $emailError,
"passwordError" => $passwordError,
"repeatedPasswordError" => $repeatedPasswordError,
"message" => "<span class='errorMessage'>Vyplňte správně všechna políčka!</span>"
)));
return false;
}
$registration = new DatabaseOperations;
if($registration->selectOneRow("users", "userID", "email", $email, PDO::PARAM_STR)){
echo(json_encode(array("message" => "<span class='errorMessage'>Tento email už někdo používá.</span>")));
return false;
}
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
if($registration->insertOneRow("users", array("email", "password"), array($email, $passwordHash))){
echo(json_encode(array("message" => "<span class='successMessage'>Registrace proběhla úspěšně.</span>")));
return true;
} else{
echo(json_encode(array("message" => "<span class='errorMessage'>Něco se pokazilo. Zkuste to prosím znovu.</span>")));
return false;
}
}
?>
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;
}
}
});
});
Guys I'm trying to make a Log in form by using Ajax and PHP. Every-time when I submit the form I'm getting the right response, but the problem here is that I have an "IF CONDITION" in my Javascript file did not execute while I get a "success" response. I don't know why. This is my code, please anybody help.
Ajax File
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
Javascript File handling Log in - The problem is here in this file
function signin(){
var logstat = _("logstat");
var loge = _("SignInEmail").value;
var logp = _("SignInPasswordActive").value;
if(loge == "" || loge == "Email address" || logp == ""){
logstat.innerHTML = "Fill out all of the form data.";
} else {
_("loginbtn").style.display = "none";
logstat.innerHTML = 'please wait ...';
var ax = ajaxObj("POST", "signin.php");
ax.onreadystatechange = function() {
if(ajaxReturn(ax) == true) {
if(ax.responseText != "success"){
logstat.innerHTML = ax.responseText;
_("loginbtn").style.display = "block";
} else {
//Here is the problem I get success in Ajax Response, but this condition did not run
logstat.innerHTML = "login success";
_("loginbtn").style.display = "block";
}
}
}
ax.send("le="+loge+"&lp="+logp);
}
}
PHP File
<?php
if(isset($_POST['le']) && isset($_POST['lp'])){
$p = $_POST['lp'];
require_once('includes/database.php');
include_once('randStrGen.php');
$e = $_POST['le'];
$p_hash = md5($p);
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
if($e == "" || $e == "Email address" || $p == ""){
echo "Fill out all of the form data.";
exit();
} else {
$sql = "SELECT id, email, password FROM users WHERE email='$e' AND activated='1' LIMIT 1";
$query = mysqli_query($db->connection, $sql);
$numrows = mysqli_num_rows($query);
if($numrows == 0){
echo "This account is not exist";
exit();
}else{
$row = mysqli_fetch_array($query);
$db_id = $row['id'];
$db_em = mysqli_real_escape_string($db->connection, $row['email']);
$db_ps = substr($row['password'],10,-10);
if($p_hash != $db_ps){
echo "Email or Password combination failed";
exit();
}else{
//This is the successful Log in condition
echo "success";
exit();
}
}
exit();
}
exit();
}
?>
Try swaping the condition so checking if it's equals (even ===) to 'success' and do the rest in the else clause
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)){
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;
}