Ajax check if username exists - php

I am having trouble to get my code working. As a user types in a username it checks the database to see if it exists and if it does sets the <P id="checkusername"> to "Username Taken." and if not sets it to "Not Taken." I can't see why my code is not working.
1-register.html
<html>
<body>
<CENTER>
<form name="register" action="register.php" method="post">
Username: <input type="text" name="username" onkeyup="checkUsername(this.value)" />
<P id="checkusername">checker</P>
<input type="submit" value="Login" />
</form>
</CENTER>
<script type="text/javascript">
function checkUsername(){
var xmlhttp;
var username=document.forms["register"]["username"].value;
if(username.length==0){
document.getElementById("checkusername").innerHTML="Empty";
return;
}
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "login.php";
var params = "header=checkusername&username="+username+"&password="";
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange = function() {//Call a function when the state changes.
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("checkusername").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.send(params);
}
</script>
</body>
</html>
2-register.php
<?php
$header = $_POST["header"];
if(header=="checkusername"){
checkusername($_POST["username"]);
}else{
echo "No match: " . $header;
}
function connection(){
$con = mysql_connect(URL, username, password);
if(!$con){
die('Could not connect: ' . mysql_error());
}
return $con;
}
function checkusername($username){
$con = connection();
mysql_select_db(database, $con);
$result = mysql_query("SELECT * FROM users WHERE username = \"" . $username . "\";");
while($row = mysql_fetch_array($result)){
if(($row['username'] == $username)){
echo "Username Taken.<br/>";
return;
}
}
echo "Not Taken.";
}
mysql_close();
?>

Read this Blog http://papermashup.com/jquery-php-mysql-username-availability-checker/

Related

Ajax call not replacing the content

What I want to do is replace the content of a div after a log in with a welcome message. I've read AJAX tutorials but I might've got it wrong.
Isn't the logIn function supposed to change the content of the element with the given id, with the content echoed by the php file?
Because right now, the log in is done but the content echoed by the php file is displayed in login.php instead of replacing the content of my "user_panel" div.
My html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>My awesome blog!</title>
<script>
function logIn(u,p) {
if (u== "" && p== "") {
document.getElementById("user_panel").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("user_panel").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","login.php?u="+u+"&p="+p,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<div class="nav">
<div class="container">
<div id="user_panel">
<ul>
<li>Login</li>
<li>Register</li>
</ul>
</div>
</div>
</div>
<form class="login" action="login.php" method="post">
<label class="login_label" for="username">Username:</label>
<input type="text" id="username" name="username">
<br>
<label class="login_label" for="password">Password:</label>
<input type="password" id="password" name="password">
<br><br>
<input type="submit" value="Login" onclick="logIn(document.getElementById('username'),document.getElementById('password'))">
</form>
</body>
</html>
my php
<?php
$server = "localhost";
$username = "root";
$password = "123456";
$dbname = "BlogDb";
// Create connection
$con = mysqli_connect($server, $username, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
//echo "Connected successfully2";
$u = $_POST['username'];
$p = $_POST['password'];
setcookie("User_in", $u, time() + (86400 * 30), "/");
// Set session variables
$_SESSION["user_on"] = $u;
$sql= "SELECT username,is_admin FROM User WHERE username ='".$u."' and password='".$p."'";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<ul>";
echo "<li>";
echo "Welcome " . $row['username'] . "! How are you today?";
echo "</li><li>";
echo "<a href=logout.php>Log out</a>";
echo "</li></ul>";
}
mysqli_close($con);
?>
What am I doing wrong here?
the input type='sumbit' when clicked where submit this form so you must prevent this default event you can change this type='button'!
document.getElementById('username') where return node n't input value get input value can use
document.getElementById('username').value
below is my change code:
html:
<input type="submit" value="Login" onclick="logIn()">
js:
function logIn(e) {
e = e || window.event;
e.preventDefault();
var u = document.getElementById('username').value,
p = document.getElementById('password').value;
if (u== "" && p== "") {
document.getElementById("user_panel").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("user_panel").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","login.php?u="+u+"&p="+p,true);
xmlhttp.send();
}
}
*** This is a comment as I don't have access to the comment section I am adding as answer******
Hi Matt,
If Ajax is used there is no need to use html-->input-->submit. Use a <button> tag
and then invoke the js function.

Ajax search not Working whereas the XML already running?

I'm a newbie on Ajax, I have tried the tutorial Book, but it did not work. The code is for searching.
This is the script search.htm
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>AJAX + MySQL I</title>
<script type="text/javascript" src="search.js"></script>
</head>
<body onload='process()'>
<h1>Student Search</h1>
<form name="form1">
Masukkan Nama Mahasiswa: <input type="text" id="namaMhs" />
</form>
<p><strong>Hasil Pencarian :</strong></p>
<div id="hasil" />
</body>
</html>
and the JS script search.js
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
xmlHttp = false;
}
}
if (!xmlHttp) alert("Obyek XMLHttpRequest tidak dapat dibuat");
else
return xmlHttp;
}
function process()
{
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
nama =
encodeURIComponent(document.getElementById("namaMhs").value);
xmlHttp.open("GET", "search.php?namaMhs=" + nama, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
setTimeout('process()', 1000);
}
function handleServerResponse()
{
if (xmlHttp.readyState == 4)
{
if (xmlHttp.status == 200)
{
var xmlResponse = xmlHttp.responseXML;
xmlRoot = xmlResponse.documentElement;
nimArray = xmlRoot.getElementsByTagName("nim");
namaMhsArray = xmlRoot.getElementsByTagName("namamhs");
alamatArray = xmlRoot.getElementsByTagName("alamat");
if (nimArray.length == 0)
{
html = "Data tidak ditemukan";
}
else
{
// membentuk tabel untuk menampilkan hasil pencarian
html = "<table border='1'><tr><th>NIM</th><th>Nama
Mhs</th><th>Alamat</th></tr>";
for (var i=0; i<nimArray.length; i++)
{
html += "<tr><td>" + nimArray.item(i).firstChild.data +
"</td><td>" +
namaMhsArray.item(i).firstChild.data +
"</td><td>" +
alamatArray.item(i).firstChild.data +
"</td></tr>";
}
html = html + "</table>";
}
document.getElementById("hasil").innerHTML = html;
setTimeout('process()', 1000);
}
else
{
alert("Ada masalah dalam mengakses server: " +
xmlHttp.statusText);
}
}
}
and the last script in php search.php
<?php
header('Content-Type: text/xml');
echo '<hasil>';
$namaMhs = $_GET['namaMhs'];
mysql_connect("localhost","root","*******");
mysql_select_db("mahasiswa");
$query = "SELECT * FROM mhs WHERE namamhs LIKE '%$namaMhs%'";
$hasil = mysql_query($query);
while ($data = mysql_fetch_array($hasil))
{
echo "<mhs>";
echo "<nim>".$data['NIM']."</nim>";
echo "<namamhs>".$data['NAMAMHS']."</namamhs>";
echo "<alamat>".$data['ALAMAT']."</alamat>";
echo "</mhs>";
}
echo '</hasil>';
?>
Please help me to fix this script. The XML on search.php is already running but my searching is not. Any help is appreciated.
You are submitting the script on load, before there is even a value in the text field:
<body onload='process()'>
<h1>Student Search</h1>
<form name="form1">
Masukkan Nama Mahasiswa: <input type="text" id="namaMhs" />
</form>
You should either add a value to the text field as such:
<input type="text" value="testname" id="namaMhs" />
Or as a better option, add a submit button and don't run the function on load, but rather on submit:
<body>
<h1>Student Search</h1>
<form name="form1">
Masukkan Nama Mahasiswa: <input type="text" id="namaMhs" />
<input type="button" value="Search" onclick="process();" />
</form>
There may be more or even many more problems with your code, I am not looking through it all, but this should get you off to a good start.

Go automatically to another page using html

I have two pages, a html that send value to a php page, and than, the php page returns the result in a div, in the html page.
In the first test it has only a message with error, and in the else clause it must redirect to another html page, so the script in the php page will be shown in html. I've used javascript but it doesn't do it for me.
This is all the codes that i've used:
if (mysqli_num_rows($result)==0)
{
echo" Code erroné ";
}
else
{
header('location:infosInt.html');
//echo "<script> window.open('infosInt.html')</script>";
//echo "<script> window.location = 'infosInt.html'</script>";
}
EDIT
my html page :
<!DOCTYPE html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script src="jquery-ui.js" charset="ISO-8859-1"></script>
<script src="jquery-1.9.1.js" charset="ISO-8859-1"></script>
<script type="text/javascript" src="jquery.crypt.js" ></script>
<LINK rel="stylesheet" type="text/css" href="android.css">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Login Form</title>
<script>
function connexion(evt)
{
var x=document.getElementById('code');
var cde = x.value;
var str = $().crypt({
method: "md5",
source: cde
});
if (cde=="")
{
// document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
var url ="http://localhost/filename/page.php";
var params="q="+ str;
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
};
</script>
</head>
<body>
<div class="login">
<p></p>
<form method="" action="" id= "codeform" onsubmit="connexion();return false;">
<p> &nbsp &nbsp &nbsp &nbsp</p>
<input type="password" id="code" ></p>
<p class="submit"><input type="submit" id="connect" value="Connexion" ></p>
</form>
<div id ="txtHint"></div>
</div>
</body>
</html>
and this is page.php:
<?php
$host = "localhost";
$port = port;
$socket = "";
$user = "root";
$password = "";
$dbname = "base";
$con = new mysqli($host, $user, $password, $dbname, $port, $socket);
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
$q =$con->real_escape_string($_POST['q']);
mysqli_select_db($con,"ajax_demo");
$sql="query where column ='".$q."'"; // ex
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result)==0)
{
echo" Code erroné ";
}
else
{
echo"<head><meta http-equiv='refresh' content='5; URL=infosInt.html'></head>";}
mysqli_close($con);
?>
The thing is, you are calling your php script with ajax, so you can't use header('Location: ...') or an html redirection. You should return a flag in your php script and test it when you get the response with javascript :
PHP (at the end of page.php):
if (mysqli_num_rows($result)==0)
{
echo "Code erroné";
}
else
{
echo "redirect"; // the flag
}
Javascript (on the xmlhttp.onreadystatechange event) :
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if (xmlhttp.responseText == 'redirect') { // if flag is sent we redirect
document.location.href = 'infosInt.html';
} else {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}

For Search In PHP using Ajax

I perform live search in php using ajax. This is my code for performing task
googleajax.php
<?php
$id=$_GET['id'];
if(isset($_POST['submit']))
{
$temp=$_POST['name'];echo $temp;
}
?>
<html>
<head>
<script language="javascript" type="text/javascript">
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getValue(id)
{
var strURL="googledata.php?id="+id;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('div1').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
</head>
<body>
<form method="post">
<?php
/*$query="Select * from tblcountry where country_id='".$id."'";
echo $
$res=mysql_query($res);
while($row=mysql_fetch_assoc($res))
{
extract($row);*/
?>
<input type="text" id="name" name="name" onKeyUp="getValue(this.value)" value="<?php echo $id;?>" />
<input type="submit" id="submit" name="submit" value="serch">
<div id="div1" name="div1">
</div>
<?php
/*<!--}-->*/
?>
</form>
</body>
</html>
and googledata.php
<?php
$con=mysql_connect("localhost","root","");
if(!$con)
{
die("error in connection");
}
else
{
mysql_select_db("hms2012",$con);
}
$id= $_GET['id'];
if($id=="")
{
}
else
{
$result=mysql_query("select * from tblcountry where country_name like '$id%'");
while($row=mysql_fetch_assoc($result))
{
extract($row);
echo "<option value='$country_id'><a href='googleajax.php?id=$country_id'>".$country_name."</a><br></option>";
}
}
?>
Performing this code I can not select value for press key.
What was the use that I can select the value?
You have no <select></select> around your <options> tags list.
You should take a look on using jQuery for your Ajax stuff.
what is $country_id and $country_name. I have changed it by assumption. Please check.
echo '<select name="somename">';
while($row=mysql_fetch_assoc($result))
{
extract($row);
echo "<option value='".$row['country_id']."'><a href='googleajax.php?id=".$row['country_id']."'>".$row['country_name']."</a><br></option>";
}
echo "</select>";

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

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 click here to login.</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 options = {
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

Categories