Posts

Home jQuery

Check and Validate Username in jQuery

Hi there developer! Today we are going to do a code snippet that:

  1. Checks if a username is available or not (in the database).
  2. If the username is available, the program will output “[your_username] is available!”
  3. Then if it is not available, “Username already taken” will be printed.
  4. This code also has a simple validation that states whether the inputted username is too short or is empty.

All those tasks will be performed via AJAX, so it is without page refresh. You can expand its validation though.

In this code, we need a sample data from the database table and four (4) files which includes: config_open_db.php, index.php, check.php and the jQuery library file.

database – you could have this table structure and data:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(32) NOT NULL,
  `lastname` 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`, `username`, `password`) VALUES
(1, 'John', 'Doe', 'johnny', 'john'),
(2, 'Albert', 'Minston', 'albert', 'albert');

config_open_db.php – this file is for database connection so that we’ll be able to load usernames from the database. You should have something like this: (Please supply the variables with YOUR settings.)

<?php
$host = "localhost";
$db_name = "your_db_name";
$username = "your_db_username";
$password = "your_db_password";

//connect to mysql server
$mysqli = new mysqli($host, $username, $password, $db_name);

//check if any connection error was encountered
if(mysqli_connect_errno()) {
    echo "Error: Could not connect to database.";
    exit;
}
?>

index.php – this file makes our user interface for this tutorial. jQuery library is of course included in this file.

<html>
	<head>
		<title>Username checker and validator</title>
	</head>
<body>

<p>
	<div id = "feedback"></div>
	<form name = 'form'>
		<input type = 'text' id = 'username_input' name = 'username' >
	</form>(try 'johnny', 'albert', 'chris' or 'james')
</p>

<div class='back-link'>
	<a href='https://www.codeofaninja.com/2011/06/check-and-validate-username-without.html'>Back to tutorial page</a>
</div>

<script type = "text/javascript" src = "js/jQuery.js"></script>
<script type = "text/javascript">

	// when the document is ready, run the jquery script
	$(document).ready(function(){
		$('#feedback').load('check.php').show();

		/* We use keyup so that everytime the user type in the keyboard, it'll check the database and get results however,
		  you can change this to a button click which is I think, more advisable.
          Sometimes, your server response is slow but just for this demo, we'll use 'keyup' */
		$('#username_input').keyup(function(){

			$.post('check.php', { username: form.username.value },
				function(result){
					$('#feedback').html(result).show();
				});

		});
	});
</script>

</body>
</html>

check.php – this file makes the request to the database, to check the inputted value.

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

isset( $_POST['username'] ) ? $username = $username = $mysqli->real_escape_string( $_POST['username'] ) : $username = "";
if($username == null){
	echo "Please enter a username.";
}

elseif(strlen($username) < 5){
	echo "Username is too short.";
}

else{
	$sql = "SELECT *
			FROM users
			WHERE username = \"{$username}\"";

	$result = $mysqli->query($sql);
	$num = mysqli_num_rows($result);
	if($num == 1 ){
		while($row = mysqli_fetch_array($result)){
			$fn = $row['firstname'];
			$ln = $row['lastname'];
			echo "<div style='color: red; font-weight: bold;'>Username already taken.</div>";
		}
	}else{
		echo "<span style='font-weight: bold;'>$username</span> is available!";
	}
}
?>

Download jQuery Code Examples

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 Check and Validate Username in jQuery.

Home jQuery

Add or Remove File Field in jQuery

Hi guys! Today I’m going to share about multiple file upload in PHP.

We’ll be using jQuery to add or remove new file fields.

This one is useful when your system has multiple email attachment or document management feature.

Home>jQuery Add or Remove File Field Then Upload File in PHP and jQuery

Multiple file upload

This code contains the form with the file field, add and remove button and of course, the upload button. jQuery is used for its dynamic adding or removing of file fields.

<html>
<head>
     <title>How To Add or Remove File Field Then Upload File in PHP and jQuery</title>
</head>
<body>
<?php
isset($_REQUEST['action']) ? $action = $_REQUEST['action'] : $action = '';

if( $action == 'uploadfiles' ){
     //define where the files will be uploaded
     $upload_directory = 'uploads/';
     $x=0;  
          echo "</div>Uploaded Files:</div>";
          foreach ( $_FILES['data']['name'] AS $key => $value ){  
               echo "<div>{$value}</div>";
               //Move file to server directory
               move_uploaded_file($_FILES["data"]["tmp_name"][$x], $upload_directory . $_FILES["data"]["name"][$x]);
               $x++;  
          }
}
?>
     <form enctype="multipart/form-data" action="#" method="POST">
          <input type="hidden" name="MAX_FILE_SIZE" value="100000" />
               <div>Choose a file to upload:</div>
                    <div id="text">
                         <div ><input name="data[]" type="file" /></div>
                         <!-- This is where the new file field will appear -->
                    </div>
                    <input type="button" id="add-file-field" name="add" value="Add input field" />
                    <input type='hidden' name="action" value="uploadfiles" />
                    <input type="submit" value="Upload File" />
     </form>



     <script type="text/javascript" src="js/jquery-1.6.1.min.js"></script>
     <script type='text/javascript'>
          $(document).ready(function(){
                // This will add new input field
               $("#add-file-field").click(function(){
                    $("#text").append("<div class='added-field'><input name='data[]' type='file' /><input type='button' class='remove-btn' value='Remove Field' /></div>");
               });
               // The live function binds elements which are added to the DOM at later time
               // So the newly added field can be removed too
               $(".remove-btn").live('click',function() {
                    $(this).parent().remove();
               });
          });
     </script>
</body>
</html>

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: Add or Remove File Field in jQuery.

Home jQuery

Check or Uncheck All Checkboxes with jQuery + Show Checked with PHP

Today, we will learn how to check or uncheck all checkboxes with jQuery. We will show all selected checkboxes using PHP as well.

When you have a list of data, sometimes, you want to easily check all or uncheck all of them. And then process those selected/checked data by getting their values first.

Today we’re going to do something like what we’re using in GMail or YahooMail.

  1. Check or Uncheck All Checkboxes in a form (using jQuery).
  2. Get the selected checkboxes values when the form is submitted (using PHP).

Check or Uncheck Checkboxes with jQuery And Get Selected with PHP

In case you want instant testing you may download the code or see the result in live demo:

Step 1: Create index.html and put the following code. The code below will show an HTML form with checkbox options.

<html>
	<head>
		<title>Check and Uncheck All</title>
	</head>
<body>

<div style='margin: 10px'><input type='checkbox' id='checker' />Check/Uncheck All</div>

<form action='index.php' method='post'>
<div style='margin: 10px'>
	<input type='checkbox' name='emotions[]' class='checkboxes' value='Happy' />Happy
	<input type='checkbox' name='emotions[]' class='checkboxes' value='Sad' />Sad
	<input type='checkbox' name='emotions[]' class='checkboxes' value='Excited' />Excited
	<input type='checkbox' name='emotions[]' class='checkboxes' value='Scared' />Scared
</div>
<div style='margin: 10px'>
	<input type='hidden' name='action' value='get_values' />
	<input type='submit' value='Submit Selected' />
</div>
<div style='margin: 10px'>
<?php
// PHP code will be here
?>
</div>
</form>

<!-- jQuery script will be here -->

</body>
</html>

Step 2: Replace "PHP code will be here" line above with the following code. The code below will show you the selected checkbox options when the form was submitted.

//Defining indexes
empty($_POST['action']) ? $action = '' : $action = $_POST['action'];
empty($_POST['emotions']) ? $emotions = '' : $emotions = $_POST['emotions'];

if( $action == 'get_values'){
	if(!empty($emotions)){ //check if user ticked any checkbox
		foreach($emotions as $keys => $values){
			echo "<div>$values</div>";
		}
	}else{
		echo "Please select emotions.";
	}
}

Step 3: Replace "jQuery script will be here" line above with the following code. The code below will check or un-check the checkbox options in the form.

<script type='text/javascript' src='js/jquery-1.6.1.min.js'></script>
<script type='text/javascript'>
	$(document).ready(function() {
		$( '#checker' ).click(function(){
			$( '.checkboxes' ).attr( 'checked', $( this ).is( ':checked' ) );
		});
	});
</script>

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: Check or Uncheck Checkboxes with jQuery And Get Selected with PHP.

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.

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!