0 Replies - 27194 Views - Last Post: 14 January 2011 - 06:19 PM

#1 aaron1178   User is offline

  • Dovakiin, Dragonborn
  • member icon

Reputation: 170
  • View blog
  • Posts: 1,310
  • Joined: 22-October 08

An insider's look into php and Ajax - A Basic Search Engine

Posted 14 January 2011 - 06:19 PM

This tutorial uses the deprecated mysql extension (as of PHP 5.5.0) which should not be used for writing new code as it will be removed in the future. The mysqli (MySQL Improved) or PDO extension should be used instead.

Nevertheless, it has been decided to keep this tutorial available until such time as it has been either updated or re-written. In the meantime, if you wish to take the tutorial, then it is recommended that you change the mysql-extension code to use mysqli or PDO. (If you do this successfully then perhaps you might consider submitting a revised tutorial, contributing to dream.in.code and earning some Kudos!)

This tutorial is aimed for people who know nothing about Ajax. A vague knowledge is required for the php side of things. The following is a core structure of this tutorial:
  • Introduction - Includes a summary of what we will be doing
  • Setting up the Database
  • Creating the required 4 pages
  • Editing index.php
  • Editing form_process.php
  • Editing style.css
  • Editing ajax.js
  • Running our results
  • Overview

Lets get started creating and learning :P

So, you want to learn more about search engines, php & MySQL or Ajax and Javascript? Well you have viewed the right tutorial. In this tutorial, we will create a fully functional basic search engine that searches the selected table in the database for matching results(or close to it). Please note: You must have a working server with php and MySQL installed.

In the upcoming structures, we will go from black pages that do nothing, to a fully functional search engine that searches results in a database table and posts them to the original page without reloading the page. We can accomplish this using php and Ajax.

As I'm assuming that you have a vague knowledge of php, so i will continue as normal. If you would like to read more on php, please read the tutorials at W3School.

What do we know about Ajax? Well Ajax stands for "asynchronous Javascript and XML" and is used to process forms and data asynchronously. Which means, you can create a register form, where a user can register without loading another page. This is very handy when it comes to apps like Shout boxes, chats and even authentication protocols. The Instant Messenger on facebook use Ajax to add and retrieve data from the chat database.

Now we know what we will be doing and what Ajax is, lets get started. In the following section, you will create a database and add a table to the created database.

In this section i will guide you to set up a database and add the provided sql.
Create a database named "tutorials", then run the following query:
`search_id` int(3) NOT NULL AUTO_INCREMENT,
`search_string` varchar(225) NOT NULL,
`search_url` varchar(225) NOT NULL,
PRIMARY KEY(`search_id`)

What does the above SQL query do you say? Simple, the above code creates a table names "search" with the following:
  • search_id - This column is an interval(number) with a maximum length of 3 characters, is able to contain data with the "NOT NULL" and increments automatically when a new data row is inserted using the "AUTO_INCREMENT" feature
  • search_string - This column is a text column with a maximum length of 225 characters, is able to contain data with "NOT NULL"
  • search_url - This column is a text column with a maximum length of 225 characters, is able to contain data with "NOT NULL"
  • PRIMARY KEY(`search_id`) - This simply makes the column "search_id" the primary key in the table
  • ENGINE=MyISAM - Makes the table use the ISAM engine

So i hope Ive made it pretty clear on how our table will be used.

P.S: Insert some data into the search table:
search_id = 1; search_string = "My Topic1"; search_url = "What ever";
search_id = 2; search_string = "My Topic2"; search_url = "What ever";
search_id = 3; search_string = "tim"; search_url = "What ever";
search_id = 4; search_string = "bob"; search_url = "What ever";

Outcome: We should now have a database named "tutorials" and a table named "search".

Creating the required pages
Here you will create the required pages for the search engine. Please do not go ahead and create all the pages, because they are not all the same extension. Please create the following pages, i have included a summary of what they will do:
  • index.php
  • form_process.php
  • ajax.js
  • style.css

This file is used as the page where your html elements, you can convert this page to html if you wish, but i always use .php files just in case i need to use php, then i don't need to go through the process of renaming the file :P

This will will contain the following elements:
  • 2 x Div elements
  • 1 x Text element
  • 1 x Submit button element

I have also included a style sheet to style it a basic way to produce results.

This file includes, database connections, queries and loops to return search results. This is not a really big file, if you remove my Documentation comments. As you will see below in the coming section, this page is quite easy to produce and uses a single technique to supply data to the requesting Ajax form. This page uses entirely only php. Other than that, there is not much to say about this page.

This sounds like it will be a huge file doesn't it? Wrong, to make Ajax work, you don't need many lines of code. This file will contain our Ajax function that will get our database results and display them within the div element in index.php. And yes, this page is a Javascript script.

This is the Css (cascading style sheet) style sheet that style all our elements to look like a basic search engine. Other than that, nothing else is needed to be known about this file.

Outcome: You should now have 4 separate files named: "index.php", "form_process.php", "ajax.js" and "stlye.css". In the following section, we will edit "index.php" for various stuff like linking the stylesheet and making the search elements.

Editing index.php
Well, its time to get creative :P even though we will be doing low level coding (html), we will at least be doing something until we get to the fun stuff :)
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Php-Ajax - An insider's look</title>
<link rel="stylesheet" href="style.css">
<script language="javascript" src="ajax.js"></script>

<div style="background-color:#FFC;padding-left: 10px;">
Search: <input type="text" name="search_text" id="search_text">
<input onclick="search_click('search_text');" type="submit" value="Search" name="search_sub" id="search_sub">
<div id="search_results">

As you can see, not much goes on here. All we are doing is referencing the ajax.js script and also include the style sheet. Then below we add some elements. The first div element holds the search engines primary elements: The text field and the submit button. When the submit button is clicked, it will call the javascript function: "search_click with a parameter of the text fields id". The second div element will hold all the results from our search engine, so dont fiddle with it (not yet anyway).

Outcome: You should now have the basic Search Engine GUI (General User Interface) all referenced to your scripts and styles.

Editing form_process.php
Well, we have made it through the daunting parts of this tutorial, no it's time for some php. I will post the code below. It's been commented so i can walk you line by line in the script.
This file will be used by the ajax processor to return search results from the database
<note> Please remember to change the database varable in the variable declaration area below


//We will first declare some variables
$server = "localhost"; //This variable is used in the database connection
$userID = "__USERNAME__"; //This variable is used in the database connection as well
$passID = "__PASSWORD__"; //This variable is used in the database connection too
$dbID = "tutorials"; //This variable is used in the database connection
$response = null; //This variable is used to store the results for ajax
$search_string = null; //This variable stores the text we will search for in the database
$id = null; //Used to store connection data
//Below we will establish a connection to the database
$id = mysql_connect($server, $userID, $passID) or die(mysql_errno().": ".mysql_error());
mysql_select_db($dbID, $id) or die(mysql_errno().": ".mysql_error());

//Now we will get the search string
if( isset( $_GET['search_string'] ) )
  $search_string = mysql_real_escape_string($_GET['search_string']);
  echo "Error: No search string specified!";

//Now we preform the query to the database
$query = "SELECT * FROM search WHERE search_string LIKE '%$search_string%'";
$sql = mysql_query($query, $id);

//Now we will use a while loop to get data and add it to the response line
while($row = mysql_fetch_assoc($sql))
  $response .= $row['search_string'].",";

//We will now dump the data from the varable and close the connection

//Now we are at the final stage, to return the rosponse line data
echo $response;


Okay, in sort all we do in this file is: Create a connection to the database and select the database, get the search string from the sent request, preform the query, add the results to the $response line, clear some MySQL memory, close the connection then echo the $response.

When we echo something, we are returning and exiting the current form. So thats why its best to echo the response line at the end.

Here, we have combined the database we created earlier and used it in this script.

Outcome: You should no have the following code in "form_process.php". This code will be used in "ajax.js", which is coming in the following section.

Editing ajax.js
Well, if you where waiting for the Ajax/Javascript part of this tutorial, it's finally here :D
In this section, we are editing "ajax.js". We are going to create a function that will create a new XMLHttpRequest object (or ActiveX object if you use Internet explorer). This new object will open the "form_process.php" with the additional "search_string" variables. This will then process and return the value in the responseText property.

So lets begin:
This script is used in our ajax form. This script uses XMLHttpRequest. This allows our javascript
code to communicate with the form_process.php page, without changing the page.

//First we will create the main ajax function
function search_click(value)
  //First we declare some vars
  var string = document.getElementById(value).value;
  var results = document.getElementById("search_results");
  results.innerHTML = null;
  //We check if the string is empty
  if(string == "")
    alert("Please enter text!");
  //next we will create the XMLHttpRequest() object
    http = new XMLHttpRequest(); // Normal for most standard browsers
    http = new ActiveXObject("Microsoft.XMLHTTP"); //For browsers that like to be different (IE Explorer) :P/>

  //Now we want to open the "form_process.php" file with the POST method
  http.open("POST","form_process.php?search_string=" + string, true);

  //When the Ajax readystate changes, it will call the following function
  http.onreadystatechange = function()
    //If the Ready State is 4, do our data processing
    if(http.readyState == 4)
      //Split our data from form_process.php
      var spl = http.responseText.split(",");
      //Get the length of th split data
      var length = spl.length;
      //A for loop to add the data to our d
      for(var x = 0; x < length-1;x++)
        results.innerHTML = results.innerHTML + spl[x] + "<br />";
      //Make the results div element viaible
      results.style.visibility = "visible";

  //Send the http object

I have also commented the above code to try and help you understand ajax a bit better. So what we are doing here is creating a javascript function that we will us as our submit buttons onclick event. In side the function is the core of our search engine. The core determines whether or not it supports XMLHttpRequest objects. If it does, then it will create on via this line of code: http = new XMLHttpRequest();, but if the browser doesn't support XMLHttpRequst objects, then it will create a new ActiveX object via this line of code: http = new ActiveXObject("Microsoft.XMLHTTP");

We then open the "form_process.php" page via http.open("POST","form_process.php?search_string=" + search_string, true);. Next it will create a function when the readystate of our http object has changed. Inside this function is where our main core features occur. If the readystate is equal to 4 then it all happens now. It will split the response text via var spl = http.responseTex.split(","); notice that we split it via the "," from form_process.php?

We then have a for loop: for(var x = 0; x < length-1;x++)
results.innerHTML = results.innerHTML + spl[x] + "<br />";
this will loop through if the length of spl is the length - 1, this is because there will always be a "," at the end as a spare :). In the loop, we add the data to the search_results div element.

http.send(); This will send our http object to the server for processing.

And there we have the Ajax core. Wasn't hard was it? i hope not, if so then read some tutorials to better your under standing.

Outcome: Our Ajax core is complete and we are almost at the end of this tutorial.

Editing style.css
No, open up the file "style.css" and include the following styles. You should at least understand this bit :P
  border: 1px solid #30C;
  line-height: 20px;
  font-size: 20px;
  padding-left: 20px;
  padding-top: 20px;
  margin-top: 5px;
  visibility: hidden;

All this does is edit the search_result div element style. So this is self explanatory.

We have reached the end of this insiders look into ajax. You should now have:
  • A vast knowledge of Php
  • A vague understanding of Ajax
  • A Simple Search Engine

You can test this search engine by navigating to the URL of index.php and enter "m", which will return all results for "m".

An online demo is available: [Here]

Thanks for following this tutorial. If you have any questions, please leave a comment.

Thanks Aaron1178

This post has been edited by andrewsw: 01 February 2015 - 05:04 AM

Is This A Good Question/Topic? 1
  • +

Page 1 of 1