Script Perfect

         Random snips of code and bugs

Ajax – A Squeeky Clean Website

Posted by Tim On September - 8 - 2009

Ajax, not the cleaner, the asynchronous JavaScript and XML, it is like viagra for your website. Pop in a little Ajax and your website is performing better and making your “visitors” happy. As with viagra you need to read the warning labels associated with Ajax.

Warning:

Ajax should be used in moderation. If your server maintains a full load for more than 4 hours as a result of using Ajax, you should consult a programmer immediately. Websites hosted on shared servers or those intending to move to a shared server should not use Ajax as this may cause complications during deployment.

Seriously though, over use of Ajax can cause a lot of load on your server if you are processing too many requests at the same time, often the requests that tax the server the most include database queries. Don’t get me wrong, I love Ajax and I think every site could put it to good use. This is why I am going to show you a few simple methods to implement it on your site to make your visitors time more enjoyable.




Asynchronous JavaScript and XML, it is a little misleading, you do not really need XML, nor do you need JavaScript, come to think of it, it does not need to be asynchronous either. There have been some releases of API’s which allow you to use Ajax without JavaScript, not really sure why anyone would want to go this route as it is not as powerful. Most commonly we will use XMLHttpRequest to exchange our information.


Our Scenario

This is one of the most useful scenarios I can think of at this particular time, considering the lack of caffeine flowing through my veins I think it is a good one. How many times have you gone to register on a website to find that your user name was taken? Out of those times how many times did you have to submit the form over and over again until you found a user name that was not taken? Through the use of Ajax we can check if a particular user name is available while we type.

This method is very easy, we will start with our php which will query the database and tell us if a particular user name is available.

checkname.php

$username = $_POST[‘username’];
$result = mysql_num_rows(mysql_query("SELECT * FROM users WHERE username=’$username‘"));
if ($result==0) {
       echo ‘Available!’;
} else {
       echo ‘Taken!’;
}

The code above simply takes a value “username” which was posted and checks if it already exists in our database. If the username entered exists we echo “Taken”, otherwise we echo “Available”.

So now we need a form and a JavaScript function which will post data to the php script we just created. What we will do is this, every time a key is pressed inside our text input we will call a JavaScript function called “checkname” which will post the value of our input to our checkname.php file.

Please enter a user name:<br/>
<input type="text" id="username" name="username" onkeypress="javascript:checkname();" />
<div id="results"></div>

A simple input box with a call to a JavaScript function. We also added a DIV on the page with the id “results”, this is where we will post the results of our query. All that is left now is the function which will actually gather the data from the page, post it to our php file, then return the results to our DIV.

The Listener

Something almost all women wish men would do, listen… We need to put a listener into place to see if anything is being parsed back to our page. Since browsers are different and handle the data being sent to them differently we need to account for both of them. Here is how:

function createXMLHttpRequest() {
        if (typeof XMLHttpRequest != ‘undefined’) {
                return new XMLHttpRequest();
        }
        try {
                return new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
                        try {
                                return new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e) {}
        }
        return false;
}

This function creates an XMLHttp request, which will not only send our data but also receive it. So it is a good talker and listener, who needs that viagra now? O.k. So the final part in this equation is to gather and post the data, we can do that with our function “checkname()”.

function checkname() {
                var new_request = createXMLHttpRequest();
                var username = document.getElementById("username").value
                postvalue = ‘username=’ + username;
                new_request.open("POST","checkname.php", true);
                new_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
                new_request.onreadystatechange = function() {
                        if(new_request.readyState == 4 && new_request.status == 200) {
                                document.getElementById("result").innerHTML = new_request.responseText;
                        }
                }
                new_request.send(postvalue);
        }

There it is, the function that will collect and post our data as well as place a reply inside our DIV tag. Here is how it works:

  • First we create a new XMLHttp Request which will handle our sending and receiving of the posted values.
  • We set a variable called “username” to equal that of the value of the input in our form.
  • We set “postvalue” to equal ” ‘username=’+username which sets our $_POST['username']
  • Next our connection to “checkname.php” is set and ready to accept data
  • Since our browser has not detected a change in state e.g. readystate 4 and status 200 we skip over this conditional statement.
  • And we send our username over to our php file.
  • Once we receive a response (readystate 4 and status 200) we update our DIV with its contents.
  • The contents of our DIV is set to the response from our php file, so if it found the user name it would read “Taken” and if the name was not found it would read “Available”. This process takes place every time the user presses a key to input a new name into our input field.

    Cleaning Up

    As with any good night on viagra or a good night with coding there is always some form of cleanup. The code above will demonstrate how to send and receive via Ajax but it is not complete. We are not escaping any values posted and there is plenty of room for errors when posting erroneous data which means you will need to check your data before sending it to your php file.

    Doctors Warning

    Over use of Ajax can cause your site to run slow, it is great for the client side but can really bog down your server if too many requests are being made at the same time. Use this tool wisely and try not to overdo it, especially if you are on a budget host.

    It has been more than four hours so I am off to seek medical erm…

    4,018 Responses to “Ajax – A Squeeky Clean Website”

    1. IRS Tax Tips…

      although the sites we link to listed here are completely unrelated to ours, we feel they are worthy of a read, so have a glance…

    2. EDU Auto Approve List…

      [...]Auto Approve List[...]…

    3. Steve’s Blog…

      [...]we like to recognize alternative online sites on the web, even if they aren’t associated to us, by linking to them. Underneath are some web pages worth looking into[...]…

    4. best says:

      Baby Bedding…

      [...]here are some links to sites that we link to because we think they are worth visiting[...]…

    5. Get The New iPad 2 this friday…

      [...]the time to read or visit the content or sites we have linked to below the[...]…

    6. Goverment Articles…

      [...] within come across the url having a blogs which i look it is advisable you can check [...] …

    7. Great internet information…

      [...]has always been one of my favorite bloggers, the link is below if you’ve never been there before today[...]…

    8. Mint says:

      Interesting Commonality…

      [...]please visit for prior reference, as this is quite important to our mission[...]…

    9. Asil Chicken says:

      Araucana Chicken…

      [...]Sites of interest we like to link to[...]…

    10. how to burn stomach fat…

      [...]the time to read or visit the content or sites we have linked to below the[...]…

    11. How to Quit Smoking Weed…

      [...]here are some links to sites that we link to because we think they are worth visiting[...]…

    12. Jake’s Blog…

      [...]just under, are quite a few absolutely not related sites to ours, however, they are definitely worth looking into[...]…

    13. [...]we like to honor other sites on the web, even if they aren’t related to us, by linking to them. Below are some sites worth checking out[...]…

      [...]the time to read or visit the content or sites we have linked to below the[...]…

    14. tegaderm…

      [...]I am linking to this istes because I am thinking how much I like to get backlinks and they worth it[...]…

    15. Travel Offers…

      [...]These subsequent websites are actually a few online sites which attracted our administrator, therefore remember to have a look at all of them[...]…

    16. What Is Tinnitus Miracle …

      [...]although the sites we link to here are not completely related to us, we think they are worth a read, so[...]…

    17. Taylor Armstrong Tells You It’s A Great Piece Of Writing Keep It Up?…

      Below might be a few other tips one may be interested on… well done…

    18. Customer Service Software Reviews…

      [...]while the sites we link to below are completely unrelated to ours, we think they are worth a read, so have a look[...]…

    19. Travis on his way to hollywood?!…

      [...]do you know that we were looking for this, johny was too[...]…

    20. [...]while the sites we link to below are completely unrelated to ours, we think they are worth a read, so have a look[...]…

      [...]just below, are some totally unrelated sites to ours, however, they are definitely worth checking out[...]…

    21. Tinnitus Miracle …

      [...]we like to honor other sites on the web, even if they are not related to our site, by linking to them.[...]…

    22. Background Check…

      [...]the time to read or visit the content or sites we have linked to below the[...]…

    23. Rob Rasner says:

      Rob Rasner Says Its An Incredible Post Keep It Up…

      [...] Neat news thought we might include some not related data, although really worth having a look [...]…

    24. hdc-tm700k says:

      HDC-TM700K…

      [...]below you may find the link to a couple of sites we think you should visit[...]…

    25. Highly Recommended…

      I enjoy what you guys are up too. This kind of clever work and coverage….

    26. Joe says:

      Site…

      [...]here are some links to sites that we link to because we think they are worth visiting[...]…

    27. Weight Loss Help Online…

      [...]just below exist a couple hyperlinks to sites that I link to due the to fact that I posit that those sites are worth reading[...]…

    28. 1.) Home Security…

      2.) [...]here are some links to sites that we link to because we think they are worth visiting[...]…

    29. 1.) Protecting your home…

      2.) [...]every so often I come across a site that I actually like to read and this is one[...]…

    30. Anonymous says:

      Hotel Safe…

      [...]the time to read or visit the content or sites we have linked to below the[...]…

    31. Breast Actives before and after…

      [...]i suggest you check out this website[...]…

    32. Learn About Colon Cleanse…

      [...]the time to read or visit the content or sites we have linked to below the[...]…

    33. Best Sites to Visit…

      [...]just below, are some totally unrelated sites to ours, however, they are definitely worth checking out[...]…

    34. Games For Girls…

      [...]here are some links to sites that we link to because we think they are worth visiting[...]…

    35. Tinnitus…

      [...]here you will find the url to a couple sites that we think you should visit[...]…

    36. Buy Yankee Candles at Half Off…

      [...]the time to read or visit the content or sites we have linked to below the[...]…

    37. Russell Armstrong Says It’s An Excellent Posting Well Done?…

      [...] Take time to see this some may represent interest also, [...]…

    38. 1.) Home Security…

      2.) [...]here are some links to sites that we link to because we think they are worth visiting[...]…

    39. 18th birthday ideas…

      [...]we like to link to other sites out there on the web, even if they aren’t related to us, by linking to them. Below are some sites worth checking out[...]…

    40. Flax Seeds Benefit…

      [...] we like to honor other sites on the web, even if they aren’t related to us, by linking to them. Below are some sites worth checking out. Posted in [...]…

    41. Boat Sales says:

      really agreed with what they were saying and thought I would share it with you all…

      was surprised by this so thought I would share it with my readers…

    42. הכרויות בטלפון…

      [...]here are some links to sites that we link to because we think they are worth visiting[...]…

    43. Cieaura Suggests It is A Fantastic Write-up Cool…

      Take some time to read these some may be fascination as well……

    44. Wrinkle Cream Critic…

      [...]below you’ll find the link to some sites that we think you should visit[...]…

    45. Hawaii Travel…

      [...]below you’ll find the link to some sites that we think you should visit[...]…

    46. Smoked Salmon Gift Baskets…

      [...]while the sites we link to below are completely unrelated to ours, we think they are worth a read, so have a look[...]…

    47. New Mesothelioma Site…

      [...]while the sites we link to below are completely unrelated to ours, we think they are worth a read, so have a look[...]…

    48. 1.) Keys, locks and more…

      2.) [...]we came across a cool site that you might enjoy. Take a look if you want[...]…

    49. Sites we Like…

      [...] Every we find blogs that we follow. Listed below are the newest sites that we choose [...]…

    50. Wedding Invitations…

      [...]below you’ll find the link to some sites that we think you should visit[...]…

    Leave a Reply

    Spam protection by WP Captcha-Free

    About Me

    I am an independent web developer and webmaster of many sites. The main goal of Script Perfect is to provide answers to some of the hard to find questions when it comes to website design and coding.

    Twitter