开发者

PHP - verify if user exist in DB and display the result without reloading the page

开发者 https://www.devze.com 2023-03-28 20:53 出处:网络
I want to check if a user exists in DB, and if exist display some error without reload the page (modify a div). Any idea what is wrong in this code? Or any other idea how to do it? Thank you

I want to check if a user exists in DB, and if exist display some error without reload the page (modify a div). Any idea what is wrong in this code? Or any other idea how to do it? Thank you

HTML:
<div style="width:510px; height:500px;">
<div class="message">
<div id="alert"></div>
</div>
<form id="signup_form" method="post" action="register.php">
<label class="label">username</label>
<p><input class="signup_form" type="text" name="username"></p>
<label class="label">parola</label>
<p><input class="signup_form" type="text" name="password"></p>
<label class="label">name</label>
<p><input class="signup_form" type="text" name="name"></p>
<label class="label">telefon</label>
<p><input class="signup_form" type="text" name="phone"></p>
<label class="label">email</label>
<p><input class="signup_form" type="text" name="email"></p>

<p><input class="signup_button"  type="submit" value="inregistrare">
</form>

<div class="clear"></div>
</div>

register.php

<?php
include "base.php"; 
$usertaken = '<li class="error">username used</li><br />';
$alert = '';
$pass = 0;
if(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$name = mysql_real_escape_string($_POST['username']);
$phone = mysql_real_escape_string($_POST['phone']);
$email = mysql_real_escape_string($_POST['email']);


 $checkusername = mysql_query("SELECT * FROM details WHERE user = '".$username."'");

 if(mysql_num_rows($checkusername) == 1)
 {
    $pass = 1;
    $alert .="<li>" . $usertaken . "</li>";
 }
 else
 {
    $registerquery = mysql_query("INSERT INTO details (user, pass, name, phone, email) VALUES('".$username."', '".$password."','".$name."','".$phone."', '".$email."')");
    if($registerquery)
    {
        echo "<h1>Success</h1>";
        echo "<p>Your account was successfully created. Please <a href=\"index.php\">click here to login</a>.</p>";
    }
    else
    {
        echo "<h1>Error</h1>";
        echo "<p>Sorry, your registration failed. Please go back and try again.</p>";    
    }       
 }
 if($pass == 1) {
    echo '<script>$(".message").hide("").show(""); </script>';
    echo "<ul>";
    echo $alert;
    echo "</ul>";
 }
}
        ?>

SOLUTION (add this in head and hide .message div)

<script type="text/javascript" src="jquery-latest.pack.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() { 
var opt开发者_高级运维ions = { 
target:        '#alert',
beforeSubmit:  showRequest,
success:       showResponse
}; 
$('#signup_form').ajaxForm(options); 
}); 
function showRequest(formData, jqForm, options) { 
var queryString = $.param(formData); 
return true; 
} 
function showResponse(responseText, statusText)  {  
} 
$.fn.clearForm = function() {
  return this.each(function() {
var type = this.type, tag = this.tagName.toLowerCase();
if (tag == 'form')
  return $(':input',this).clearForm();
if (type == 'text' || type == 'password' || tag == 'textarea')
  this.value = '';
else if (type == 'checkbox' || type == 'radio')
  this.checked = false;
else if (tag == 'select')
  this.selectedIndex = -1;
  });
};
</script>


You need to use AJAX to do a dynamic page update.

Take a look here: http://api.jquery.com/jQuery.ajax/ for how to do it with jQuery.

Your current code uses a form submit, which always reloads the page.


You need to use ajax. Write something like this as a JavaScript:

 var xmlHttp;
 function checkUser(user) {
   xmlHttp=GetXmlHttpObject();
   if (xmlHttp==null) {
     alert ("Browser does not support HTTP Request.");
     return;
   }
   var url = "check.php"; //This is where your dynamic PHP file goes
   url = url + "?u=" + user;
   url = url + "&sid=" + Math.random();
   xmlHttp.onreadystatechange = getData;
   xmlHttp.open("GET",url,true);
   xmlHttp.send(null);
 }
 function getData () {
   if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
     if (xmlHttp.responseText == 1) {
           alert('Username free'); //action if username free
         } else {
           alert('This username is taken'); //action if its not
         }
   }
 }
   function GetXmlHttpObject() {
   var xmlHttp=null;
   try {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
   } catch (e) {
     //Internet Explorer
     try {
       xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
     } catch (e) {
       xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
     }
   }
   return xmlHttp;
 }

And in your check.php file, just check against your database if the username is taken or not, if not and simply echo('1') if its free, else echo('0') o whatever you want. that single number will be handled as the xmlHttp.responseText. you can also do something fancy instead of the alerts, like an image. also you need to run the check() fumction either when the user is typing, or when the form is submitted, with the username form field as a parameter. Hope this helps.

EDIT: Oh, also I forgot that in the check.php file, the $_GET['u'] variable contains the the entered username. Check that against the database.


If that's all in a single page, you'll have to structure it like this:

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
   ... do form retrieval/database stuff here ...
   if (error) {
      $message = 'Something dun gone boom';
   }
}

if ($message != '') {
   echo $message;
}
?>

form stuff goes here
0

精彩评论

暂无评论...
验证码 换一张
取 消