0

hello....

i want to do the validations in registration form. but my validation is when the user enters the value in textbox that value automatically cheks that value is already in database or not.


for example..........username textbox is there..now i am entering value first three letter "kal" then comes beside the textbox "username 'kal' is available for you". and next i am entering nextletter "kalp" then comes beside the textbox "kalp is available". plz help me.....any chances to do this task.

3
Contributors
8
Replies
11
Views
7 Years
Discussion Span
Last Post by jomanlk
0

First write a PHP page that accepts a variable (username) and does a database query to see whether it is available. This page can return a value depending on whether the username is available or not.

Once you have done that, use Javascript on the form so that everytime the user types something in it send an AJAX request to the above PHP page with the username as the variable.

You should probably put a minimum threshold of a few characters so that it doesn't check for one letter usernames

0

First write a PHP page that accepts a variable (username) and does a database query to see whether it is available. This page can return a value depending on whether the username is available or not.

Once you have done that, use Javascript on the form so that everytime the user types something in it send an AJAX request to the above PHP page with the username as the variable.

You should probably put a minimum threshold of a few characters so that it doesn't check for one letter usernames

will it works with out submit the form? if u have any sample code send it.....for basic idea.

Edited by muralikalpana: n/a

0

Yeah, it will work without a submit since it's using ajax. The request is sent in the background.

This is probably what you're looking for : http://www.ajaxf1.com/tutorial/ajax-php.html

<?php
ob_start();
extract($_REQUEST);
extract($_POST);
session_start();
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
$db=mysql_select_db('murali',$con);


$message = '';
    $error = array();
     $select=mysql_query("select * from registration where username='$_REQUEST[username]'");
	  
   
     
$taken_usernames=mysql_fetch_array($select);

    // main submit logic
    if (@$_REQUEST['action'] == 'register') {
        $resp = check_username($_REQUEST['username']);
        
        if ($resp['ok']) {
            $message = 'All details fine';
        } else {
            $message = 'There was a problem with your registration details';
            $error = $resp;
        }
    } else if (@$_REQUEST['action'] == 'check_username' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
        // means it was requested via Ajax
        echo json_encode(check_username($_REQUEST['username']));
        exit; // only print out the json version of the response
    }
    
    function check_username($username) {
        global $taken_usernames;
        $resp = array();
        $username = trim($username);
        if (!$username) {
            $resp = array('ok' => false, 'msg' => "Please specify a username");
        } else if (!preg_match('/^[a-z0-9\.\-_]+$/', $username)) {
            $resp = array('ok' => false, "msg" => "Your username can only contain alphanumerics and period, dash and underscore (.-_)");
        } else if (in_array($username, $taken_usernames)) {
            $resp = array("ok" => false, "msg" => "The selected username is not available");
        } else {
            $resp = array("ok" => true, "msg" => "This username is free");
        }

        return $resp;        
    }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en">
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title>jQuery for Designers - Ajax Form Validation Example</title>
    <style type="text/css" media="screen">
    <!--
      BODY { margin: 10px; padding: 0; font: 1em "Trebuchet MS", verdana, arial, sans-serif; font-size: 100%; }
      H1 { margin-bottom: 2px; font-family: Garamond, "Times New Roman", Times, Serif;}
      TEXTAREA { width: 80%;}
      FIELDSET { border: 1px solid #ccc; padding: 1em; margin: 0; }
      LEGEND { color: #ccc; font-size: 120%; }
      INPUT, TEXTAREA { font-family: Arial, verdana; font-size: 125%; padding: 7px; }
      LABEL { display: block; margin-top: 10px; } 
      IMG { margin: 5px; }
      #message {
          border: 1px solid #ccc;
          background-color: #ffa;
          padding: 5px;
      }
      DIV.submit {
        background: #eee;
        border: 1px solid #ccc;
        border-top: 0;
        padding: 1em;
        text-align: right;
        margin-bottom: 20px;
      }
      IMG.avatar {
          vertical-align: top;
      }
    -->
    </style>

    <script src="jquery.js" type="text/javascript"></script>
<?php if (!isset($_REQUEST['nojs'])) : ?>
    <script type="text/javascript">
    <!--
    $(document).ready(function () {
	
        // Username validation logic
        var validateUsername = $('#validateUsername');
        $('#username').keyup(function () {
            // cache the 'this' instance as we need access to it within a setTimeout, where 'this' is set to 'window'
            var t = this; 
            
            // only run the check if the username has actually changed - also means we skip meta keys
            if (this.value != this.lastValue) {
                
                // the timeout logic means the ajax doesn't fire with *every* key press, i.e. if the user holds down
                // a particular key, it will only fire when the release the key.
                                
                if (this.timer) clearTimeout(this.timer);
                
                // show our holding text in the validation message space
                validateUsername.removeClass('error').html('<img src="images/ajax-loader.gif" height="16" width="16" /> checking availability...');
                
                // fire an ajax request in 1/5 of a second
                this.timer = setTimeout(function () {
                    $.ajax({
                        url: 'ajax-validation.php',
                        data: 'action=check_username&username=' + t.value,
                        dataType: 'json',
                        type: 'post',
                        success: function (j) {
                            // put the 'msg' field from the $resp array from check_username (php code) in to the validation message
                            validateUsername.html(j.msg);
                        }
                    });
                }, 200);
                
                // copy the latest value to avoid sending requests when we don't need to
                this.lastValue = this.value;
            }
        });
        
        // avatar validation
        // we use keyup *and* change because 
        $('#avatar').keyup(function () {
            var t = this;
            clearTimeout(this.timer);
            this.timer = setTimeout(function () {
                if (t.value == t.current) {
                    return true;
                }

                var preview = $('#validateAvatar').html('<img src="images/ajax-loader.gif" height="16" width="16" /> trying to load avatar...');
                var i = new Image();

                clearTimeout(t.timeout);

                if (t.value == '') {
                    preview.html('');
                } else {
                    i.src = t.value;
                    i.height = 32;
                    i.width = 32;
                    i.className = 'avatar';

                    // set a timeout of x seconds to load the image, otherwise, show the fail message
                    t.timeout = setTimeout(function () {
                        preview.html('Image could not be loaded.');
                        i = null;
                    }, 3000);

                    // if the dummy image holder loads, we'll show the image in the validation space,
                    // but importantly, we clear the timer set above
                    i.onload = function () {
                        clearTimeout(t.timeout);
                        preview.empty().append(i);
                        i = null;
                    };
                }
                
                t.current = t.value;
            }, 250);
        }).change(function () {
            $(this).keyup(); // call the keyup function
        });
    });
    //-->
    </script>
<?php endif ?>
  </head>
  <body>
    <div>
        
        
<?php if ($message) : ?>
        <p id="message"><?=$message?></p>
<?php endif ?>
        <form action="" method="post">
            <fieldset>
                <legend>Register</legend>
                <div>
                    <label for="username">Username, valid: a-z.-_</label>
                    <input type="text" name="username" value="<?=@$_REQUEST['username']?>" id="username" />
                    <span id="validateUsername"><?php if ($error) { echo $error['msg']; } ?></span>
                </div>
                <div>
                    <label for="avatar">Avatar URL</label>
                    <input type="text" name="avatar" size="50" value="<?=@$_REQUEST['avatar']?>" id="avatar" />
                    <span id="validateAvatar"><?php if (@$_REQUEST['avatar']) { echo '<img src="' . $_REQUEST['avatar'] . '" height="32" width="32" class="avatar" />'; }?></span>
                </div>
            </fieldset>
            <input type="hidden" name="action" value="register" />
            <div class="submit"><input type="submit" name="register" value="Register" id="register" /></div>
        </form>
       
    </div>
  </body>
</html>

not working..........plz see once. in_array error occuring. but my requirement is exactly like twitter registration form.

Edited by muralikalpana: n/a

0
<?php
ob_start();
extract($_REQUEST);
extract($_POST);
session_start();
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
$db=mysql_select_db('murali',$con);


$message = '';
    $error = array();
     $select=mysql_query("select * from registration where username='$_REQUEST[username]'");
	  
   
     
$taken_usernames=mysql_fetch_array($select);

    // main submit logic
    if (@$_REQUEST['action'] == 'register') {
        $resp = check_username($_REQUEST['username']);
        
        if ($resp['ok']) {
            $message = 'All details fine';
        } else {
            $message = 'There was a problem with your registration details';
            $error = $resp;
        }
    } else if (@$_REQUEST['action'] == 'check_username' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
        // means it was requested via Ajax
        echo json_encode(check_username($_REQUEST['username']));
        exit; // only print out the json version of the response
    }
    
    function check_username($username) {
        global $taken_usernames;
        $resp = array();
        $username = trim($username);
        if (!$username) {
            $resp = array('ok' => false, 'msg' => "Please specify a username");
        } else if (!preg_match('/^[a-z0-9\.\-_]+$/', $username)) {
            $resp = array('ok' => false, "msg" => "Your username can only contain alphanumerics and period, dash and underscore (.-_)");
        } else if (in_array($username, $taken_usernames)) {
            $resp = array("ok" => false, "msg" => "The selected username is not available");
        } else {
            $resp = array("ok" => true, "msg" => "This username is free");
        }

        return $resp;        
    }
?>
      <!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>Ajax - PHP example</title>
  
      </head>
 
   
 
      <body>
 
       

      <script language="javascript" type="text/javascript">

      <!--
  
      // Get the HTTP Object
  
      function getHTTPObject(){
 
      if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");

      else if (window.XMLHttpRequest) return new XMLHttpRequest();

      else {

      alert("Your browser does not support AJAX.");

      return null;

      }

      }

       

      // Change the value of the outputText field
 
      function setOutput(){

      if(httpObject.readyState == 4){
  
      document.getElementById('outputText').value = httpObject.responseText;
  
      }
 
       

      }

       
 
      // Implement business logic

      function doWork(){
 
      httpObject = getHTTPObject();
 
      if (httpObject != null) {
  
      httpObject.open("GET", "upperCase.php?inputText="

      +document.getElementById('inputText').value, true);
 
      httpObject.send(null);
 
      httpObject.onreadystatechange = setOutput;
  
      }
 
      }
  
       
 
      var httpObject = null;

       
  
      //-->
 
      </script>

       

      <form name="testForm">

      Input text: <input type="text" onkeyup="doWork();" name="inputText" id="inputText" />

      Output text: <input type="text" name="outputText" id="outputText" />
  
      </form>
 
      </body>
 
      </html>

sorry last example is not correct. see this is done by me. not working

Edited by muralikalpana: n/a

0

I have a question about something ... how can i make my userz have to go thru the login page to access ther accounts,
E.X.
http//x.php = login page
http://y.php = users page

I need if you tipe http://y.php in the browser to give you http://x.php not y.php ... only after you enter your user and pass go to y.php

Right now you dont even have to be registerd to access y.php :(

Edited by foxwizzy: n/a

0

@foxwizzy

Start a new thread with your question please. Otherwise the topic of this thread may veer off from the original.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.