Jump to content

AJAX PHP HELP


djbuddhi

Recommended Posts

I have a question .i used ajax with php .i  have form .first field is username ,second field  is email address .now i want to check username exits and to check  email is valid by textbox key up or key enter event .

 

how to do it in ajax. i am little stuck on this on key up or key enter event ,but in form submit event i am able to do that.

 

have u got any idea of how you doing it ? :)

Link to comment
Share on other sites

HTML:

<input type="text" name="username" onkeyup="checkUsername(this.value);">
<span id="usernamecheck"></span>

 

JS:

function getHTTPObject() {
    var xmlhttp;
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        try {
            xmlhttp = new XMLHttpRequest();
        } catch (e) {
            xmlhttp = false;
        }
    }
    return xmlhttp;
}
var http = getHTTPObject();
function checkUsername(uname){
var prodid = document.getElementById('upc'+idnum).value;
http.open('GET', 'ajax.php?function=CheckUserName&=username'+uname, true);
http.send(null);
eval(http.responseText);
}

 

PHP:

<?php
if ($_REQUEST['function']=="CheckUserName"){
$query = "SELECT count(*) FROM accounts WHERE username = '{$_REQUEST['username']}'";
$result = mysql_query($query) or die("alert('Database error: ".mysql_error()."');");
$row = mysql_fetch_row($result);
if ($row[0]>0){
	echo "document.getElementById('usernamecheck').innerHTML = 'That username is already taken.';";
}
}
?>

 

That should get you started.

Link to comment
Share on other sites

Ignore that "var prodid" line. I copied this code from one of my projects and forgot to remove that line.

 

The HTML code is your main page where the username is entered. The JS code is either in it's own .js file, or it's in the <script> tags in your main page. The PHP code is in a separate PHP file, in this case ajax.php in the same directory.

Link to comment
Share on other sites

You're welcome for the help. However, I am not going to write your code for you.

 

Do you know JavaScript? Do you know PHP?

 

If you know JS, then you should know how to disable a button. So, just use the PHP code in the ajax.php file to echo the JS code that will disable the button.

Link to comment
Share on other sites

index.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<title>Untitled Document</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<script type="text/javascript">

var http = false;

 

if(navigator.appName == "Microsoft Internet Explorer") {

  http = new ActiveXObject("Microsoft.XMLHTTP");

} else {

  http = new XMLHttpRequest();

}

 

function validate(user) {

  http.abort();

  http.open("GET", "bud.php?name=" + user, true);

  var result=http.responseText;

  http.onreadystatechange=function() {

    if(http.readyState == 4) {

      document.getElementById('buddhika_div_id').innerHTML = http.responseText;

    }

///document.getElementById('vv').disabled = false;

  }

  http.send(null);

}

// if(result=="Username Exists ..!"){

  //document.getElementById('vv').disabled = true;}

// else{ document.getElementById('vv').disabled = false;}

 

</script>

 

</head>

 

<body>

<form>

  <input type="text" onkeyup="validate(this.value)" />

  <div id="buddhika_div_id"></div>

    <p> </p>

    <p>

      <input type="submit" name="Submit" value="Submit" id="vv">

    </p>

 

</form>

 

</body>

</html>

 

 

here is bud.php

 

<?php

 

$link = mysql_connect("127.0.0.1", "root", "") or die("Could not connect");

 

        $db = mysql_select_db("login", $link) or die("Could not select database");

 

 

       

 

 

function validate($name) {

  if($name == '') {

    return '';

  }

 

  $query = "SELECT count(*) AS C  FROM login WHERE username = '$name'";

  $result = mysql_query($query) or die("alert('Database error: ".mysql_error()."');");

  $counta=mysql_result($result,0,'C'); ///$row = mysql_fetch_row($result);

 

  if ($counta >0){

  return "<span id=\"warn\">Username Exists ..! </span>\n";

 

  }

 

}

 

echo validate(trim($_REQUEST['name']));

?>

 

check the comment place .it was not working .disable the submit button

Link to comment
Share on other sites

PLEASE post you code in the code tags, as it is painful to read without.

 

Try this:

index.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
var http = false;

if(navigator.appName == "Microsoft Internet Explorer") {
  http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
  http = new XMLHttpRequest();
}

function validate(user) {
  http.abort();
  http.open("GET", "bud.php?name=" + user, true);
  var result=http.responseText;
  http.onreadystatechange=function() {
    if(http.readyState == 4) {
      eval(http.responseText);
    }
  }
  http.send(null);
}

</script>

</head>

<body>
<form>
  <input type="text" onkeyup="validate(this.value)" />
  <div id="buddhika_div_id"></div>
    <p> </p>
    <p>
      <input type="submit" name="Submit" value="Submit" id="vv">
    </p>

</form>

</body>
</html>

 

bud.php

<?php
$link = mysql_connect("127.0.0.1", "root", "") or die("Could not connect");
$db = mysql_select_db("login", $link) or die("Could not select database");

function validate($name) {
  if($name == '') {
    return "document.getElementById('vv').disabled = false;";
  }

  $query = "SELECT count(*) AS C  FROM login WHERE username = '$name'";
  $result = mysql_query($query) or die("alert('Database error: ".mysql_error()."');");
  $counta=mysql_result($result,0,'C');   ///$row = mysql_fetch_row($result);

  if ($counta >0){
   return "document.getElementById('buddhika_div_id').innerHTML = '<span id=\"warn\">Username Exists ..! </span>';\n" .
   		"document.getElementById('vv').disabled = true;";

  }

}

echo validate(trim($_REQUEST['name']));
?>

Link to comment
Share on other sites

i tried using this code with my form and did everything like you said but my form now wont change the div from the ajax.php

 

FORM
<html>
<head>
<title>
- Registration
</title>
<script type="text/javascript">
function getHTTPObject() {
var xmlhttp;
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
var http = getHTTPObject();

function emailvalidation(entered)
{
with(entered)
{
apos=value.indexOf("@");
dotpos=value.lastIndexOf(".");
lastpos=value.length-1;
if (apos<1 || dotpos-apos<2 || lastpos-dotpos>3 || lastpos-dotpos<2)
{
document.regform.register.disabled=true;
document.regform.email.style.backgroundColor='red';
var x = document.getElementById('emailtext');
x.innerHTML='Your email is invalid!';

}
else
{
document.regform.register.disabled=false;
document.regform.email.style.backgroundColor='lime';
var x = document.getElementById('emailtext');
x.innerHTML='Your email fits validation, but it need to be valid for activation!';
http.open('GET', 'ajax.php?function=CheckUserName$=username'+entered, true);
http.send(null);
eval(http.responseText);
}
}
}
}

function username(entered)
{
with(entered)
{
var username = entered.value.length;
if (username < 5)
{
document.regform.register.disabled=true;
document.regform.user.style.backgroundColor='red';
var x = document.getElementById('usernametext');
x.innerHTML='Username Too Short';

}
else if (username > 30)
{
document.regform.register.disabled=true;
document.regform.user.style.backgroundColor='red';
var x = document.getElementById('usernametext');
x.innerHTML='Username Too Long';

}
else
{
document.regform.register.disabled=false;
document.regform.user.style.backgroundColor='lime';
http.open('GET', 'ajax.php?function=CheckUserName&=username'+entered, true);
http.send(null);
eval(http.responseText);
}
}
}

function password(entered)
{
with(entered)
{
passwordlength = entered.value.length
if(passwordlength > 30)
{
document.regform.register.disabled=true;
document.regform.pass.style.backgroundColor='red';
var x = document.getElementById('passtext');
x.innerHTML='Password Too Long';
}
else if(passwordlength < 5)
{
document.regform.register.disabled=true;
document.regform.pass.style.backgroundColor='red';
var x = document.getElementById('passtext');
x.innerHTML='Password Too Short';
}
else
{
document.regform.register.disabled=false;
document.regform.pass.style.backgroundColor='lime';
var x = document.getElementById('passtext');
x.innerHTML='Password Valid';
}
}
}

function password2(entered)
{
with(entered)
{
if(document.regform.pass.value != entered.value)
{
document.regform.register.disabled=true;
document.regform.pass2.style.backgroundColor='red';
var x = document.getElementById('pass2text');
x.innerHTML='Passwords Must Match';
}
else
{
document.regform.register.disabled=false;
document.regform.pass2.style.backgroundColor='lime';
var x = document.getElementById('pass2text');
x.innerHTML='Passwords Match';
}
}
}
</script>
</head>
<body>
<center>
Use the form below to register at <br>
<form action = "reg_info.php" method = "post" name="regform">
<input type = "hidden" name = "reg258741" value = "reg258741">
Desired Username: <input type = "text" size = 20 name = "user" id="user" onkeyup="username(this);"><div id="usernametext">Username between 5-32 characters.</div><br>
Desired Password: <input type = "password" size = 20 name ="pass" onkeyup="password(this)"><div id="passtext">Password between 5 - 30 characters</div><br>
Repeat Password: <input type = "password" size = 20 name = "pass2" onkeyup="password2(this)"><div id="pass2text">Password must match with before</div><br>
Email: <input type = "text" size = 20 name = "email" id="email" onkeyup="emailvalidation(this);"><div id="emailtext">Your email must be valid!</div><br>
<input type = "submit" id="register"value = "Register!">
</form>
</center>
</body>
</html>

ajax.php
<?php
require("config.php");
mysql_select_db($db, $con);
if ($_REQUEST['function']=="CheckUserName"){
$query = "SELECT count(*) FROM Account WHERE username = '{$_REQUEST['username']}'";
$result = mysql_query($query) or die("alert('Database error: ".mysql_error()."');");
$row = mysql_fetch_row($result);
if ($row[0]>0){
echo "document.getElementById('usernametext').innerHTML = 'That username is already taken.';";
}
else
{
echo "document.getElementById('usernametext').innerHTML = 'That username is valid and can be taken.';";
}
}
?>

 

I donno what to do because it works fine just the ajax.php echo statements dont seem to work. i used FF error console nothing popped up. note div wont change if the username is or is not taken.

Link to comment
Share on other sites

i am seriously confused as to what the problem is, so here is the updated code that i tried doing.

 

Form

<html>
<head>
<title>
- Registration
</title>
<script type="text/javascript">
function getHTTPObject() {
var xmlhttp;
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
var http = getHTTPObject();

function emailvalidation(entered)
{
with(entered)
{
apos=value.indexOf("@");
dotpos=value.lastIndexOf(".");
lastpos=value.length-1;
if (apos<1 || dotpos-apos<2 || lastpos-dotpos>3 || lastpos-dotpos<2)
{
document.regform.email.style.backgroundColor='red';
var x = document.getElementById('emailtext');
x.innerHTML='Your email is invalid!';

}
else
{
document.regform.email.style.backgroundColor='lime';
var x = document.getElementById('emailtext');
x.innerHTML='Your email fits validation, but it need to be valid for activation!';
http.open('GET', 'ajax.php?function=CheckUserName$=username'+entered, true);
http.send(null);
eval(http.responseText);
}
}
}


function username(entered)
{
with(entered)
{
var username = entered.value.length;
if (username < 5)
{
document.regform.user.style.backgroundColor='red';
var x = document.getElementById('usernametext');
x.innerHTML='Username Too Short';

}
else if (username > 30)
{
document.regform.register.disabled=true;
document.regform.user.style.backgroundColor='red';
var x = document.getElementById('usernametext');
x.innerHTML='Username Too Long';

}
else
{
document.regform.user.style.backgroundColor='lime';
http.open('GET', 'ajax.php?function=CheckUserName&=username'+entered, true);
http.send(null);
eval(http.responseText);
<?php
if($_POST['taken'] == "yes")
{
?>
document.getElementById('usernametext').innerHTML = 'Username is Taken'
<?php
}
else
{
?>
document.getElementById('usernametext').innerHTML = 'Username valid and has not been taken.'
<?php
}
?>
}
}
}

function password(entered)
{
with(entered)
{
passwordlength = entered.value.length
if(passwordlength > 30)
{
document.regform.pass.style.backgroundColor='red';
var x = document.getElementById('passtext');
x.innerHTML='Password Too Long';
}
else if(passwordlength < 5)
{
document.regform.pass.style.backgroundColor='red';
var x = document.getElementById('passtext');
x.innerHTML='Password Too Short';
}
else
{
document.regform.pass.style.backgroundColor='lime';
var x = document.getElementById('passtext');
x.innerHTML='Password Valid';
}
}
}

function password2(entered)
{
with(entered)
{
if(document.regform.pass.value != entered.value)
{
document.regform.pass2.style.backgroundColor='red';
var x = document.getElementById('pass2text');
x.innerHTML='Passwords Must Match';
}
else
{
document.regform.pass2.style.backgroundColor='lime';
var x = document.getElementById('pass2text');
x.innerHTML='Passwords Match';
}
}
}
</script>
</head>
<body>
<center>
Use the form below to register at <br>
<form action = "reg_info.php" method = "post" name="regform">
<input type = "hidden" name = "reg258741" value = "reg258741">
Desired Username: <input type = "text" size = 20 name = "user" id="user" onkeyup="username(this);"><div id="usernametext">Username between 5-32 characters.</div><br>
Desired Password: <input type = "password" size = 20 name ="pass" onkeyup="password(this)"><div id="passtext">Password between 5 - 30 characters</div><br>
Repeat Password: <input type = "password" size = 20 name = "pass2" onkeyup="password2(this)"><div id="pass2text">Password must match with before</div><br>
Email: <input type = "text" size = 20 name = "email" id="email" onkeyup="emailvalidation(this);"><div id="emailtext">Your email must be valid!</div><br>
<input type = "submit" id="register"value = "Register!">
</form>
</center>
</body>
</html>

ajax.php

<?php
require("config.php");
mysql_select_db($db, $con);
if ($_REQUEST['function']=="CheckUserName"){
$query = "SELECT count(*) FROM Account WHERE username = '{$_REQUEST['username']}'";
$result = mysql_query($query) or die("alert('Database error: ".mysql_error()."');");
$row = mysql_fetch_row($result);
if ($row[0]>0){
echo "document.getElementById('usernametext').innerHTML = 'That username is already taken.';"; 
//note ive tired using echo "alert('Username exists')"; and nothing happens.
$taken = "yes";
return $taken;
}
else
{
echo "document.getElementById('usernametext').innerHTML = 'That username is valid and can be taken.';";
}
}
?>

 

im having problems getting the php variable to return back to the original form page so i always get the that username isn't taken div appearing.

Link to comment
Share on other sites

  • 3 months later...
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.