For absolutely no reason whatsoever, I decided to create a simple example of AJAX, based on the framework I layed out in an earlier post.
The goal of this AJAX example is to allow a user who is registering for your site to see if the username they want to use is taken already or not, without having to submit a form and reload the page. I believe Digg uses this, and I hear it’s all the rage for Astronomy-based dating sites. You can skip to the implemented example in action here. Yeah, I did it in ASP this time, instead of PHP…FOR NO RAISIN WHATSOEVER, except maybe to show that the same JS framework works for both ASP and PHP.
First, I constructed the ASP page that will do the dynamic checking. It should take one querystring (GET) parameter, in this case “username”, and print out a message regarding whether or not that username is taken, or if it’s invalid. Here’s the gist of it:
'if there's a space in the username, it's invalid
if InStr(request("username")," ") then
response.write "TakenOrNot|Spaces are not allowed in usernames, please try again."
else
'database stuff
dim strConn, dbConn, RS
'...set up your connection string here (MySQL, MS-SQL, whatever)
dbConn.open(strConn)
'query the database
set RS = dbConn.execute("SELECT count(*) AS cnt FROM blog_comment " &_
"WHERE username = " & request.querystring("username"))
'is this name taken or not
if RS("cnt") > 0 then
response.write "TakenOrNot|Sorry, " & request.querystring("username") &_
" is already taken. Please try a different one."
else
response.write "TakenOrNot|" & "Congratulations! " & request.querystring("username") &_
" is available for you to use."
end if
end if
So, depending on the username, this ASP code will print 1 of 3 possible strings.
The next thing I did was to write a new function in my ajax.js file. This is very similar to the sndReq() function from before:
// this function should be called for user input
// it opens up the usercheck.asp page with a querystring of 'action'
function sndUserCheck(action)
{
http.open("get", "usercheck.asp?username=" + action);
http.onreadystatechange = handleResponse;
http.send(null);
}
So, whenever this function is called, it will send an XMLHttpRequest to usercheck.asp using whatever username string was specified by whatever is calling this function. Not much different than sndReq(). One could probably abstract this function out even more to make the ASP/PHP page name a parameter as well, but for simplification, I won’t do that.
Finally, I set up the interface page:
<HTML> <TITLE>AJAX Username Checker Example</TITLE> <!-- AJAX functionality --> <script type="text/javascript" src="ajax.js"></script> <BODY> <form name="FormAccount"> <input type="text" id="formUserName" name="formUserName"> <input type="button" value="Check" onclick="sndUserCheck(document.FormAccount.formUserName.value);"> </form> <br><br> <div id="TakenOrNot"></div> </BODY> </HTML>
Again, not much different than the original example. We have one text box, where the user types in the name they want to check (formUserName), we have one button that will they will click to do the checking (formCheck), and one div object that will display the response message. Note that we grab the user’s text input for the sndUserCheck function like so:
document.FormAccount.formUserName.value
Note the use of the FormAccount (the name of the form) and formUserName (the ID of the text box)
That’s all there is to it! Users are now able to look up a username in your database and give a response to the user without a refresh. You can download the source code for this example below.
Digg this story
I got something similar to work (for no reason whatsoever). The problem is you could potential enter a space and/or invalid username, it would say it’s available, and then your full form submission error-checking would catch it and say “no dice”. The one on Digg seems to do some validation in addition to the db check.
Yes, as does my above example. I check to see if it has a space, and show an error. That could be expanded to whatever other checks you want to do.
ajax
i expected more.
What else did you expect?
i got some error like “permission denied” who so ? Give me reply to my mail
Hello, thanks for this usefull tutorial, I test it in IE and works fine, but Don’t work in Fire Fox. ¿?, may be it’s easy to fix, I think it’s the function handleResponse(),… document.getElementById(update[0]), but not sure i’m starting learn javascript. Regards, Joan
It may be the actual browser detection part of the script. If it somehow thinks that the browser is IE, it will attempt to use ActiveX, which obviously won’t work if it’s not IE.
To fix this, better browser detection code would be necessary.
Why mix Java into this ? it works perfect with plain asp, in fact it startet to work when I removed all Java
Firstly, it’s JavaScript, not Java. And I don’t understand how it would work without JavaScript, unless you are directly using the lookup ASP page.
test ,i want to study this technoledge
Cool tutorial, I think it would improve the usability if you bound the sndUserCheck function call to the onblur event of the textbox rather than having a separate button for it.
That’s certainly one thing you could do: however each call to sndUserCheck will result in a seperate SQL call, meaning that there could be multiple SQL connections for each user. If there was then a high amount of traffic, there would be a huge performance hit.
Besides the performance hit, you forgot to seperate or explode the response into two variables… one for the id of the div element and the other for the innerHTML.
Maybe I glossed over that Seth, but if you check out http://mgroves.com/A-simple-AJAX-example you’ll see that I didn’t forget. It just explodes with “|” as the delimeter, though it would work equally well no matter what delimeter you want to use.
The above code helps me a lot
Thanks
I can’t seem to get it to work in a php page rather than asp.
Any chance you could post code?
Thanks
Sarah, when I blogged about the original framework, I used ASP. The Javascript and HTML remains the same no matter what scripting language you use:
Check it out at http://mgroves.com/A-simple-AJAX-example
Hi every body,
i have some problem with the script:
“The document.getElementById(update[0]) has no properties”
[javascript snippet removed]
And query.php thank’s for your help
Abid
[php code snippet removed]
Walou, please just post the code where you are having the problem.
Walou — I removed your code, but I did look at it. The PHP response must be in the format “id|content”, where “id” is the HTML element you want to update, and “content” is what you want to update it to.
How can I make it work for access database?
Thanks!
This method is independent of the database you use. So however you normally open your DB from a web page is how you do it here. The JavaScript code does not directly touch a database, so you can use MySQL, MSSQL, Access, Oracle…whatever.
Thanks so much, just got this to work, thanks again!!
Really its amazing
It’s more than amazing. It’s wondrous.
What’s amazing is the lack of complaints I get about this post despite the terrible formatting.
sorry but wheres the code to be downloaded?
Sorry to make it confusing, but it’s right under “Attachments”. Or here’s the direct link: http://www.mgroves.com/documents/AJAX_usercheck.zip
Thanx mate but some of ur blogs need editing for the MOD-rewrite engine implementation. I had to logically deduce the real url by breaking down the link title.
HMMMM.. ok thanks for the ajax help and, what ever that last post was.
Indeed!
Thank you For Ajax Help.
i am newer in to the ajax field how can i staart to load this code in to my page will you please tell me i don`t know anything about ajax and jsp plz help me ….
very interesting, but I don’t agree with you
Idetrorce
take that mgroves.com, someone doesnt agree with you, theres a new one
It’s because his code has a conservative slant.
Out of all the blog posts to disagree with, this seems like it should be very low on the list…
Thanks a lot – I learned A LOT by this example. Been using fxmods opensource with a terrible username validation. Doing some cleanup with ajax, was very much worth it.. Merry X.mas and a happy new year
Greetings from Denmark
Jan
Hello there,
My name is Nadina and I work for Soft5000.
We just added Ajax Username Availability Checking to our database. You can see the script details here:
http://scripts.soft5000.com/download154.html
We ask you if you can, please add our link http://scripts.soft5000.com to your references page.
Thank you and hope to see more of your products launched soon,
Nadina
Hello everybody, my name is Damion, and I’m glad to join your conmunity,
and wish to assit as far as possible.
hello my name is minywheats and groves sucks
hi any idea about AJAX-Form Save and reload.
hi how are you?
i want to know how i can check the availabilty for a room in a hotel reservation system by using JSP