JSON, Ajax login and signup form problem, critique

Posted by user552828 on Stack Overflow See other posts from Stack Overflow or by user552828
Published on 2011-06-24T00:02:51Z Indexed on 2011/06/24 0:22 UTC
Read the original article Hit count: 397

Filed under:
|
|
|

Here is my problem;

indexdeneme2.php

has two forms Sign up and Login form, and there is validation.js and login.js which are handling the AJAX and JSON response, there are validate.php and login.php which are my scripts for validating and login.

When you sign up, it sends the data to validate.php perfectly and validate.php response with JSON perfectly, validate.js must show the error in #error div. validation.js works perfectly if it is working alone.

I use same kind of script for login form. Login.php also works perfectly it responses with JSON and login.js shows the errors are appear in #errorlogin div. But this works when login.js works alone.

When I try to work login.js and validate.js together, it is not working. validate.php and login.php works perfectly but login.js and validation.js are not working together. They can't handle the responses coming from php scripts. It is not showing the errors in #errorlogin and #error div. They intercept each other I guess.

By the way if you can critique my login.php and validate.php I will be really appreciated.

Thank you all.

this is indexdeneme2.php

    <?php include('functions.php')?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" href="css/cssdeneme1.css" /> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="validation.js"></script>
<script type="text/javascript" src="login.js"></script>
<script type="text/javascript">
 var RecaptchaOptions = {
    theme : 'custom',
    custom_theme_widget: 'recaptcha_widget'
 };
 </script>
</head>
<body onload="document.signup.reset()">

<div id="topbar">
    <div class="wrapper">
    </div>
</div>
<div id="middlebar">
    <div class="wrapper">
        <div id="middleleft">
          <div id="mainformsecondcover">
            <div id="mainform">
                <div id="formhead">
                    <div id="signup">Sign Up</div>
                </div>
                <form method="post" action="validate.php" id="myform" name="signup">
                <div id="form">
                    <table border="0" cellpadding="0" cellspacing="1">
                        <tbody>
                            <tr>
                                <td class="formlabel">
                                    <label for="name">First Name:</label>
                                </td>
                                <td class="forminput">
                                    <input type="text" name="name" id="name" />
                                </td>
                            </tr>
                            <tr>
                                <td class="formlabel">
                                    <label for="lastname">Last Name:</label>
                                </td>
                                <td class="forminput">
                                    <input type="text" name="surname" id="lastname" />
                                </td>
                            </tr>
                            <tr>
                                <td class="formlabel">
                                    <label for="email">Email:</label>
                                </td>
                                <td class="forminput">
                                    <input type="text" name="email" id="email" />
                                </td>
                            </tr>
                            <tr>
                                <td class="formlabel">
                                    <label for="remail">Re-Enter Email:</label>
                                </td>
                                <td class="forminput">
                                    <input type="text" name="remail" id="remail" />
                                </td>
                            </tr>
                            <tr>
                                <td class="formlabel">
                                    <label for="password">Password:</label>
                                </td>
                                <td class="forminput">
                                    <input type="password" name="password" id="password" maxlength="16" />
                                </td>
                            </tr>
                            <tr>
                                <td class="formlabel">
                                    <label for="gender">I am:</label>
                                </td>
                                <td class="forminput">
                                    <select name="gender" id="gender">
                                        <option value="0" selected="selected">-Select Sex-</option>
                                        <option value="1">Male</option>
                                        <option value="2">Female</option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <td class="formlabel">
                                    <label>My Birthday:</label>
                                </td>
                                <td class="forminput">
                                    <select size="1" name="day">
                                        <option value="0" selected="selected">Day</option>
                                        <?php formDay(); ?>
                                    </select>&nbsp;
                                    <select size="1" name="month">
                                        <option value="0" selected="selected">Month</option>
                                        <option value="1">January</option>
                                        <option value="2">February</option>
                                        <option value="3">March</option>
                                        <option value="4">April</option>
                                        <option value="5">May</option>
                                        <option value="6">June</option>
                                        <option value="7">July</option>
                                        <option value="8">August</option>
                                        <option value="9">September</option>
                                        <option value="10">October</option>
                                        <option value="11">November</option>
                                        <option value="12">December</option>
                                  </select>&nbsp;
                                  <select size="1" name="year">
                                    <option value="0" selected="selected">Year</option>
                                    <?php formYear(); ?>
                                  </select>
                                </td>
                            </tr>
                            <tr>
                                <td class="formlabel">
                                    <label for="recaptcha_response_field">Security Check:</label>                                 
                                </td>
                            </tr>
                        </tbody>
                    </table>
                                <?php
                                  require_once('captchalib.php');
                                ?>

                </div>
                <div id="formbottom">
                    <div id="error">
                    </div>
                    <div id="formbottomright">
                            <input type="submit" id="formbutton" value="Sign Up" />
                            <img id="loading" src="css/images/ajax-loader.gif" height="35" width="35" alt="Processing.." style="float:right; display:block" /> 
                    </div>
               </div>
                </form>
            </div>
           </div>
         </div>
        <div id="middleright">
            <div id="loginform">
                <form name="login" action="login.php" method="post" id="login">
                    <label for="username">Email:</label>
                        <input type="text" name="emaillogin" />
                    <label for="password">Password:</label>
                         <input type="password" name="passwordlogin" maxlength="16" />
                    <input type="submit" value="Login" />
                    <img id="loading2" src="css/images/ajax-loader.gif" height="35" width="35" alt="Processing.." style="float:right; display:block" />
                </form>
            </div>
            <div id="errorlogin"></div>
        </div>
    </div>
</div>
<div id="bottombar">
    <div class="wrapper"></div>
</div>
</body>
</html>

validation.js

$(document).ready(function(){

    $('#myform').submit(function(e) {

        register();
        e.preventDefault();

    });

});

function register()
{
    hideshow('loading',1);
    error(0);

    $.ajax({
        type: "POST",
        url: "validate.php",
        data: $('#myform').serialize(),
        dataType: "json",
        success: function(msg){

            if(parseInt(msg.status)==1)
            {
                window.location=msg.txt;
            }
            else if(parseInt(msg.status)==0)
            {
                error(1,msg.txt);
                Recaptcha.reload();
            }

            hideshow('loading',0);
        }
    });

}

function hideshow(el,act)
{
    if(act) $('#'+el).css('visibility','visible');
    else $('#'+el).css('visibility','hidden');
}

function error(act,txt)
{
    hideshow('error',act);
    if(txt) $('#error').html(txt);
}

login.js

$(document).ready(function(){

    $('#login').submit(function(e) {

        login();
        e.preventDefault();

    });

});

function login()
{
    error(2);

    $.ajax({
        type: "POST",
        url: "login.php",
        data: $('#login').serialize(),
        dataType: "json",
        success: function(msg){

            if(parseInt(msg.status)==3)
            {
                window.location=msg.txt;
            }
            else if(parseInt(msg.status)==2)
            {
                error(3,msg.txt);
            }

        }
    });

}

function error(act,txt)
{
    hideshow('error',act);
    if(txt) $('#errorlogin').html(txt);
}

login.php

<?php
session_start();
require("connect.php");
$email = $_POST['emaillogin'];
$password = $_POST['passwordlogin'];
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password);

    if(empty($email))
    {
        die('{status:2,txt:"Enter your email address."}');
    }

    if(!filter_var($email, FILTER_VALIDATE_EMAIL))
    {
        die('{status:2,txt:"Invalid email or password"}');
    }

    if(empty($password))
    {
        die('{status:2,txt:"Enter your password."}');
    }

    if(strlen($password)<6 || strlen($password)>16)
    {
        die('{status:2,txt:"Invalid email or password"}');
    }

$query = "SELECT password, salt FROM users WHERE Email = '$email';";
$result = mysql_query($query);

    if(mysql_num_rows($result) < 1) //no such user exists
    {
        die('{status:2,txt:"Invalid email or password"}');
    }

$userData = mysql_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );

    if($hash != $userData['password']) //incorrect password
    {
        die('{status:2,txt:"Invalid email or password"}');
    }
////////////////////////////////////////////////////////////////////////////////////
    if('{status:3}')
{   
    session_regenerate_id (); //this is a security measure
    $getMemDetails = "SELECT * FROM users WHERE Email = '$email'";
    $link = mysql_query($getMemDetails);
    $member = mysql_fetch_row($link);
    $_SESSION['valid'] = 1;
    $_SESSION['userid'] = $member[0];
    $_SESSION['name'] = $member[1];
    session_write_close();
    mysql_close($con);  
    echo '{status:3,txt:"success.php"}';
}

validate.php

<?php
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$remail = $_POST['remail'];
$gender = $_POST['gender'];
$bdate = $_POST['year'].'-'.$_POST['month'].'-'.$_POST['day'];
$bday = $_POST['day'];
$bmon = $_POST['month'];
$byear = $_POST['year'];
$cdate = date("Y-n-j");
$password = $_POST['password'];
$hash = hash('sha256', $password);
$regdate = date("Y-m-d");


function createSalt()
{
    $string = md5(uniqid(rand(), true));
    return substr($string, 0, 3);
}

$salt = createSalt();
$hash = hash('sha256', $salt . $hash);

    if(empty($name) || empty($surname) || empty($email) || empty($remail) || empty($password) )
{
    die('{status:0,txt:"All the fields are required"}');
}


    if(!preg_match('/^[A-Za-z\s ]+$/', $name))
{
    die('{status:0,txt:"Please check your name"}');
}


    if(!preg_match('/^[A-Za-z\s ]+$/', $surname))
{
    die('{status:0,txt:"Please check your last name"}');
}


    if($bdate > $cdate)
{
    die('{status:0,txt:"Please check your birthday"}');
}


    if(!(int)$gender)
{
    die('{status:0,txt:"You have to select your sex"}');
}


    if(!(int)$bday || !(int)$bmon || !(int)$byear)
{
    die('{status:0,txt:"You have to fill in your birthday"}');
}


    if(!$email == $remail)
{
    die('{status:0,txt:"Emails doesn&sbquo;t match"}');
}


    if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
    die('{status:0,txt:"Enter a valid email"}');
}


    if(strlen($password)<6 || strlen($password)>16)
{
    die('{status:0,txt:"Password must be between 6-16 characters"}');
}

    if (!$_POST["recaptcha_challenge_field"]===$_POST["recaptcha_response_field"]) 
{
    die('{status:0,txt:"You entered incorrect security code"}');
}


    if('{status:1}') 
{   
    require("connect.php");
    function getRealIpAddr()
    {
        if (!empty($_SERVER['HTTP_CLIENT_IP']))
        {
          $ip=$_SERVER['HTTP_CLIENT_IP'];
        }
        elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
          $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        else
        {
          $ip=$_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }
    $rip = getRealIpAddr();
    $ipn = inet_pton($rip);
    $checkuser = mysql_query("SELECT Email FROM users WHERE Email = '$email'"); 
    $username_exist = mysql_num_rows($checkuser);
    if ( $username_exist !== 0 )
    {
        mysql_close($con);
    die('{status:0,txt:"This email Address is already registered!"}');
    }
    else
    {

    $query = "INSERT INTO users (name, surname, date, Email, Gender, password, salt, RegistrationDate, IP) VALUES ('$name', '$surname', '$bdate', '$email', '$gender', '$hash', '$salt', '$cdate', '$ipn')";
    $link = mysql_query($query);
    if(!$link)
        {
        die('Becerilemedi: ' . mysql_error());
        }
        else
        {
        mysql_close($con);  
        echo '{status:1,txt:"afterreg.php"}';
        }
    }
}

?>

css of indexdeneme2.php

* { 
    padding:0; margin:0; 
}

#topbar {
    width:100%;
    height:50px;
}
.wrapper {
    margin:0 auto;
    width:1000px;
    height:100%;
}
#middlebar {
    width:100%;
    height:650px;
}
#middleleft {
    width:55%;
    float:left;
    height:650px;
}
#middleright {
    width:45%;
    float:right;
    height:650px;
}
#mainformsecondcover {
    width:404px;
    padding:0px;
    margin:0px;
    border:4px solid #59B;
    border-radius: 14px;
    -moz-border-radius: 14px;
    -webkit-border-radius: 14px;
}
#mainform {
    width:400px;
    border:2px solid #CCC;
    border-radius: 11px;
    -moz-border-radius: 11px;
    -webkit-border-radius: 11px;
}
#formhead {
    margin:7px;
}
#signup {
    margin-top:13px;
    margin-left:13px;
    margin-bottom:3px;
    color:#333;
    font-size:18px;
    font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
    font-weight:bold
}
#form {
    margin:7px;
}
#form table {
    margin:0px;
    width:380px;
}
#form table tr{
    height:28px;
}
#form table td{
    height:18px;
}
.formlabel {
    cursor:pointer;
    display:table-cell;
    text-align:right;
    font-size:12px;
    color:#000;
    font-weight:normal;
    vertical-align:middle;
    font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
    letter-spacing:1px;
    width:120px;
    height:37px;
    padding-right:5px;
}
.formlabel label{
    cursor:pointer
}
.forminput input {
    width:240px;
    font-size:13px;
    padding:4px;
}
#recaptcha_image {
    width:300px;
    height:57px;
    border:2px solid #CCC;
}
#recaptcha_widget {
    margin-left:35px;
}
#securityinfo {
    font-size: 11px;
    line-height: 16px;
}
#formbottom {
    width:360px;
    min-height:45px;
}
#error {
    float:left;
    width:200px;
    border:1px solid #F00;
    margin-left:20px;
    margin-top:7px;
    text-align:center;
    color:#F00;
    font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
    font-size:11px;
    line-height:16px;
    padding:2px;
    visibility:hidden;
}
#errorlogin {
    float:left;
    width:200px;
    border:1px solid #F00;
    margin-left:20px;
    margin-top:7px;
    text-align:center;
    color:#F00;
    font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
    font-size:11px;
    line-height:16px;
    padding:2px;
    visibility:hidden;
}
#formbottomright {
    float:right;
    height:45px;
    width:115px;
    margin-left:5px;
}
#loading {
    visibility:hidden;
}
#loading2 {
    visibility:hidden;
}
#formbutton {
    display:block;
    font-size:14px;
    color:#FFF;
    background: #0b85c6; /* Old browsers */
    background: -moz-linear-gradient(top, #0b85c6 0%, #59b 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#0b85c6), color-stop(100%,#59b)); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top, #0b85c6 0%,#59b 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top, #0b85c6 0%,#59b 100%); /* Opera11.10+ */
    background: -ms-linear-gradient(top, #0b85c6 0%,#59b 100%); /* IE10+ */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#0B85C6', endColorstr='#59B',GradientType=0 ); /* IE6-9 */
    background: linear-gradient(top, #0b85c6 0%,#59b 100%); /* W3C */
    font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
    height:26px;
    width:60px;
    margin:7px;
    text-align:center;
    padding-bottom:4px;
    padding-left:4px;
    padding-right:4px;
    float:left;
    margin-right:5px;
}
#bottombar {
    width:100%;
    height:50px;
}
{}

© Stack Overflow or respective owner

Related posts about php

Related posts about AJAX