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;
}
}
}
?>
Related
Still havent solved this. Can someone help me with my new, updated code. The new code is at the bottom of this post.
Im learning PHP and right now Im trying to learn to pass data from JS to PHP using AJAX.
This is my form:
<form id="login">
<label><b>Username</b></label>
<input type="text" name="username" id="username"
required>
<label><b>Password</b></label>
<input type="password" name="password" id="password"
required>
<button type="button" id="submitLogin">Login</button>
</form>
First I have a function, something like this:
try {
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}else{
Do stuff }
}
catch(error){ alert('"XMLHttpRequest failed!' + error.message); }
After this, Im trying to send my form data to a php-file, using new FormData(), but Im not really sure how to do this. Right now I have a code like this:
if (getElementById('username').value != "" & getElementById('password').value != "") {
request.addEventListener('readystatechange', Login, false);
request.open('GET', 'login.php', true);
request.send(new FormData(getElementById('login')));
}
The login-function is a function to test
if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {
In my PHP-file I have a function looking like this right now:
session_start();
$logins = array('username1' => 'password1','username2' => 'password2');
if(isset($_GET['login'])) {
$Username = isset($_GET['username']) ? $_GET['username'] : '';
$Password = isset($_GET['password']) ? $_GET['password'] : '';
if (isset($logins[$Username]) && $logins[$Username] == $Password){
do stuff
}
What more do I need to pass my form data from the js-file to the php-file, so I can check if the input data is the same as the data I have in the array?
-----------------------------------------------------------------------
New code:
function LoginToSite() {
if (getElementById('username').value != "" && getElementById('password').value != "") {
request.addEventListener('readystatechange', Login, false);
var username = encodeURIComponent(document.getElementById("username").value);
var password = encodeURIComponent(document.getElementById("password").value);
request.open('GET', 'login.php?username='+username+"&password="+password, true);
request.send(null);
}
}
function Login() {
if (request.readyState === 4 && request.status === 200) {
alert("READY");
var myResponse = JSON.parse(this.responseText);
getElementById("count").innerHTML = myResponse;
getElementById('login').style.display = "none";
if(request.responseText == 1){
alert("Login is successfull");
}
else if(request.responseText == 0){
alert("Invalid Username or Password");
}
}
else{
alert("Error :Something went wrong");
}
request.send();
}
session_start();
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if($username != '' and $password != ''){
foreach($user_array as $key=>$value){
if(($key == $username) && ($value == $password)){
echo "1";
}else{
echo "0";
}
}
}else{
echo "0";
}
When im trying to login, the site first alert that something went wrong, then the same thing happens again and after that, it alerts "ready". What do I have to change to get this right?
Try running the following code.
HTML :
<form id="login">
<label><b>Username</b></label>
<input type="text" name="username" id="username"
required>
<label><b>Password</b></label>
<input type="password" name="password" id="password"
required>
<button type="button" id="submitLogin">Login</button>
</form>
JavaScript:
function submitLogin{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var http = new XMLHttpRequest();
var url = "login.php";
var params = "username="+username+"&password="+password;
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
if(http.responseText == 1){
alert("Login is successfull");
}
else{
alert("Invalid Username or Password");
}
}
else{
alert("Error :Something went wrong");
}
}
http.send(params);
}
PHP:
<?php
session_start();
$logins = array('username1' => 'password1','username2' => 'password2');
if(isset($_POST['username']) && isset($_POST['password'])){
$username = trim($_POST['username']);
$password = trim($_POST['password']);
foreach($logins as $key=>$value){
if(($key == $username) && ($value == $password)){
echo "1";
}else{
echo "0";
}
}
}else{
echo "0";
}
?>
I hope this helps you.
Basically you need something like this (JS side)
// create and open XMLHttpRequest
var xhr = new XMLHttpRequest;
xhr.open ('POST', 'login.php'); // don't use GET
// 'onload' event to handle response
xhr.addEventListener ('load', function () {
if (this.responseText == 'success')
alert ('successfully logged in.');
else
alert ('failed to log in.');
}, false);
// prepare and send FormData
var fd = new FormData;
fd.append ('username', document.getElementById("username").value);
fd.append ('password', document.getElementById("password").value);
xhr.send (fd);
PHP code (login.php) may look like this.
# users array
$logins = array ( 'username1' => 'pwd1', 'username2' => 'pwd2' );
# validate inputs
$u = isset ($_POST['username']) ? $_POST['username'] : false;
$p = isset ($_POST['password']) ? $_POST['password'] : false;
# check login
if ($u !== false && $p !== false && isset ($logins[$u]) && $logins[$u] == $p)
echo "success";
else
echo "error";
Course, it's recommended to check do functions XMLHttpRequest and FormData exist first.
if (window['XMLHttpRequest'] && window['FormData']) {
/* place your Ajax code here */
}
I'm trying to validate if a username is already taking or not. This onchange of an input field. I already got other checks but they don't work anymore since I added the ajax call. I'm new to ajax and javascript so the error can be there.
the html form:
<form action="test" method="post">
<input id="username" type="text" placeholder="Gebruikersnaam" name="username" required onchange="checkUserName()">
<br>
<input id="email" type="text" placeholder="Email" name="email" required onchange="validateEmail()">
<br>
<input id="pass1" type="password" placeholder="Type wachtwoord" name="password1" required>
<br>
<input id="pass2" type="password" placeholder="Bevestig wachtwoord" name="password2" required onchange="passwordCheck()">
<br>
<select name="typeAccount">
<option value="bedrijf">Bedrijf</option>
<option value="recruiter">Recruiter</option>
<option value="werkzoekende">Talent zoekt job</option>
</select>
<p id="demo1">
</P>
<p id="demo2">
</P>
<button type="submit">Scrijf mij in!</button>
</form>
the javascript that I use:
<script src="jquery.js">
function passwordCheck(){
var password1 = document.getElementById('pass1').value;
var password2 = document.getElementById('pass2').value;
if(password1 !== password2){
document.getElementById("pass1").style.borderColor = "#ff3333";
document.getElementById("pass2").style.borderColor = "#ff3333";
}else{
document.getElementById("pass1").style.borderColor = "#1aff1a";
document.getElementById("pass2").style.borderColor = "#1aff1a";
}
}
function validate(email){
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validateEmail(){
var email = document.getElementById('email').value;
if(validate(email)){
document.getElementById("email").style.borderColor = "#1aff1a";
}else{
document.getElementById("email").style.borderColor = "#ff3333";
}
}
function checkUserName(){
var username = document.getElementById('username').value;
if(username === ""){
document.getElementById("username").style.borderColor = "#ff3333";
}else{
$.ajax({
url: "userCheck.php",
data: { action : username },
succes: function(result){
if(result === 1){
document.getElementById("username").style.borderColor = "#1aff1a";
}else{
document.getElementById("username").style.borderColor = "#ff3333";
}
}
});
}
}
</script>
The php script I use this is in a different file:
<?php
include("connect.php");
$connect = new Connect();
$username = mysql_real_escape_string($_POST['username']);
$result = mysql_query('select username from usermaindata where username = "'. $username .'"');
if(mysql_num_rows($result)>0){
echo 0;
}else{
echo 1;
}
?>
The script and the html form is in the same html-file and the php is in a seperate PHP-file.
I just want to check if the name is already in the database or not.
I assume your database connection is perfect.
$username = mysql_real_escape_string($_POST['username']);
change above code to
$username = mysqli_real_escape_string($db_connection,$_REQUEST['action']);
because in your ajax you're doing like
$.ajax({
url: "userCheck.php",
data: { action : username },
succes: function(result){
if(result === 1){
document.getElementById("username").style.borderColor = "#1aff1a";
}else{
document.getElementById("username").style.borderColor = "#ff3333";
}
}
});
You have not specified request type and you're fetching value using $_POST with different variable name username which is actually value
You should use $_REQUEST['action']
And make sure you've added jquery.js file in your html.
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();
}
}
}
Uncaught ReferenceError: ajaxObj is not definednewsletter #
main.js:22onclick # index.php:541
I am trying to develop a newsletter which will be on the footer part of the every page and it will use NAME and EMAIL to suscribe. It will grab the data entered by user from HTML form and pass it to ajax for validation after usere click submit which will pass information to newsletter.php and give back message to user if they already exist or signup sucessfull message but what happened is as User click submit button it just says "Please wait.." and keeps on loading forever giving above message on chrome cousole.
I want user to be able to sign up from any page they are on without reloading page.
The problem here is
Above Error given in Chrome cousole while I try to submit the form.
Thank you for looking at my problem. Any help will be appriciated..
HTML
<?php include_once('newsletter.php'); ?>
<form name="signupform" id="signupform" method="POST" onsubmit="return false;">
<p align="center"><strong>NEWSLETTER SIGNUP :</strong>
<input id="sus_name" name="sus_name" type="text" placeholder="Enter your Name" size="15">
<input id="sus_email" name="sus_email" type="text" placeholder="Enter your Email" size="26">
<input id="optin" name="optin" type="submit" value="SUBSCRIBE" onclick="newsletter()"><br>
<span id="status"></span>
</p>
</form>
AJAX
//News Letter Validation
function newsletter(){
var u = document.getElementById("sus_name").value;
var e = document.getElementById("sus_email").value;
var m =(document.URL);
var status = document.getElementById("status");
if(u == "" || e == ""){
status.innerHTML = "Fill out all of the form data";
} else {
document.getElementById("optin").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST","(document.URL)");//Problem with this line as i want it to post to same page where url will be dynamic
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
document.getElementById("optin").style.display = "block";
} else {
window.scrollTo(0,0);
document.getElementById("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> ";
}
}
}
ajax.send("u="+u+"&e="+e);
}
}
newsletter.php
<?php
$msg_to_user = "";
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once "includes/mysqli_connect.php";
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = ereg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysql_real_escape_string($_POST['e']);
// GET USER IP ADDRESS
$ip = ereg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
if (($u != "") && ($e != "") ){
// Be sure to filter this data to deter SQL injection, filter before querying database
$name = $u;
$email = $e;
$sql = mysql_query("SELECT * FROM news_letter WHERE susc_email='$email'");
$numRows = mysql_num_rows($sql);
if (!$email) {
$msg_to_user = '<br /><br /><h4><font color="#FFFFFF">Please type an email address ' . $name . '.</font></h4>';
} else if ($numRows > 0) {
$msg_to_user = '<br /><br /><h4><font color="#FFFFFF">' . $email . ' is already in the system.</font></h4>';
} else {
$i= substr($name,0,3);
$j=rand(1000,9999);
$l= substr($email,0,3);
$k= $i.$j.$l;
$o=rand(0,9);
$m=str_replace("#","$o","$k");
$n=mysql_real_escape_string($m);
$sql_insert = mysql_query("INSERT INTO news_letter (susc_name, susc_email, susc_date, susc_code)
VALUES('$name','$email',now(),'$n')") or die (mysql_error());
$msg_to_user = '<br /><br /><h4><font color="#FFFFFF">Thanks ' . $name . ', you have been added successfully.</font></h4>';
echo "signup_success";
exit();
}
}
}
?>
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.