How to Search a Website Directory Asynchronously Using AJAX and PHP


Search Learning About Electronics

In this article, we show how to search a directory or multiple directories of a website asynchronously using AJAX and PHP.

The search text box above searches this website asynchronously and returns back relevant search results, all without the user having to refresh the page.

Google does the same thing. When you type in a search query, before you even hit the button, it's already returning results back.

The search engine above does the same thing.

Through AJAX, we can make asynchronous requests to the server to get information from the server such as files from a website directory. We can search through an entire directory or several directories to look for any type of file.

This way, a user can keep on working while information in a page updates without the page having to be refreshed.

So AJAX is a powerful language that allows us to send asynchronous requests to a server so that a browser can get information from the server without the page having to be refreshed.

In order for AJAX to work, 2 languages must be used, a client-side language (this is Javascript) and a server-side language such as PHP or The thing about AJAX is it allows a programmer to combine a client-side language with a server-side language to get the benefits of both and combine in them.

With AJAX, client side triggers can get server-side information.

So AJAX allows like the best of both worlds.

It's like Javascript being a client and server side language at the same time. But it's not Javascript working alone. It's javascript doing the client side work while making a request to the server (through the browser) to get information from the server (such as a database like a MySQL database). We then let a server-side language take over to get the server side information and return it to our page.

So this is the benefits of AJAX.

It allows us to update a page without refreshing because we communicate asynchronously with the server while a user continues to work.

So looking at the search box above, you see a standard text box that a user can type in a search query.

With AJAX, we can check the directory or directories that you want to to see if there are any files present that matches the query that the user has entered in, all of this done asynchronously. If it any match, we return the search result. If not, then we echo out that no search results have been found for this query.

This form uses the javascript onkeypress() function for the search text box, which means that the ajax function is called when the user starts typing into the text box. When the user does this, search results begin getting shown and as the user keeps tying, the search results get updated.

Again, all the major search engines out there, including google, bing, yahoo, duckduckgo all show search results asynchronously that a user types in. They're updating search results even before a user clicks the button.

So AJAX is widespread on the web and very useful.

So now we will show how to go about searching a directory or directories on a website to search through all the files in the directories and how to return relevant results.

So how do we do this?

HTML and Javascript Code

The HTML and Javascript code to needed to create a search engine that returns results by searching the directory or directories of a website is shown below.

So this is all the Javascript and HTML code needed to create asynchronous requests for our username registration form.

We'll now go through each line of code so that you understand what each does.

So we add <script> tag to our code to indicate that we're going to add Javascript to the page. Any type of Javascript entry requires an opening and closing script tag.

We then create a function called SearchQuery(). This function is designed to return relevants results based on a user's search query.

The first thing we do in this function is create a variable called request. This variable will represent a request object, which is absolutely imperative in order for the browser to request communication with the server. Otherwise, AJAX is impossible. The request object is pretty much the heart of AJAX.

The most common way to create a request object is through the line, request= new XMLHttpRequest(); Through this line, most browsers can create a request object, which then can be called so that a browser can communicate with the server. However, this line may not work for all browsers. Therefore, we use try catch statements to create a request object by other means in the event that the browser cannot do so through the first way. So we try also the tryMicrosoft function and the otherMicrosoft function. These are more specific to Microsoft browsers such as Internet Explorer for creating a request object. If all the methods fail, the last method failed is run, which makes the request object equal to null; if this happens, asynchronous communication cannot occur because the browser has no way of contacting the server. However, if you are using any type of major browser, this shouldn't happen. You should be able to create a request object.

You'll see how this request object is used later in the code. But if you want a full in-depth article on request objects, see How to Create a Request Object in AJAX.

So after we've created a request object, we then create a variable called url, which contains the name of the PHP file that processes our data. I named my file, searchquery.php.

Next, a variable named searchentry has been created which stores the value that the user has entered into the search box.

We then create a variable called vars. This variable stores the value of the search entered in. This variable is written as a name=value pair. So the name is search and the value is searchentry. Since the search query equals the variable searchentry, the total statement is, var vars= "search="+searchentry;

This variable vars is very important and in fact can be seen as the heart of the PHP file, searchquery.php, that processes our request. Using this vars variable, we can have PHP parse this variable and extract the data from it. Thus, from this vars variable, we can know what a user enter into these username and password text boxes. We'll show how to do this in PHP when we get to the PHP code.

Next we take the request object and use the open method on it. This open method decides whether we use the POST or GET method. It takes the URL that we want parsing the data that we submit to. And it determines whether the request should be asynchronous or not. By making the third parameter true, the request becomes an asynchronous request which is what we desire.

The line, request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");, is just for character encoding of the variable vars we are sending. For the vars variable, it is organized in name1=value1&name2=value2&name3=value3 order. Now say for instance, that the value had the ampersand symbol (&), this could throw off the vars variable and cause an error. To protect against this, we put this line in the code.

Next, we take the request object and find its onreadystatechange property and set it equal to function(). The onreadystatechange property is a property that changes as the server processes a request by a browser. It has 4 states, 1 is the first inital state and 4 means it's absolutely ready. If request.readyState is equal to 4, this means that the server has obtained the request object from the browser and is ready to process the data sent. There is also another property named status that we can check to determine if everything is in place. If ready.status is equal to 200, this means that all is OK. Once these 2 parameters are in place, we create a variable called return_data and set it equal to request.responseText. The responseText variable is the data which the PHP file returns. Let's say you have a PHP file processing this request and in turn you set so that the PHP file echos a certain statement such as, "Everything has been processed well." This statement then goes into the responseText, which receive back after everything has been processed on the server side. So the return_data is very important. It's the output of the PHP file that processes the request on the server side.

We then take the Javascript document.getElementById() function to get the element on our HTML page that has the Id of status. We place this in an HTML div tag below the search box. This div tag has the Id of status. We access the contents of this label tag through .innerHTML. This property lets us write data to the HTML label tag that has the Id of status. We then set it equal to return_data, which is the data that the PHP file echoes out.

The last statement, request.send(vars);, is the statement that actually executes the sending of the vars variable, so that the PHP file can process it. So it isn't actually sent until this statement.

So this is all that is required on the HTML and Javascript.

The last thing we have is the PHP code.

PHP Code

So the last thing we have is the PHP code, which is the server side language that can actually speak to the server.

Javascript cannot manipulate server information. A server side language is needed, and that's PHP.

So we need a server side language to ge the data from the server, so that we can process this data and output a result based on this data.

The PHP code that we use is shown below.

So this is our PHP code above.

The first line uses a PHP variable called $search_entered. It gets the value of the search query that the person has entered in the form. Remember that the vars variable contained, var vars= "search="+searchentry; PHP is able to extract the data that the person has entered into the search box through the name=value pair. So all we have to do is create a PHP variable and set it equal to the value of the name of the pair. So we set the $search_entered variable to $_POST['search']; PHP will then get the value that the person has entered into the search text box.

We then add a variable called $searchoriginal. This makes a copy of the search query entered before we manipulate it and change the string. We want to preserve the original search query entered.

One of the manipulations we do is make the search query lowercase. This is so that we don't have case sensitivity problems when we are later matching it to existing files in a directory. We later make the file names all lowercase too.

We then use the PHP function to trim away all whitespace to the left and right of the string.

We then do something called exploding the string. This means we divide the string based on a certain parameter; in this case, the parameter is " " (whitespace). This way, if a user types in multiple words, we can look for all of the words in the file name and only return files that have all those words.

This exploded string gets placed in the $countsearchterms variable.

Since almost all the files on this site are stored in the Articles directory, I set the $directory variable equal to "Articles/" You can change this to any directory you want. If you want to check multiple directories, all you have to do is copy and paste the whole PHP code and just change the directory you want to search to a new directory. Or if you want to search every directory in your home root directory, then see the following code.

If the search term isn't empty and the directory you specified is a valid directory, we open up that directory. If the search query that the user has entered in is a single term, we read all the files of that directory. We make the file name lower case and remove all "-" or "_" symbols through the str_replace() function. We also remove the file ending of the file, because we don't want the ending showed when we display the search results.

If the search query that the user has entered matches any of the file names, then we return this result. We use the PHP ucwords() function to capitalize each word in the string. We create an array named array[] which stores the name of the file. We do this because we later check at the end of the code to see if it contains something or is empty. If it is empty, then we echo the statement that no search results have been found based on this search query.

We then have an if statement if the user enters in a search query that has 2 words in the search query. The first term is search_entered[0] and the second is search_entered[1]. If they are both in the file name, we return that result.

We then do the same thing for 3 words in the search query, 4 words in the search query... up to 10 words in the search query. This search engine only returns results if all the words entered match all the words in a file name.

So this is how we can search a directory asynchronously using AJAX and PHP.

Again, if you want to search multiple directories, just copy and paste the whole code over and change the directory name each time.

Related Resources

How to Retrieve Data From a MySQL Database Using AJAX and PHP

How to Insert Data into a MySQL Database Using AJAX and PHP

HTML Comment Box is loading comments...