Posts

Home jQuery

Search Data Using jQuery – Step By Step Guide!

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!

Related Tutorials

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

Home jQuery

How To Highlight Table Row OnMouseOver

I'm just gonna make a continuation of my previous post. We are going to:

1. Highlight the table row on mouse over.
2. Show its original color on mouse out.

Just add the following JavaScript code before the </body> tag:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js">
</script>
<script type='text/javascript'>
$(document).ready(function(){

//we will select the odd and even row
//to highlight it on mouse over
$('.odd-row, .even-row').hover(
function () {
$(this).css('background-color', '#CFF');
},
function () {
//then get the class name to identify
//and show its original color
var c_name = $(this).attr('class');
if(c_name == 'odd-row'){
$(this).css('background-color', '#E3E3E3');
}else if(c_name == 'even-row'){
$(this).css('background-color', '#D1D1D1');
}
}
);

});
</script>

   

That's it! :)
Home jQuery

How To Use jQuery Lightbox With A Database? Step by Step Guide!

Today I'm gonna show you how to use Lightbox while getting photo information from your database.

I think this is great if you wanna have something like a dynamic photo gallery in your site.

How To Use Lightbox With A Database

Step 1: Prepare your Database. We’ll have something like this:

CREATE TABLE IF NOT EXISTS `photos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(32) NOT NULL,
  `description` text NOT NULL,
  `filename` varchar(32) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `photos`
--

INSERT INTO `photos` (`id`, `title`, `description`, `filename`) VALUES
(1, 'Mt. Batulao', 'Mt. Batulao''s New Trail', 'Mt-Batulao.jpg'),
(2, 'Mt. Polis', 'A few klicks outside Bontoc going up to Mt Polis', 'Mt-Polis.jpg'),
(4, 'Chocolate Hills 1', 'The wonderful chocolate hills', 'chocolatehills-1.jpg');

Step 2: Download Lightbox here.

Step 3: Unzip it on your web directory.

Step 4: Prepare your database configuration file for database connection. Create config_open_db.php file and place the following code.

<?php
$host = "your host";
$db_name = "your database name";
$username = "your database username";
$password = "your database password";

$conn = new PDO("mysql:host=" . $host . ";dbname=" . $db_name, $username, $password);
?>

Step 5: Create a images folder, we’ll assume that your photos are stored here. You can download and use some photos for free from Unsplash.

Step 6: We’ll have the following codes on our index.php file.

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>How To Use jQuery Lightbox With A Database</title>

        <link rel="stylesheet" type="text/css" href="js/css/jquery.lightbox-0.5.css" media="screen" />
    </head>
<body>

<div>You may click the images below.</div>
<div id="gallery"> <!-- id to detect images for lightbox -->

<?php
include 'config_open_db.php'; // Database Connection
$sql = "select * from photos"; // Query the photos
$stmt = $conn->prepare( $sql );
$stmt->execute();

while($row = $stmt->fetch(PDO::FETCH_ASSOC)){ // Loop through the records
    $file_name = $row['filename'];
    $title = $row['title'];
    $description = $row['description'];

    // We will append the $file_name variable to href and src attributes
    // to identify what image is being selected/shown
    // The rel='lightbox[philippines]' <a> attribute is
    // needed to use lightbox for set of images
    // It should be stored under one name, we gave the name 'philippines'
    // we also included the title and decription on the title attribute
    // so it will be shown on the overlay
    echo "<a href='images/$file_name' rel='lightbox[philippines]' title='$title - $description'>";
        echo "<img src='images/$file_name' width='150' height='100' />";
    echo "</a> ";
}
?>
</div>

<div class='back-link'>
    <a href='https://www.codeofaninja.com/2010/10/how-to-use-lightbox-with-database.html'>Back to tutorial page</a>
</div>

<script type="text/javascript" src="js/js/jquery.js"></script>
<script type="text/javascript" src="js/js/jquery.lightbox-0.5.js"></script>

<script type="text/javascript">
// script to activate lightbox
$(function() {
    $('#gallery a').lightBox();
});
</script>

</body>
</html>

There are also lots of things that you can configure in jQuery Lightbox such as overlay background color, opacity, navigation behavior, button images, border size, resize speed, keyboard navigation, and etc.

You can find that in jquery.lightbox-0.5.js file in the js/ directory.

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

Thank you for learning from our post about: How To Use jQuery Lightbox With A Database? Step by Step Guide!