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 Android

A Happy Developer, Android + CakePHP + jQuery

Hi there! Well, I don't have much posts few weeks ago since I'm kinda busy working on a project. I got good news and not-so-bad news, haha! This past few weeks, I've been working on an Android application which makes me so happy (though at first, kinda stressed, since I'm a beginner on this). Yes, it has been my dream to be a Java programmer since college. I can't believe that now, one of my dreams is coming true (Since Android is Java based).
A Happy Developer, Android + CakePHP + jQuery
There's more :)

I can say that now, I'm comfortable with developing an Android application. It is total object oriented, powerful, has lots of possibilities, useful, extensible, and almost anything you can think of. It can be integrated with other technologies like Web App Development (which is also what I'm working on now). Most of all, it is continuously developed by increasing hundreds of thousands of other developers around the world (I'm happy and grateful to be one of them). Another great thing is that, there are over 400,000 Android devices were activated everyday.
I'm gonna tell you something about my current project. The Android application is run in a tablet device (I have Samsung Galaxy Tab, Android Froyo for now. But I'm delighted by it.). The Android App I'm doing is some sort of a content management system that syncs data from an encrypted XML stream. Those data include images, slideshows, flash games, videos, audios, websites, survey forms, sales data, etc. The XML stream is of course generated dynamically by a Web based content management system which is developed with some web development technologies like HTML5CakePHP and jQuery
Sounds simple right? But like any other software project, it will be from simple to complex. We will discover more about the client's business logic. The user of this application is in the retail industry. The Android App will be installed in tablet devices in different parts of the country (where they have market places).
Here's the not-so-bad news: The web based CMS is developed by other programmer. And so now, it is assigned to be developed by me. So I got a lot of work to do. I thought I will concentrate on Android development, but it seemed like web app development always haunt me haha! Anyway the good news there is that, I'll have a lot of knowledge to share with you guys and of course the open-source community.
As of now, I'm the only programmer of this project. Good thing is I'm with a Systems Analyst who helps a lot. But the team will expand sooner or later. :)
Just a piece of advice, to those who want to learn language frameworks such as CakePHP (for PHP) and jQuery (for JavaScript), you have to learn first its basic or native language: PHP and JavaScript. This will give you great development advantage. :)
And oh, I got a late special announcement (or at-least for me), as you've noticed, you accessed this blog in a top level domain: https://www.codeofaninja.com which is before http://www.codeofaninja.blogspot.com. It's my dream to own a ".com" website before, and now, it just came true last June 2, 2011. I registered https://www.codeofaninja.com at Go Daddy.
I'm also so happy to see that there are increasing number of traffic on this site (based on this blog's google analytics account). It makes my goal to help and share knowledge to other people in different parts of the world.

Home jQuery

Including Google Hosted jQuery and other JS Libraries

jquery-tutorial

When I'm testing my JavaScript with jQuery, sometimes, I feel lazy to locate on my hard disk where is that jQuery library file.

At the same time, I don't want to download it on their website. So I thought of hosting it on a server and just specify its URL as a source of my <script> tag.

But then I found out that Google is hosting different JavaScript library for free. So now, I can access the library just by specifying the URL of Google-hosted jQuery library.

Google hosts several open-source library which includes:

Chrome Frame

Dojo

Ext Core

jQuery

jQuery UI

MooTools

Prototype

script_aculo_us

SWFObject

Yahoo! User Interface Library (YUI)

WebFont Loader

So now, here's how I include a jQuery library on my scripts.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

You may also use google.load function if you want. But you have to get your own API key. So I prefer accessing it in direct path (script above).

Here's a simple slide and toggle demo, with jQuery hosted by google.

Well actually, jQuery site also provide their script.

<script src="http://code.jquery.com/jquery-latest.js"></script>

There are many debates whether to host your jQuery on Google or not. You may also read this article and its comments.

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

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! :)