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…

    11 Responses to “Ajax – A Squeeky Clean Website”

    1. Netcom3 says:

      Registry Cleaner Procedure…

      Answering the question of “How to clean my registry” could be as simple as choosing either to do it manually or to utilize software program. Doing it by hand actually entails intervening in the editing process by yourself. Now, should you continually…

    2. casino en ligne…

      Partage des revenus 50% 2….

    3. casino en ligne…

      [...] C’est toujours une sign. [...]…

    4. Make your own life time easier get the credit loans and all you require.

    5. Why NUVIGIL builds on the success of Modafinil…

      General Information on Nuvigil and Modafinil I think many of us have already experienced conditions of periodic sleepiness during the day……

    6. The largest and best club for insomnia…

      Here is the club of the loser of sleeping. We supply the most abundant knowledge about insomnia and help you get rid of it soon….

    7. proactol for easy weight loss…

      Proactol like a healthy way of making it easier to take charge of your easy weight loss and eating habits. …

    8. Download best free registry cleaner tools online For Windows XP….

      This is a best free registry cleaner tools blog….

    9. 10 lose weight fast tips…

      In this article, lets take a look at how to lose weight effectively. Losing weight effectively means eating healthily and reducing your daily calorie…

    10. Purchase mp3 music online…

      Because of reading your blog, I decided to write my own. I had never been interested in keeping a blog until I saw how fun yours was, then I was inspired!…

    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