Welcome to Lieben Knowledgebase!

form input check against mysql db with js and or ajax and php

Question/Problem:

i have a form:

<input type=text name=login>

how do i check if what the user enters, already exists in the database, without them having to submit the form first? ie: live checking when focus of the input box is changed.

the database is mysql, table name is gebruikers.

story: a new user enters his login name in a form, and has to be notified if the name is already in use before submitting the form.

Please only complete and ready to use examples, because I'm very shitty at JS/Ajax :)


The answer/solution:

here's the first part, client side code on your page

<html  >
<head>

    <script>

      var theLogInBox;
     
      //From: http://www.degraeve.com/reference/simple-ajax-example.php

      function CallAJAX(theUrl)

      {

            var xmlHttpReq = false;
            var self = this;

            // Mozilla/Safari

            if (window.XMLHttpRequest) {

                  self.xmlHttpReq = new XMLHttpRequest();

            }

            // IE

            else if (window.ActiveXObject) {

                  self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");

            }

            self.xmlHttpReq.open('GET', theUrl, true);

            self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

            self.xmlHttpReq.onreadystatechange = function() {

                  if (self.xmlHttpReq.readyState == 4) {

                        DisplayResult(self.xmlHttpReq.responseText);

                  }

            }

            self.xmlHttpReq.send();

      }

      function CheckLogInName(theBox)
      {

            theLogInBox = theBox;

            CallAJAX("CheckUserName.php?userName="+theLogInBox.value);

      }

     
      function DisplayResult(theText)

      {

            if(theText == "TAKEN")

            {

                theLogInBox.style.color = "red";

            }

            else

            {

                theLogInBox.style.color = "green";

            }

      }     

</script>
</head>

<body>

    <form>

        <input type=text name=login id=login onchange="CheckLogInName(this)">

    </form>

</body>

</html>

 

The second part, server side php file

Now you need to write CheckUserName.php.  All you need to do for this is get the parameter userName.

 

All this needs to do is return a simple string.  If the username is taken, return "TAKEN" if it's free return anything else that doesn't match"TAKEN" and it will work.

This is done with the echo statement, so, make a mysql query that checks if the name exists, if it doesn't, make your php file echo anything you want, if it does, echo "TAKEN", for example:

<?php

yourquery

if(queryresult == "") {

echo "free";

}else {

echo "TAKEN";

}

?>


added by Jos on: 26-04-2007



keywords: PHP, ajax, javascript,


©2009 by Lieben.nu