Last updated on March 1st, 2022 at 11:10 am

Ajax PHP Live Search is very popular now a days. In this tutorial we are searching wordpress post live using Ajax. This will in turn help user to search for a keyword with ease rather than typing it on a text box, hitting the search button and waiting for the results. We are fetching data from MYSQL as well for displaying the results.

The demo we have will search for our posts (400 Plus) and list those matching post title as a suggestion. Check it out. No need of any plugin.

This is a very simple script which has 2 files. One is an HTML (search.html) file with a Search input box and the second is a PHP (result.php) file that has a regular Mysql connect and a select statement to get the data from database. This script also has a Loading message shown while the data is being pulled from Mysql. Please note that live search might use more resources from your server. It might result in server overload / slowness if your infrastructure is limited.

In result.php file we are just using basic PHP / Mysql connection statements. We are also making us of Jquery to pass Ajax request from the search page to result page.

search.html page will look like this

<!doctype html>
<html>
<head>
<title>Search Using Ajax & PHP</title>
<meta charset="UTF-8">
<style>
input[type=text] {padding:5px; border:2px solid #ccc; 
-webkit-border-radius: 5px;
    border-radius: 5px;
}
input[type=text]:focus {border-color:#333; }
</style>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
function getmydata(p){
    var page=p;
    $('#loadingmessage').show();  // show the loading message.
    $.ajax({
        url: "result.php",
        type: "POST",
        cache: false,
        data: "&name="+ page,
        success : function(html){
            $("#results").html(html);
            $('#loadingmessage').hide(); // hide the loading message
        }
    });
}
</script>
</head><center>
<b>Search For Scripts Here : <input type="text" size="35" onkeyup="getmydata(this.value)"/>
<div id='loadingmessage' style='display:none'>
Loading....
</div>
</b>
<div id="results"></div>
<body>
</body>
</html>
 

In the code above we are showing a loading message initially followed by an Ajax POST request with data: “&name=”+ page,

Where name is query string and page is value that we pass through key press in the search.html page.

When a user start typing in the input field an ajax post request is send to result.php page where it will run the select statement and display result inside the div container.

<div id="results"></div>

Once the result is displayed it will hide the loading message.

You might also be interested in,

Show loading image while page loads using jquery / Ajax

Scroll to the top of the page After Ajax submit using jquery

Autosuggestion / Autocomplete script using PHP and Ajax

result.php page will look like this. Make sure to update the username, password, database and servername according to your configuration.

<?php
$servername="localhost";
$username="";
$password="";
$dbname="";
$table = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$search = $_POST["name"];
$sql = "SELECT DISTINCT post_title FROM $table  WHERE post_title LIKE '%$search%'";
$result = $conn->query($sql);
echo "$result->num_rows results found";
echo "<table id='data'>";
if ($result->num_rows > 0) {
	while($row = $result->fetch_assoc()) {
echo "<tr><th><div><a target=_blank href='http://mistonline.in/wp/?s=".$row["post_title"]."'>" . $row["post_title"] . "</a></div></th></tr>";
	}
}
else{
	echo "0 results";
}
echo "</table>";
$conn->close();
?>

Note : If you don’t want the search link but need the URL , try getting the guid column . The table we are using here is posts or if you have any custom prefix for the table add that, for example the default prefix is wp_ so the table name will be wp_posts .

If that is the case update the query with this in the code above

SELECT DISTINCT post_title,guid FROM $table WHERE post_title LIKE '%$search%';

As you can see from the code above, I am fetching data from MySQL using this query. You may have to modify it according to your requirement.

$sql = "SELECT DISTINCT post_title FROM $table  WHERE post_title LIKE '%$search%'";

We are also adding some CSS here to the input field and also for the result page.

a {
     display: block;
     height: 25px;
     padding-left: 25px;
     color:#fff;
     font: bold 15px Tahoma;
     text-decoration: none;
 }
a:hover { color: green; }
#data {
    font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
    width: 100%;
    border-collapse: collapse;
}

#data td, #data th {
    font-size: 1em;
    border: 2px solid #fff;
    padding: 3px 7px 2px 7px;
}

#data th {
    font-size: 1.1em;
    text-align: left;
    padding-top: 5px;
    padding-bottom: 4px;
    background-color: #81BEF7;
    color: #ffffff;
}

#data tr.alt td {
    color: #000000;
    background-color: #EAF2D3;
}

DEMO, In this demo it fetches result from out website posts and provide links to those tutorials.

NOTE:- In the demo we are using our own database. You can make use of it for searching all our tutorials instantly and simply click on the hyperlink to view them.

Leave a Reply

Your email address will not be published. Required fields are marked *