i am trying to validate a form along with a php script.
validations are perfectly working, but if i submit correct details the button is not clicked.
when i dont enter any details the msg of required field is displayed.
when i enter wrong details the alert message is displayed.
but when i enter correct details the login button is not clicked.
In alls() function i tried to return true but then the problem that it gets refreshed after displaying the required field message for a second.
HTML code:
<form id="frm_login" method="post" name="frm_login" onSubmit="return alls()">
UserName: <input type="text" name="txt_usrnm" /><label id="i"></label>
<br/><br/>
Password: <input type="password" name="pswd" /><label id="i1"></label>
<br/><br/>
<input type="submit" name="submit" value="Login" style:"width=10px"/>
Forgot Password ?
<br/><br/>
<font size="+1">Register Here</font>
</form>
Javascript:
<script type="text/javascript">
function req()
{
if (document.frm_login.txt_usrnm.value=="")
{
document.getElementById('i').innerHTML="*This field is required";
document.getElementById('i').style.color="red";
document.getElementById('i').style.fontSize="12px";
}
if (document.frm_login.pswd.value=="")
{
document.getElementById('i1').innerHTML="*This field is required";
document.getElementById('i1').style.color="red";
document.getElementById('i1').style.fontSize="12px";
}
return false;
}
function validateUname()
{
submitFlag = true;
var len=document.frm_login.txt_usrnm.value.length;
if((len>0) && (len<6)){
submitFlag=false;
document.getElementById('i2').innerHTML="*Enter atleast 6 characters";
document.getElementById('i2').style.color="red";
document.getElementById('i2').style.fontSize="12px";
}
return submitFlag;
}
function alls()
{
req();
validateUname();
//CheckPassword(this);
//num();
//confirm_pswd();
//namevalid();
//ValidateEmail(this);
return false;
}
</script>
PHP code:
<?php
if(isset($_POST['submit']))
{
$usrnm1=$_POST['txt_usrnm'];
$pswd1=$_POST['pswd'];
$user_name = "root";
$password = "";
$database = "show_your_talent";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$res="select * from username where UserName='$usrnm1' and Password='$pswd1'";
$result2 = mysql_query($res,$db_handle);
$count=mysql_num_rows($result2);
if($count==1)
{
$_SESSION['user'] =$usrnm1;
//echo $_SESSION['user'];
header("Location: category.php");
}
else
{
//$_SESSION['user']="false";
echo "<script type='text/javascript'> alert('Incorrect UserName/Password.')</script>";
//header('Location: index.php');
}
mysql_close($db_handle);
}
?>
You submit function, alls(), always returns false which means form will not submit. Try this:
function req() {
var submitFlag = true;
if (document.frm_login.txt_usrnm.value == "") {
submitFlag = false;
document.getElementById('i').innerHTML = "*This field is required";
document.getElementById('i').style.color = "red";
document.getElementById('i').style.fontSize = "12px";
}
if (document.frm_login.pswd.value == "") {
submitFlag = false;
document.getElementById('i1').innerHTML = "*This field is required";
document.getElementById('i1').style.color = "red";
document.getElementById('i1').style.fontSize = "12px";
}
return submitFlag;
}
function validateUname() {
submitFlag = true;
var len = document.frm_login.txt_usrnm.value.length;
if ((len > 0) && (len < 6)) {
submitFlag = false;
document.getElementById('i').innerHTML = "*Enter atleast 6 characters";
document.getElementById('i').style.color = "red";
document.getElementById('i').style.fontSize = "12px";
}
return submitFlag;
}
function alls() {
var valid = true;
valid *= req();
valid *= validateUname();
//CheckPassword(this);
//num();
//confirm_pswd();
//namevalid();
//ValidateEmail(this);
return valid ? true : false;
}
which will prevent form from submitting when req() or validateUname() returns false.
alls() always returns false. Hence you form is never submitted.
When onsubmit callback returns false, the submission to the server is stopped.
Related
My ajax code:
$('#name').keyup(function() {
var usercheck = $(this).val();
$('#nameAvailability').html('<img src="../SPR/assets/img/loading.gif" width="300" />'); //this part is working
$.post("../SPR/backend/username_availability_check.php", {user_name: usercheck} ,
function(data)
{
if (data.status == true)
{
$('#nameAvailability').parent('div').removeClass('has-error').addClass('has-success');
} else {
$('#nameAvailability').parent('div').removeClass('has-success').addClass('has-error');
}
$('#nameAvailability').html(data.msg); // not working
} ,'json');
});
My php code:
<?php
require("connection.php");
if(isset($_POST['user_name']) && $_POST['user_name'] != '')
{
$response = array();
$username = mysqli_real_escape_string($conn,$_POST['user_name']);
echo $username;
$sql = "select username from users where users.username='".$username."'";
$res = mysqli_query($conn, $sql);
$count = mysqli_num_rows($res);
if($count > 0)
{
$response['status'] = false;
$response['msg'] = 'Username already exists.';
}
else if(strlen($username) < 6 || strlen($username) > 15){
$response['status'] = false;
$response['msg'] = 'Username must be 6 to 15 characters';
}
else if (!preg_match("/^[a-zA-Z1-9]+$/", $username))
{
$response['status'] = false;
$response['msg'] = 'Use alphanumeric characters only.';
}
else
{
$response['status'] = true;
$response['msg'] = 'Username is available.';
}
echo json_encode($response);
echo $response;
}
?>
I have used session_start() in my index.php where user inputs his username in the input field with id 'name'
I have checked the given php code by running it individually by passing a custom username from the database and it works fine. So probably there's something wrong with the ajax code.
It is impossible to tell what your clientside code does based on what is posted here.
But in general, for debugging and to check if your serverside code works, do this:
Make a simple form, that POSTS to your PHP script.
<form action="whateveryourphpcodeisnamed.php" METHOD="POST">
<INPUT TYPE="TEXT" NAME="user_name">
<INPUT TYPE="SUBMIT" VALUE="TEST THE USERNAME">
</FORM>
And see what it says back to you.
Be sure to activate error_reporting during development.
I cannot send this Json To another PHP page...Do i have to Stringify it or what???My aim is to Inert Email into database and get validation message back...If it is already in database i should get the validation message back and do not insert it into database if it is in there already.
The page where my form is located is this one...
Index.php
<script type="text/javascript">
$(document).ready(function(){
$("#emailForm").submit(function(event){
event.preventDefault();
var form = $(this);
var emailValue = form.find("#email").val();
var url = form.attr("action");
var posting = $.post( url, { email : emailValue });
posting.done(function( data ){
$("#email_approved_message").empty();
$("#email_approved_message").html(data);
});
});
});
</script>
<form id="emailForm" method="POST" action="petme.php">
<input type="email" id="email" name="email" placeholder="Email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-zA-Z]{2,3}$" required>
<br>
<span class="error_form" id="email_error_message"></span>
<span class="approved_form" id="email_approved_message"></span>
<br>
<input type="submit" id="submit" name="submit" value="Pošalji">
</form>
This is my petme.php page where i should validate email input value.I cannot get back validation message from function ServerValidationMessage,i need to get that string back and show it in span with id=email_approved_message!!!
<?php
header("Content-Type: application/json; charset=UTF-8");
include_once("../app/modules_bl/emailBL.class.php");
$email = isset($_POST["email"]) ? $_POST["email"] : "";
$EmailBL = new EmailBL();
$ObjectsFromBM = $EmailBL->GetEmail();
foreach ($ObjectsFromBM as $ObjectFromBM)
{
$arrayofEmails[]= $ObjectFromBM->GetEMAIL_BM();
}
$returnedMsg = ServerValidationMessage($email);
$validatedEmail = array("validationMessage" => "$returnedMsg");
print(json_encode($validatedEmail));
function ServerValidationMessage($email)
{
if(is_array($email) || is_numeric($email) || is_bool($email) || is_float($email) || is_file($email) || is_dir($email) || is_int($email))
{
return $emailfalseMsg;
}
else
{
$email= trim(strtolower($email));
$emailtrueMsg = "Uspešno ste uneli email i prijavili se na naš newslettter!";
$emailfalseMsg = "Morate uneti ispravnu email adresu!";
$emptyemailfieldMsg = "Unesite email!";
$emailduplicatedMsg = "Vi ste se već prijavili na naš newletter sa ovom email adresom!";
if(filter_var($email, FILTER_VALIDATE_EMAIL) !== false && $email != "")
{
$EmailBL = new EmailBL();
$ObjectsFromBM = $EmailBL->GetEmail();
foreach ($ObjectsFromBM as $ObjectFromBM)
{
$arrayofEmails[]= $ObjectFromBM->GetEMAIL_BM();
}
if(in_array($email, $arrayofEmails) && isset($arrayofEmails))
{
return $emailduplicatedMsg;
}
else
{
$EmailBL->InsertEmail();
return $emailtrueMsg;
}
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false && $email != "")
{
$pattern = '/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}#)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*#(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD';
return (preg_match($pattern, $email) === 1) ? $emailtrueMsg : $emailfalseMsg;
}
if($email == "")
{
return $emptyemailfieldMsg;
}
}
}
?>
At first password change was working but when i added hash and salt now passwords can not be changed by user
(keep getting: Current password is not correct)
if (count($_POST)>0) {
$result = mysql_query("SELECT * from users WHERE username='"
.$_SESSION["user"] . "'");
$row=mysql_fetch_array($result);
if($_POST["currentPassword"] == $row["password"]) {
mysql_query("UPDATE users set password='" . $_POST["newPassword"] . "'
WHERE username='" . $_SESSION["user"] . "'");
$message = "Password Changed";
} else $message = "Current Password is not correct";
}
Here is the register page:
session_start();
if($_SESSION['user']!=''){header("Location:welcome.php");}
$dbh=new PDO('mysql:dbname=doctor;localhost', 'root', '');
$email=$_POST['mail'];
$password=$_POST['pass'];
if(isset($_POST) && $email!='' && $password!=''){
$sql=$dbh->prepare("SELECT id,password,psalt FROM users WHERE
username=?");
$sql->execute(array($email));
while($r=$sql->fetch()){
$p=$r['password'];
$p_salt=$r['psalt'];
$id=$r['id'];
}
$site_salt="mysalt";/
$salted_hash = hash('sha256',$password.$site_salt.$p_salt);
if($p==$salted_hash){
$_SESSION['user']=$id;
header("Location:welcome.php");
}else{
echo "Username OR Password is Incorrect...";
}
}
Here is the JavaScript:
function validatePassword() {
var currentPassword,newPassword,confirmPassword,output = true;
currentPassword = document.frmChange.currentPassword;
newPassword = document.frmChange.newPassword;
confirmPassword = document.frmChange.confirmPassword;
if(!currentPassword.value) {
currentPassword.focus();
document.getElementById("currentPassword").innerHTML = "required";
output = false;
}
else if(!newPassword.value) {
newPassword.focus();
document.getElementById("newPassword").innerHTML = "required";
output = false;
}
else if(!confirmPassword.value) {
confirmPassword.focus();
document.getElementById("confirmPassword").innerHTML = "required";
output = false;
}
if(newPassword.value != confirmPassword.value) {
newPassword.value="";
confirmPassword.value="";
newPassword.focus();
document.getElementById("confirmPassword").innerHTML = "not same";
output = false;
}
return output;
}
Assuming there is a user with that username, there's a problem with your first script:
if($_POST["currentPassword"] == $row["password"])
This compares the raw password from the form ($_POST["currentPassword"]) with a hashed password from the result ($_POST["currentPassword"]). What you need to do is compare the hash forms of both passwords. You need to hash the one from the form with the same hash function you used before storing the user's password.
I'm working on a simple form and validating it through javascript php and AJAX.
Here is the html form snippet just for the password:
Password:
<input type="password" name="password" id="password"
onblur="checkUserInputs('password')"
<span id="password-warning"></span>
<input type="button" name="signup" id="signup"
value ="Sign Up" class="button signup-button"
onclick="signUp()">
<span id="status-field"></span>
Here is the checkUserInput() snippet that fires up on onblur event:
function checkUserInputs(inputId){
var inputField = document.getElementById("password");
var varName = "checkPassword"; /variable name to send to php
var functionToCall = "check_password";//php calls corresponding function based on this string value
if(inputField.value != ""){
//creates ajax object
var ajax = createAjax("POST", "core/proccess_signup.php");
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.onreadystatechange = function(){
if(ajaxReady(ajax)){
//display error massage
warningDiv.innerHTML = ajax.responseText;
}
}
//now data to php scripts for validation ajax.send(varName+"="+inputField.value+"&functionToCall="+functionToCall);
}
}
SignUp() fires up when clicking signup button:
function signUp(){
var password = document.getElementById("password").value;
//rest of the code to get other inputs values...
//status div to display errors
var statusDiv = document.getElementById("status-field");
if(password !="")//I have other checks too, just shortened the code here {
//setup ajax
var ajax = createAjax("POST", "core/proccess_signup.php");
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.onreadystatechange = function(){
if(ajaxReady(ajax)){
if(ajax.responseText == "success"){ //registartion was successful
document.getElementById("signup-form").innerHTML =
"Registration was successful";
}else{
statusDiv.innerHTML = "Please check the error massages";
}
}
}
//send all of the data to php scripts for validation ajax.send("functionToCall=signup&username="+username+"&password="+password);
}else{
statusDiv.innerHTML = "Please fill out all of the form data";
return;
}
}
Validate the data in php:
$functionToCall = $_REQUEST['functionToCall'];
if($functionToCall == "check_password"){
check_password();
}else if($functionToCall == "signup"){
check_password();
signup();
}
function check_password(){
if(isset($_POST['checkPassword'])) {
$pass = $_POST['checkPassword'];
if(strlen($pass)< 6 || strlen($pass) > 20){
echo 'password must be min 6 and max 20 characters';
exit();
}
if(preg_match("/\s/", $pass)) {
echo 'Password can not be empty or contain spaces';
exit();
}
echo '';
return true; //if all is good return true so i can check if password validation passed successfully
}
}
Here is the signup function
function signup(){
if(isset($_POST['username'])) {
//here I check just the password
if(check_password()){
echo 'success';
exit();
}
}
well if password entered correctly with no white spaces and length between 6-20, check_password() should be set to true and echo 'success' should be executed, but it DOESN'T. this drives me nuts.
Why echo 'success' never gets executed? Take a look at the code and tell me what I'm doing wrong.
The main problem that I can see is that the check_password function looks for isset($_POST['checkPassword']).
That function is called again by the second ajax request, which doesn't post that value. It posts password.
I would strongly recommend using xdebug if you aren't already. It really helps when stepping through this kind of thing. xdebug
Here's a quick fix to pop in check_password function.
if(isset($_POST['checkPassword']) || isset($_POST['password']) ) {
$pass = (isset($_POST['checkPassword']) ) ? $_POST['checkPassword'] : $_POST['password'];
Also you call the check_password function twice. It might be better to store the return value of that as a variable then pass as a parameter.
First call
if($functionToCall == "signup"){
check_password();
signup();
Second Call (in signup function)
if(check_password()){
echo 'success';
exit();
}
I had to mess with the js a little to make that work , but I'm guessing that was just some mishaps in abbreviating the code for simplicity.
Changes:
Ajax request wasn't working, so edited.
username var wasn't set, so hardcoded to foobar.
Here is the full html page
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>TEST</title>
<script>
function checkUserInputs(inputId){
var inputField = document.getElementById("password").value;
var varName = "checkPassword";
var functionToCall = "check_password";
var warningDiv = document.getElementById("password-warning");
if( inputField != ""){
var params = varName + "=" + inputField + "&functionToCall=" + functionToCall;
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
warningDiv.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","core/proccess_signup.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send( params );
}
}
function signUp(){
var password = document.getElementById("password").value;
//rest of the code to get other inputs values...
//status div to display errors
var statusDiv = document.getElementById("status-field");
if(password !=""){ //I have other checks too, just shortened the code here
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if( xmlhttp.responseText == "success"){ // registration was successful
statusDiv.innerHTML = "Registration was successful";
}
else{
statusDiv.innerHTML = "Please check the error messages";
}
}
}
xmlhttp.open("POST","core/proccess_signup.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("functionToCall=signup&username=foobar&password="+password);
}
else
{
statusDiv.innerHTML = "Please fill out all of the form data";
return;
}
}
</script>
</head>
<body>
<input type="password" name="password" id="password" onblur="checkUserInputs('password')" />
<span id="password-warning"></span>
<input type="button" name="signup" id="signup" value ="Sign Up" class="button signup-button" onclick="signUp()" />
<span id="status-field"></span>
</body>
</html>
Here is the php (I haven't taken out the duplicate function call)
<?php
$functionToCall = $_REQUEST['functionToCall'];
if($functionToCall == "check_password"){
check_password();
}else if($functionToCall == "signup"){
check_password();
signup();
}
function check_password(){
if(isset($_POST['checkPassword']) || isset($_POST['password']) ) {
$pass = (isset($_POST['checkPassword']) ) ? $_POST['checkPassword'] : $_POST['password'];
if(strlen($pass)< 6 || strlen($pass) > 20){
echo 'password must be min 6 and max 20 characters';
exit();
}
if(preg_match("/\s/", $pass)) {
echo 'Password can not be empty or contain spaces';
exit();
}
echo '';
return true; //if all is good return true so i can check if password validation passed successfully
}
}
function signup(){
if(isset($_POST['username'])) {
//here I check just the password
if(check_password()){
echo 'success';
exit();
}
}
}
I'm trying to validate a form with JavaScript. It prints error messages when input fields are empty. The problem I'm having is that the code doesn't fire on submit.
http://jsfiddle.net/LHaav/
Here is the HTML code:
<head>
...
<script type="text/javascript" src="./js/validate.js"></script>
....
</head>
...
<form name="submitForm" method="post" id="submitBetaForm" onsubmit="return(validate())" action="validate.php" class="form-style">
<label for="email">Email:</label>
<input type="text" id="email-beta" name="email" placeholder="Enter Email"/>
<label for="firstName">Name:</label>
<input type="text" id="firstName" class="half-width" name="messageName" placeholder="First name"/>
...
Here is the JavaScript code:
function validate()
{
var email = document.submitForm.email;
var first = document.submitForm.firstName;
var last = document.submitForm.lastName;
var message = document.getElementById('warning');
message.innerHTML = 'This is working!';
var newLineCharNum = 0, poemContentArray = 0;
//check to make sure that there is actually new line in the
//text area. Ensure that code doesn't blow up.
if(textarea.value.match(/\n/g) != null)
{
newLineCharNum = textarea.value.match(/\n/g).length;
poemContentArray = textarea.value.split("\n");
}
//check for email, firstName, lastName
//focus puts the cursor on the element that needs to be corrected.
var lineNum = newLineCharNum + 1;
// if(email.value.length > 30)
// {
// message.innerHTML = 'Email should be less than 30 character';
// title.focus();
// return false;
// }
else if(email.value.length == 0 || title == "")
{
message.innerHTML = 'Please enter your email';
title.focus();
return false;
}
if (firstName.value.length > 30)
{
message.innerHTML = 'First name should be less than 30 character';
authorName.focus();
return false;
}
else if(firstName.value.length == 0 ||authorName == "")
{
message.innerHTML = 'Please enter your first name';
authorName.focus();
return false;
}
if (lastName.value.length > 30)
{
message.innerHTML = 'Last name should be less than 30 character';
authorName.focus();
return false;
}
else if(lastName.value.length == 0 ||authorName == "")
{
message.innerHTML = 'Please enter your last name';
authorName.focus();
return false;
}
}
And PHP here:
<?php
session_start();
include('connection.php');
if(isset($_POST['SEND'])){
//get information from the form
$email = $_POST['email'];
$first_name = $_POST['messageName'];
$last_name = $_POST['messageLast'];
$interest = $_POST['interest'];
$country = $_POST['country'];
// Check connection
if ($con)
{
$insert_query = "INSERT INTO `user` (`id`, `first_name`, `last_name`, `interest`, `country`, `time`, `email`)
VALUES (NULL, '$first_name', '$last_name', '$interest', '$country', CURRENT_TIMESTAMP, '$email')";
$con->query($insert_query);
$con->close();
echo "here";
}
else{
echo "ERROR!";
}
//store informationn in the sessiont for later use
$_SESSION['email'] = $email;
$_SESSION['first_name'] = $first_name;
$_SESSION['last_name'] = $last_name;
$_SESSION['interest'] = $interest;
$_SESSION['country'] = $country;
}
?>
It turns out that your example is full of bad variable names and references. Your using firstNmae when you should be using first, for instance.
I've corrected some of them and it's apparently working: http://jsfiddle.net/LHaav/1/
You just have to be aware of the JS errors in your browser console and you'll be fine. ;)
You got a good few problems in your Javascript - undefined variables everywhere. But the main problem is that your Javascript in that fiddle is not being executed at all. If you change your form handler to onsubmit="return validate()" you'll see that validate is not defined, although this may be down to how the JS is loaded in the fiddle.
Regardless, to alleviate this problem move your script out of the head and put it in the bottom of the page, just the before the closing body tag. You'll at least now hopefully hit the validate method.
http://jsfiddle.net/LHaav/2/
Now you'll have to take care of all those undefined variables.