Posts

How To Center Screen Pop Up Window With JavaScript

There was a time when I wanted the contact form of a website to be popped up in another window. I was able to pop-up the window but it was not centered on the screen. For me, it looks better when the window pop up is at the center of you screen. So I found a way to do that. Today we're going to:

1. Create a file with a button and  to trigger the centered pop up window (index.php)
2. Create a file which will serve as the pop up window (contact_form.php)

   

<html>
<head>
<title>How To Center Screen Pop Up Window With JavaScript</title>
</head>
<body>


<h3>Please click the button below</h3>


<!-- We will use a button to trigger the pop up window -->
<input type='button' value='Contact Us' onclick="showcontactusform()" align="center" />


<script type='text/javascript'>
function showcontactusform() {
//set the width and height of the
//pop up window in pixels
var width = 500;
var height = 500;

//Get the TOP coordinate by
//getting the 50% of the screen height minus
//the 50% of the pop up window height
var top = parseInt((screen.availHeight/2) - (height/2));

//Get the LEFT coordinate by
//getting the 50% of the screen width minus
//the 50% of the pop up window width
var left = parseInt((screen.availWidth/2) - (width/2));

//Open the window with the
//file to show on the pop up window
//title of the pop up
//and other parameter where we will use the
//values of the variables above
window.open('contact_form.php',
"Contact The Code Ninja",
"menubar=no,resizable=no,width=500,height=500,scrollbars=yes,left="
+ left + ",top=" + top + ",screenX=" + left + ",screenY=" + top);
}
</script>
</body>
</html>

That's it! :)

How To Refresh Greybox Parent Page

I wonder why its hard to find this tutorial on the web. So I decided to make my own. This snippet is useful if you’re editing data in the greybox pop up window and then you want to reflect the changes in its parent window by refreshing it.

In case you want to test this code instantly, you may download the code or see the result of this tutorial live:

DOWNLOAD SOURCE CODE LIVE DEMO

Step 1: Download Greybox here and place it inside you js/ directory.

Step 2: Create your index.php file, with these codes inside:

<html>
     <head>
          <title>How To Refresh Greybox Parent Page</title>

          <script type="text/javascript">
               var GB_ROOT_DIR = "js/greybox/";
          </script>
          
          <script src="js/greybox/AJS.js" type="text/javascript">
          </script>
          <script src="js/greybox/AJS_fx.js" type="text/javascript">
          </script>
          <script src="js/greybox/gb_scripts.js" type="text/javascript">
          </script>
          <link href="js/greybox/gb_styles.css" rel="stylesheet" type="text/css">       

          <script language="javascript" type="text/javascript">
               // we will use greybox' afterclose function to reload the parent page
               // after closing the grebox pop up window
             <!--
                    function afterclose() {
                         window.location.reload();
                    }        
               // -->
          </script>

     </head>
<body>

     <b>This is the greybox parent window</b>
     <p>
          <a href="greybox_pop_up.php" title="Greybox pop up" rel="gb_page_center[500, 500]">
               Click this link to greybox pop up
          </a>
     </p>

     Textbox with default input: 
     <input name="sample_textbox" size="40" type="text" value="some predefined value" />

</body>
</html>

Step 3: Create your greybox pop up page which is greybox_pop_up.php with these codes inside:

<html>
     <head>
          <title>This is the greybox pop up</title>
          <script type='text/javascript'>
          function redirect_to_parent(){
               parent.parent.window.location = "index.php";
               parent.parent.GB_hide();
          }
          </script>
     </head>
<body onunload="redirect_to_parent();"> <-- The important part -->


     <h2>This is the greybox pop up window</h2>
     <form>
          <input type="button" value="Close This Window" onclick="parent.parent.GB_hide();"> 
     </form>


</body>
</html>

Step 4: You should have this files by now:

How To Refresh Greybox Parent Page

Final files in this tutorial

Step 5: Testing

  • If you’re gonna run index.php, you should see this in your browser:
  • Our index.php file

    Our index.php file

  • Change the predefined textbox value to any values you want, like the following:
  • Textbox with changed predefined value

    Textbox with changed predefined value

  • Click the link to show the greybox pop up
  • Greybox pop up window

    Greybox pop up window

  • Close the pop up window, if the textbox value returned to “some predefined value”, it means that the parent page was refreshed.

By the way, if you’re not yet familiar with greybox, I also have a tutorial on how to use greybox. That’s it! Hope it helps :)

Home jQuery

How To Use jQuery Table Sorter With A Database

Hi there! Today we’re going to do a script that:

  1. Get list of data from a database.
  2. Arrange those data into a table, so that
  3. It will be sortable (without page refresh) once you click its header.

How To Use Table Sorter With A Database

All of these are done with the help of TableSorter. It is a jQuery plugin that lets you sort your tables without refreshing page.

tablesorter
 

Flexible client-side table sorting

This one is beautiful when you want to sort hundreds of table rows really quick. A thousand table rows could be sorted a bit slower, but still effective.

Step 1: Download tablesorter and place it inside your js/ directory
Step 2: You can also download a theme here (I used Blue Skin) for your table.
Step 3: Create your database table. You could have this one, just add more records if you want:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `email` varchar(32) NOT NULL,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `firstname`, `lastname`, `email`, `username`, `password`) VALUES
(1, 'John', 'Doe', 'john@gmail.com', 'johnny', 'john'),
(2, 'Albert', 'Minston', 'albert@gmail.com', 'albert', 'albert');

Step 4: Create your database configuration file (i got config_open_db.php) and index.php file. Place the following codes inside the index.php file.

<html>
   <head>
        <title>How To Use Table Sorter With A Database</title>
        <!-- we will use the 'blue' theme -->
        <link href='blue/style.css' rel='stylesheet' type='text/css' />
   </head>
<body>
<?php
//connect to database
include 'config_open_db.php';

//query the database
$sql = "select * from users";
$rs = mysql_query ( $sql );

//construct the table with id 'your-table'
echo "<table id='your-table' class='tablesorter'>";
    echo "<thead>"; //thead tag is required for using tablesorter
        echo "<tr>";
            echo "<th>Lastname";
            echo "<th>Firstname";
            echo "<th>Email";
            echo "<th>Username";
            echo "<th>Password";
        echo "</tr>";
    echo "</thead>";
echo "<tbody>"; //tbody tag is required for using tablesorter

//looping through retrieved data
while ( $row = mysql_fetch_array ( $rs ) ){
    extract ( $row );
    echo "<tr>";
        echo "<td>$lastname</td>";
        echo "<td>$firstname</td>";
        echo "<td>$email</td>";
        echo "<td>$username</td>";
        echo "<td>******</td>";
    echo "</tr>";
}
echo "</tbody>";
echo "</table>";
?>
    
<!-- include jQuery library and table sorter plugin -->
<script type='text/javascript' src='js/tablesorter/jquery-latest.js'>
</script>
<script type='text/javascript' src='js/tablesorter/jquery.tablesorter.min.js'>
</script>

<script type='text/javascript'>
    $(document).ready(function() { 
        $("#your-table").tablesorter({ 
            //for example we want to disable the 
            //password column (5th column) from sorting
            //we will specify '4' since it was indexed
            //(count starts at '0')
            //and set its property to 'false'
            headers: { 
                4: {    
                    sorter: false 
                }
            }
        }); 
    });
</script>
</body>
</html>

Hope this helps. :)

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 Table Sorter With A Database.

SHA1 Hashing Algorithm

If you're feeling lazy right now to create your own hashing algorithm (like me haha!), here's one of best built in hashing algorithm with its new feature in PHP5 - SHA1. It uses US Secure Hash Algorithm 1.

I didn't hear any successful hacking attempts or tools for sha1 yet. (If you have, please pm me or comment to this post! thanks... ) Unlike for MD5 hashing, there are successful hacking attempts discovered.


HOW TO's
*Comments on codes serves as its explanation

Step 1: Put the following PHP code in your index.php file.

<?php
$str = 'dalisay'; // we're gonna hash this string

echo sha1( 'dalisay' ); // to be seen on the page

echo nl2br("nn"); // just some line breaks

// in this part, we're just gonna test if sha1 is working in your server
// the random number and digits is the hash code for string 'dalisay'
// the condition for a login system with sha1 passwords goes like this
if ( sha1( $str ) == '49d8801436095c7a0445a3c53c7d31270223069c' ){
    echo "Yes";
}else{
    echo "No";
}
?>

Step 2: Testing. If you end up something like this, sha1 is working fine.


Final output for the codes above


TIPs
If you're going to use sha1 for passwords to be stored in the database, make the datatype of your password field to BLOB type, just to make it more secure. :)



Thank you for reading! :)

How To Use Greybox

Greybox is another beautiful way not only to display your site contents or websites in a pop up window but also to do database operations in it. 
Image from http://orangoo.com

How To's.
*Comments on codes serves as its explanations.
Step 1: Download Greybox here.
Step 2: Create your js/ directory and place greybox in it.
Step 3: Create your index.php file and it should have the following codes in it:

<html>
<head>
<title>How To Use Greybox</title>

<script type="text/javascript">
var GB_ROOT_DIR = "js/greybox/";
</script>

<script src="js/greybox/AJS.js" type="text/javascript"></script>
<script src="js/greybox/AJS_fx.js" type="text/javascript"></script>
<script src="js/greybox/gb_scripts.js" type="text/javascript"></script>
<link href="js/greybox/gb_styles.css" rel="stylesheet" type="text/css">

</head>
<body>

<b>This is the greybox parent window</b>
<p>
<a href="greybox_pop_up.php" title="Greybox pop up" rel="gb_page_center[500, 500]">
Click this link to greybox pop up
</a>
</p>

</body>
</html>

Step 4: Create your greybox_pop_up.php with these codes in it:

<html>
<head>
<title>This is the greybox pop up</title>
</head>
<body>
<h2>This is the greybox pop up window</h2>
</body>
</html>

Step 5: Run your index.php, click the link to test if greybox is working.
our index.php
Greybox pop up after clicking the "Show greybox pop up link"
Tips.

You can do many things with greybox. It prevents you from the hassle of refreshing the whole page.

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!

How to: Date Format

If you're gonna display this date format in your page, it will look so elementary: 2010-10-20. So we got to have a format for this one.
How to: Date Format with PHP
Date Format


Step 1: Prepare your database configuration file.
Step 2: Create and put this code inside your index.php file.

<?php
include 'config_open_db.php';

// to format the date, we used the date_format function
// we also label the column as formatted_date 'coz if not, we will have to access the data
// in this way: date_format(date_created,'%M %d, %Y')
$sql = "select title, date_format(date_created,'%M %d, %Y') as formatted_date from articles";
$rs = mysql_query( $sql ) or die( 'Database Error: ' . mysql_error());
while( $row = mysql_fetch_array( $rs ) ){
extract( $row );
echo "<h4>$title</h4>";
echo "Created on " . $formatted_date. "< hr />";
}
?>

you should have something like this:

Date Format
Step 3: If you also want to display the time just change %M %d, %Y to %M %d, %Y %r. You should have something like this.
Date Format With Time Specified
For more date format patter strings, look here.

How To: Read More Link

Creating a Read More link saves space in your page especially if you want to display a list of articles. It is much better than displaying the whole content of an article.

How To: Read More Link
Read More Link

Step 1: Prepare your database configuration file.

Step 2: Create your index.php file. You should have these codes.

<?php
include 'config_open_db.php'; // For database connection

// SUBSTR function in the query is used to shorten the output of the content
$sql = "select id, title, SUBSTR( body, 1, 300 ) as body from articles";
$rs = mysql_query( $sql ) or die( 'Database Error: ' . mysql_error());
while( $row = mysql_fetch_array( $rs ) ){
    extract( $row ); // to have variable names the same with column names
    echo "<h4>$title</h4>";
    echo "$body";
    // Link to the page where the reader can read the whole article
    echo "...[<a href='read_news.php?page_id=$id'>Read More</a>]";
}
?>