Organic Search Engine Optimization (SEO) Solutions. Call now on 0879807629 or contact us via email
AKA Marketing.com Logo

Blogged thoughts, is our web blog. Expect views, opinion, rants and tirades about everything and anything 

« Home / Services / Forums »        

Subscribe to our SEO / IT related blog by entering your email address below

Blogged thoughts

| by the www.akamarketing.com team



Ajax example - staff directory search with PHP & C# ASP.Net

Ajax in a nutshell is a set of technologies which allow for partial page updates without requiring the whole page to refresh after communication with the server. Usually when a visitor is on a webpage and clicks a link or a button the whole page is reloaded (and the browser window goes white) before the user can see the updated page back, however with Ajax the user could see the specific results of the link/button click almost immediately as only the relevant section of the page is updated. What Ajax (the frontend) updates the page with is usually based on what it passes to the server (backend).

Ajax uses Asynchronous communication to allow this type of update to a page. Asynchronous communication in this context basically means that the loading of data/information (for example results from an SQL Query) for display in a specific section of the web page does not interfere with the normal loading of the web page and thus the page will not freeze or go white as is normally the case. The idea with Ajax is to give the end user a much better experience. This better experience comes from increased responsiveness/speed and usability.

Have a look at the following two pages (which open in new windows) which provide the user with the ability to lookup contact details for staff of a dummy company called HollyWood MovieStars Ltd.

Standard search interfaceAjax enabled search interface (have a sneak at the source if you want)
TIP - Search for one of the vowels first.

The first page is a standard search interface where you enter in your query, press search and watch as the whole page posts back, reloads and gives you back your search results. The second page is an Ajax enabled search interface which returns results almost immediately as soon as you start typing your query - without requiring a whole page reload. I know which one would make me the happier end user.

In this post I’ll present a step by step example of how to use Ajax to create a much more responsive and user friendly interface than is possible with the regular request and wait protocol we are all so familiar with. The interface I’m actually going to put together is the Ajax enabled one shown above. As you can see it basically allows a user to quickly look up the contact details of a member of staff by sub string searching on their name information which is stored in a database somewhere. I’m tagging this one as a staff directory search but it could just as easily be used to find details for club members, clients etc. The important thing is the underlying concepts and not what it’s actually used for. 

The actual Ajax code which communicates with the server is written in Javascript and thus the frontend of this interface will just be a standard webpage (.html extension) with a mixture of Javascript/HTML and a touch of CSS/DHTML too. For the backend - which does the actual SQL query database lookup based on what the Ajax frontend passes to it and returns results I will provide summary code in both PHP and C# ASP.Net. You could actually use the exact same PHP or C# ASP.Net code to run both a standard click and wait search interface and an Ajax enabled one (if you set the form method to GET on the standard search page) so there is definitely nothing special about the backend in this case and thus summary code and summary explainations are all that’s needed for the backend in this case.

XMLHttpRequest
Let’s begin with the object that makes everything Ajax possible. The XMLHttpRequest javascript based object is the actual mechanism that allows independent asynchronous communication between client and server. Without it Ajax would not exist. As you can see from the XMLHttpRequest Wikipedia page the object has a number of methods (actions) and properties (values) available to it. The most important methods include Open() and Send(), while the most important properties are onreadystatechange, readyState, status and ResponseText at least for this example anyhow. OK let’s see some code and then I’ll offer a line or two on the above methods and properties as we come across them. The function below is your bread and butter Ajax client to server communication code…

  1.  function getText(urlToCall, functionToCallBack, divToUpdate)
  2. {
  3.    
  4.     var XMLHttpRequestObject = false;
  5.  
  6.     //will exist in navigator, firefox & safari
  7.     if (window.XMLHttpRequest)
  8.     {
  9.           XMLHttpRequestObject = new XMLHttpRequest();
  10.     } 
  11.     //will exist in explorer
  12.     else if (window.ActiveXObject)
  13.     {
  14.          XMLHttpRequestObject = new
  15.          ActiveXObject(“Microsoft.XMLHTTP”);
  16.     }
  17.  
  18.     //if object was created successfully
  19.     if(XMLHttpRequestObject)
  20.     {
  21.             XMLHttpRequestObject.open(“GET”, urlToCall);
  22.             XMLHttpRequestObject.send(null);
  23.  
  24.             XMLHttpRequestObject.onreadystatechange = function()
  25.            {
  26.                  if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
  27.                 {
  28.                     functionToCallBack(XMLHttpRequestObject.responseText, divToUpdate);
  29.                     delete XMLHttpRequestObject;
  30.                     XMLHttpRequestObject = null;
  31.                 }
  32.            }
  33.     } //end if object created
  34.  
  35. } //end of function
  36.  

Lines 6 through 16 are what actually creates a new instance of a XMLHttpRequest object for use later in the function. How the Javascript creates the object depends on what the current browser is. This is required as Internet Explorer creates the underlying object differently than most other browsers.  

Line 19 simply checks if the earlier logic to create the XMLHttpRequest object was successful, and if this is the case it calls the open() method of the object. This is a very important method and is used to inform the XMLHttpRequest object of the location of the backend script (urlToCall) to call and communicate with. It also specifies the mode of communication, the most common modes of communication are POST and GET. How you pass data to the backend script depends on what option you select as the mode of communication, in this case this is set to GET - meaning we will pass data (whatever the searcher types into the search box) via query strings embedded into the url of the backend script (urlToCall) which we want to communicate with. It is important to note that no actual communication with the server has begun - open() simply specifies information about an async request which is about to happen, thus in this way the use of the word open is perhaps misleading.

Line 22 is what actually kicks things off, it does this by sending the request to the backend script as specified by the urlToCall parameter. Referring back to our XMLHttpRequest Wikipedia page we notice that the send method can take one parameter called content. This parameter is used to specify the data to send to the backend script if we set our mode of communication to POST. The backend script would then by able to access this data in a standard way such as $_POST['data'] in PHP or Request.Form["data"] in C# ASP.Net. Since we are passing data via query params (GET mode) attached to the filename specified by urlToCall we only need to pass a value of null.

Next up we see the onreadystate change property which calls an anonymous function everytime the state of the request changes. In the function both readyState and status are checked to make sure the request is a) complete and b) successful. The two magic numbers here are ‘4′ (readyState) meaning the the request is fully complete and ‘200′ (status) meaning the communication between client and server was successful.

Line 28 is just a standard Javascript function call to the function specified by functionToCallBack. The call passes in the text that was returned from the backend script via the XMLHttpRequest objects’ ResponseText property as well as the id of the div (or span/p etc.) element to update with the response. It is of course possible to handle the ResponseText right there in the anonymous function, however this is not a good idea as each Ajax application will be handling responses differently so it’s better to keep the getText function clear of any hardcoding and use specific embedded callback functions for each different page. Doing this will mean you can use the same getText function again and again in lots of different Ajax interfaces without modification.

Finally for the getText function lines 29 and 30 use good programming practice and dispose of now unneeded resources.

Incidentally the getText function I’ve used here is actually a slightly modified version of a function which is part of a very simple (but more often than not sufficient) Ajax framework which was originally included with an Ajax book I read called Ajax Bible written by a guy called by Steven Holzner. I thoroughly recommend the book to anyone wanting to get aquainted with Ajax and what it can do. As for the framework, it can be downloaded from http://www.akamarketing.com/scripts/ajaxutility.js, you will notice that getText is one of four functions available. By the way don’t be scared off by the word ‘framework’, a framework in the context of development is basically just a load of pre written code for you to use as a base, it’s nothing more and nothing less.

Displaying the response in the browser
The getText function as outlined above looked after the async client & server communication side of things and called another function on line 28 (commonly referred to as the callback function) when everything was done. The whole purpose of this callback function is to handle and display the response of the aforementioned communication. Let’s have a look at this very simple function now…

  1. //this function gets called when results are ready from the server side
  2. function callbackfunction(text, divToUpdate)
  3. {
  4.     //handle response in here, in this case we are just outputting it
  5.      document.getElementById(divToUpdate).innerHTML = text;
  6. }

I’m sure anyone used to fiddling with the DOM and/or DHTML can see what’s going on here. This code is basically instructing the browser to update the div as indicated by divToUpdate with the response outputted by the backend script and passed in via the parameter text.

Getting the ball rolling with user driven events 
You’ve seen how the callback function gets called from within the getText function, but how does the getText function get called in the first place? Good Question! The getText function gets called by tying it to some user driven event such as a button click, mouse move or keypress. You can see from the Ajax enabled search interface (the one we’re trying to make) that there isn’t a button in sight so we won’t be attaching a call to the getText function to an onClick event. Instead to enable getText to get called with each and every single keypress (and hence provide search results very quickly) in the query textbox we are using the onkeyup event. Here is the code we need.

  1. <input id=“query” onkeyup=“getText(’ajax-backend.php?query=’+document.getElementById(’query’).value+”,callbackfunction, ’searchResults’)” name=“query” type=“text” /> 

Notice that in this case the backend is PHP driven, also notice how we are embedding the search query into the backend filename. In this case the HTML element which we want to update with the server response has the id ’searchResults’. This means that a div, span, p or some other HTML element which exposes the InnerHTML property and has an id of ’searchResults’ must be present on the page or a Javascript error will occur. At this stage the client side frontend of our staff search interface is complete, you can get the full source by opening the Ajax enabled search interface page and selecting View >> Source from the toolbar. You may notice that the getText function is included in the frontend via an external JS file.

All that’s left to do now is to complete the backend code. The backend code is pretty standard issue stuff. Your basically checking for a query string param called ‘query’ and if it’s found your executing an SQL query (with the query string embedded) against a DB and simply outputting the results. The backend summary code is first given for ajax-backend.aspx (C# ASP.Net) and is then given for ajax-backend.php (PHP).

ajax-backend.aspx

  1. <!–Page Language=“C#”–>
  2. <!–Import Namespace=“System.Data.SqlClient”–>
  3. <script>
  4.     protected void Page_Load(object sender, EventArgs e)
  5.     {
  6.         //if something is in the query param do a LIKE search
  7.         //against the staff directory database and return results if any
  8.         if (Request.QueryString[“query”] != null)
  9.         {
  10.             string query = Server.HtmlEncode(Request.QueryString[“query”].Replace(“‘”,“””));
  11.             SqlConnection connection = new SqlConnection(“connection string in here”);
  12.             SqlCommand command = new SqlCommand();
  13.             SqlDataReader reader;
  14.  
  15.             command.Connection = connection;
  16.             command.CommandText = “select * from staff_directory where firstname like ‘%” + query + “%’ or…”;
  17.  
  18.             connection.Open();
  19.             reader = command.ExecuteReader();
  20.  
  21.             int count = 0;
  22.             while (reader.Read())
  23.             {
  24.                 Response.Write(
  25. <tr>
  26. <td>reader[0].ToString()….. etc. etc.”);
  27.                 count++;
  28.             }
  29.  
  30.             if (count == 0)
  31.             {
  32.                 Response.Write(“Sorry no results were found for your search”);
  33.             }
  34.         }
  35.     }
  36. </script>
  37.  
  38. <!– Stripped out all other output as frontend is handled by ajax-frontend.html –>

ajax-backend.php

  1. <!–r–>if(isset($_GET[“query”]) && $_GET[“query”] != “”)
  2. {
  3.  
  4.  $dbcon = mysql_connect(“localhost”,“username”,“password”);
  5.  
  6.  if (!$dbcon)
  7.  {
  8.    die(‘Not connected : ‘ . mysql_error());
  9.  }
  10.  
  11.  $db_selected = mysql_select_db(‘DB’, $dbcon);
  12.  if (!$db_selected)
  13.  {
  14.    die (‘Can\’t use foo : ‘ . mysql_error());
  15.  }
  16.   
  17.  //setup a query
  18.  $query = “select * from staff_directory where firstname like ‘%” . $_GET[“query”] . “%’ or lastname like ‘%” . $_GET[“query”] . “%’ or firstname + ‘ ‘ + lastname like ‘%”. $_GET[“query”] . “%’”;
  19.  
  20.  //execute the query
  21.  $get_results = mysql_query($query);
  22.  if (!$db_selected)
  23.  {
  24.    die (‘Query Error : ‘ . mysql_error());
  25.  }
  26.  
  27.  if(mysql_num_rows($get_results)>0)
  28.  {
  29.   $counter=0;
  30.   while($row = mysql_fetch_array($get_results))
  31.   {
  32.    $counter++;
  33.    echo “<strong>NAME</strong>: “ . $row[0] . ” “ . $row[1] . ” <strong>PHONE:</strong> “ . $row[2] . ” <strong>EMAIL:</strong> “ . $row[3] . ” <strong>SEX:</strong> “ . $row[4] . “”;
  34.   } 
  35.  }
  36.  else
  37.  {
  38.   echo “Sorry no results were found for your search”;
  39.  }
  40.  
  41. }
  42. ?> 

Neither the C# ASP.Net or PHP code given above is complete or production ready, both code samples do however provide you with a very good idea of what needs to go on from the backend point of view. Remember anything that you Response.Write() or echo out on the backend page will be returned to the client via the XMLHttpResponse objects’ ResponseText property.

Well that’s really it, with both the frontend and backend elements of an example Ajax interface covered you should now be able to implement something similar to suit your own needs, if not I hope I have at least provided you with a good basis for further research and remember if your stuck on anything please drop me a comment. In fact even if your not stuck please drop me a comment as I’d love to get your feedback on this post.

One Comment on “Ajax example - staff directory search with PHP & C# ASP.Net”
1| Peter Her said,

Your website provides very good information about staff search directory. However, I’m a beginner to create a staff search directory and would like to learn more about the process how to create both the frontend and backend, such as what tools can I use for developing frontend and backend? For example, if I need to create a staff search directory, how do I start and what are the steps? Any help will be much appreciated.

Leave a Comment
Name:
Email:
Website:
 
HOME | ABOUT US | CONTACT US | SITEMAP | GOOGLE SITE SEARCH | TOP
12 Lorcan Crescent, Santry, Dublin 9, Ireland +353 87 9807629