Forum Moderators: open

Message Too Old, No Replies

Check POST information against Database

Need Help With Javascript Function to check database

         

jaknmekh

5:02 pm on Jan 10, 2008 (gmt 0)

10+ Year Member



Howdy,

My name is Robert and I am trying to write a javascript function to onsend check my mysql database for duplicate information.

I am basically making a admin panel with AJAX and when I go to add a user I want to make a javascript function that checks my database to make sure the username is unique.

Can someone help me?

Thanks,
-Robert

gergoe

6:21 pm on Jan 10, 2008 (gmt 0)

10+ Year Member



Hello Robert!

What you basically need is two things:
1.) A server-side script (written in any language, probably php in your case?), which runs an sql query against the database and returns a true or false value based on the result. This script check the duplicate name. returning value here means, that you output (either xml, either normal text) to the 'browser'.

2.) A javascript function which creates an xmlrequest object, initiates a request to the page described in point 1, and evaluates the response. Based on the received response you can take further actions, display a warning message, color the field red, etc.

The first one is probably not a difficulty, while the second is a bit more difficult. But i understand from your email that you are familiar with AJAX already, probably already using some AJAX library too, so maybe the second is not difficult either.

A rough example how you could do this:
test.php

<?php 
//mysql_connect(...);
//mysql_select_db(...);
if (isset($_REQUEST['username']) &&
!empty($_REQUEST['username'])) { 
if (($CountRow = @mysql_fetch_row(@mysql_query("SELECT COUNT(*) FROM users WHERE username = '". mysql_real_escape_string($_REQUEST['username']). "'")))
!== false) { 
echo $CountRow[0]==0?'true':'false';
} else echo 'false';
} else echo 'false';
?>

The javascript function:

<script language="javascript" type="text/javascript"> 
function checkUsername(username){
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open('GET', 'test.php?username='+username, false);
xmlhttp.send('');
if (xmlhttp.status == 200) {
return xmlhttp.responseText.indexOf('true') == -1;
} else return false;
}
</script>

Then you can call from your form's onsubmit handler the checkUsername function with the username as parameter, and if it returns true, then there's no such a username yet.

jaknmekh

6:32 pm on Jan 10, 2008 (gmt 0)

10+ Year Member



Amazing!

Thanks!

I figured thats how I would do it but I needed confirmation...

My only question is how does the XMLrequest know whether the output is true or false if the php script isnt outputting a XML response?

jaknmekh

8:58 pm on Jan 10, 2008 (gmt 0)

10+ Year Member



Ok, I am still somewhat new to javascript...

How would I alert if it returns false?

The whole return true or false thing confuses me.

d40sithui

10:05 pm on Jan 10, 2008 (gmt 0)

10+ Year Member



Robert,
Gergoe's example is a basic rundown of the programming syntax needed to accomplish what you're doing. You will most likely need to expand that further. check [w3schools.com...] for a brief refresh of AJAX. Their example is more simple than gergoe's =p.
To make things simple, you will need 3 javascript functions, and one php script (or asp, whatever you prefer). you can easily expand their example to what you're trying to do. in the end, you can end up just typing in the username and an auto message will print if the username is a duplicate. cool eh? Post here if you need any more help.

gergoe

11:52 pm on Jan 10, 2008 (gmt 0)

10+ Year Member



Their example is more simple than gergoe's =p.

lol, I consider this as a compliment ;-)

Regarding to jaknmekh's first question;
You can read the response from the xmlrequest object as XML (more usual), but you can read it as text too, regardless of the actual content type. If the request comes back with an XML structure, you can choose to read it as text (then you get a string back with the XML in it), and as XML, but then it becomes slightly more complicated, because you need to use the DOM model to read the values back. Although the second is the preferred (XML with DOM), I chosen the plain text approach, to make the example a bit simpler (but I did not succeed on that it seems).

So back to the question, from where does it know? The php script outputs a string, either 'true' either 'false'. In the javascript function I read the response as text (using the responseText property), which returns with a string ('true' or 'false' to stick to this example), and with indexOf I evaluate the that string. If it does not contains the word 'true' (please note that true is in quotes, so it is not the logical true, but a string!), then the function returns true, indicating that the given username is already occupied. Just for your information, I used indexOf because this way newlines or other characters does not affect the proper evaluation.

The second question;
You are right, the fast that I used the *words* true and false in the php script, made it very confusing, I should have been chosen something else. But anyway; The return value of the checkUsername function which matters, and that returns a (real) logical boolean value. So in your form's onsubmit you can do this:

if (checkUsername(formObj.username.value)) alert('Wrong username!');

To make it less condensed (and hopefully less confusing):

var result = checkUsername(formObj.username.value); 
if (result == true) alert('Wrong username!');

So the answer to both of your questions; true and 'true' is two very different things, the first is a logical true (boolean), while the second is a four character long string.

gergoe

12:04 am on Jan 11, 2008 (gmt 0)

10+ Year Member



Just a note about the recommended examples on w3schools (which is indeed a good source for AJAX development): You should not use asynchronous xml request in your case, because you are doing this whole check while the form is being submitted, that would make things very funny if you do so. The request would have been sent to the server (to check the username), but the form checking would continue with an unknown result (because there's no response yet), and the response to the username request would arrive (but it won't) when the form was already posted to the database.

When working with onsubmit and similar event handlers (like onunload for example), you either need to use blocking request (they only return, when the request has been completed), or cancel the form sending (return false to the onsubmit), and in the xml event handler (the stateChanged function in the w3schools example) you'll post your form once again - if the username is not in the database yet.

In any case, you will certainly need to dig yourself into javascript, XML, DOM and all related technologies/languages, if you are going to make a whole application using AJAX...

jaknmekh

12:19 am on Jan 11, 2008 (gmt 0)

10+ Year Member



Thanks very much, I got it working like a charm!