Search Data Using jQuery – Step By Step Guide!

Last update: November 17, 2010
Date posted: November 17, 2010
Created by ninjazhai
banner-3

[adinserter block=”34″]Today, we will learn how to search data using jQuery. It will be very convenient for the users of your web application if you can load more data from the database without refreshing the whole page.

Users don’t have to wait for those web contents such as images, text, flash files, etc. to load because the app will refresh only a part of a web page. Thanks to AJAX group of technologies (AJAX in not a technology in itself).

Today I’m gonna show you a data searching example without refreshing a page:

  1. User will input a name on the textbox.
  2. User can click the search button or just simply press enter to start search.
  3. A loader image will be shown.
  4. Loader image will hide when search result comes in.

In this tutorial, we will need five files:

  • js/jquery-1.4.2.min.js – the main weapon
  • images/ajax-loader.gif – loader image (animated ofcourse)
  • config_open_db.php – for database connection
  • index.php – read below
  • search_results.php – read below

Step 1: We should have the following table structure. Just insert your own data.

CREATE TABLE `users` (
   `id` int(11) not null auto_increment,
   `firstname` varchar(32) not null,
   `lastname` varchar(32) not null,
   `email` varchar(32),
   `username` varchar(32) not null,
   `password` varchar(32) not null,
   PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=23;

Step 2: Create config_open_db.php file and put the following code.

<?php
// used to connect to the database
$host = "localhost";
$db_name = "your_db_name";
$username = "your_db_username";
$password = "your_db_password";

try {
    $con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}

// show error
catch(PDOException $exception){
    echo "Connection error: " . $exception->getMessage();
}
?>

Step 3: We will have the user interface here in our index.php file with these codes:

<html>
<head>
    <title>Data Searching Without Page Refresh</title>
</head>
<body>

<!--
we will preload the loader image
to show it instantly on search
-->
<div style='display:none;'>
    <img src="images/ajax-loader.gif" />
</div>

<form name = "form">

    <div>Try to search for "dalisay" or "Chris" then click the Search Button or just press Enter</div>

    <!-- where our search value will be entered -->
    <input type="text" name="name" id="fn" />

    <!-- This button will call our JavaScript Search functions -->
    <input type="submit" value="Search" id="search-btn" />
</form>

<div id = "s-results">
    <!-- This is where our search results will be displayed -->
</div>

<div style='clear:both;'></div>
<div class='back-link' style='margin:3em 0 0 0;'>
    <a href='https://www.codeofaninja.com/2010/11/how-to-searching-without-page-refresh.html'>Back to tutorial page</a>
</div>

<!-- import jQuery file -->
<script type='text/javascript' src='js/jquery-1.4.2.min.js'></script>
<script type="text/javascript">
// jQuery code will be here
</script>

</body>
</html>

Step 4: jQuery code that will make the front-end work and send request to back-end. Replace “// jQuery code will be here” line above with the following code.

$(document).ready(function(){
    //load the current contents of search result
    //which is "Please enter a name!"
    $('#s-results').load('search_results.php').show();


    $('#search-btn').click(function(){
        showValues();
    });

    $(function() {
        $('form').bind('submit',function(){
            showValues();
            return false;
        });
    });

    function showValues() {
        //loader will be show until result from
        //search_results.php is shown
        $('#s-results').html('<p><img src="images/ajax-loader.gif" /></p>');

        //this will pass the form input
        $.post('search_results.php', { name: form.name.value },

        //then print the result
        function(result){
            $('#s-results').html(result).show();
        });
    }

});

Step 5: This search_results.php file gets the request from our interface and then returns a result that will be displayed on the interface (index.php) too.

<?php
include_once("config_open_db.php");

//define index
$name = isset($_REQUEST['name']) ? $_REQUEST['name'] : "";

if( empty( $name )){
    // this will be displayed if search value is blank
    echo "Please enter a name!";
}else{
    // this part will perform our database query
    $query = "select * from users where firstname like ? OR lastname like ?";

    // prepare query statement
    $stmt = $con->prepare($query);

    // bind  variables
    $query_search_term = "%{$name}%";
    $stmt->bindParam(1, $query_search_term);
    $stmt->bindParam(2, $query_search_term);

    // execute query
    $stmt->execute();

    // count number of categories returned
    $num = $stmt->rowCount();

    if($num>0){
        // this will display how many records found
        // and also the actual record
        echo "<div style='margin: 0 0 10px 0; font-weight: bold;'>$num record(s) found!</div>";

        // loop through the categories and show details
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            echo "<div>" . $row['firstname'] . " " . $row['lastname'] ."</div>";
        }
    }else{
        // if no records found
        echo "<b>Name not found!</b>";
    }
}
?>

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!
[purchase_link id=”12316″ text=”Download Now” style=”button” color=”green”]

Related Tutorials

[adinserter block=”1″]

Thank you for learning from our post about: Search Data Using jQuery – Step By Step Guide!