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.

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

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!
[purchase_link id="12355" text="Download Now" style="button" color="green"]

Thank you for learning from our post about: Add or Remove File Field in jQuery.

Check or uncheck checkbox in JavaScript

Today, we will learn how to check or uncheck checkbox in JavaScript. 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!
[purchase_link id="12324" text="Download Now" style="button" color="green"]

Related Tutorials

We listed all our high quality full-stack web development tutorials here: Click here.

Thank you for learning from our post about: Check or Uncheck Checkboxes with jQuery And Get Selected with PHP.

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', '[email protected]', 'johnny', 'john'),
(2, 'Albert', 'Minston', '[email protected]', '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!
[purchase_link id="12344" text="Download Now" style="button" color="green"]

Thank you for learning from our post about: How To Use jQuery Table Sorter With A Database.

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!
[purchase_link id="12316" text="Download Now" style="button" color="green"]

Related Tutorials

We listed all our high quality full-stack web development tutorials here: Click here.

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

How To Highlight Table Row on Hover

In this post, we'll highlight table row on hover. Here's how it will work: Highlight the table row on hover. 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! :)

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!
[purchase_link id="12364" text="Download Now" style="button" color="green"]

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