Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

How to Add Select All Options to jQuery Select2 Plug-in

On 4/09/2018 Be the first to comment!

Hi, in this post let's see how to add select all options to jQuery Select2 plugin. Select2 is an excellent alternative to the standard HTML selection box that supports all its functions and provides greater flexibility. The plug-in is easy to setup and use. It supports multiple selection options where the selected elements will be added as pills to the top text box. You can also tag, search and load remote data-sets to select2 control.

Below we will see how to use select2 in your web projects, and select all options at once by ticking a check box using jquery.

jquery select2 select all options on click

How to Use Select2 jQuery Plug-in?

To implement Select2 plug-in in your projects, create a regular drop-down box with html markup as usual.

HTML:

<select id="states" style="width:300px">
    <option>Alaska</option>
    <option>Arizona</option>
    <option>California</option>
    <option>Florida</option>
    <option>Hawaii</option>
    <option>illinois</option>
    <option>Michigan</option>
    <option>North Dacota</option>
    <option>Ohio</option>
    <option>Washington</option>
</select>

This would produce a select box like this,

standard html select box example

Now load the library files for jquery and select2 on the html page. Do it only once on a page.

CSS:

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css" rel="stylesheet" />

JS:

<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js" type="text/javascript"></script>

Finally bind the select2() method to the dropdown in this way,

$(document).ready(function() {
    $('#states').select2();
});

It will initialize the select2 control and convert the plain dropdown to this,

select2 single select example

Please note that you must wrap your code within the $(document).ready() block. This will ensure that the DOM is ready before initializing the select2 control.

Select2 Multiple Select Box:

Select2 also supports multiple selection option. All you have to do is to declare the multiple attribute to the input. This will add the selected options as pills to the text box at the top of the control.

Example:

<select id="states" multiple style="width:300px">
    <option>Alaska</option>
    <option>Arizona</option>
    <option>California</option>
    <option>Florida</option>
    <option>Hawaii</option>
    <option>illinois</option>
    <option>Michigan</option>
    <option>North Dacota</option>
    <option>Ohio</option>
    <option>Washington</option>
</select>

<script type="text/javascript">
$(document).ready(function() {
    $('#states').select2();
});
</script>

The above example will produce a dropdown box like this,

select2 multi select example

Add Select All Option to jQuery Select2:

Select2 also supports selecting all options at once from the list. Here we'll see how to select all the options when the user ticks the 'Select All' checkbox.

First create the markup for the multi-value select box and a check box for selecting all option.

<select id="states" multiple style="width:300px">
    <option>Alaska</option>
    <option>Arizona</option>
    <option>California</option>
    <option>Florida</option>
    <option>Hawaii</option>
    <option>illinois</option>
    <option>Michigan</option>
    <option>North Dacota</option>
    <option>Ohio</option>
    <option>Washington</option>
</select>

<input id="chkall" type="checkbox" >Select All

Now add this java script to the page.

<script type="text/javascript">
$(document).ready(function() {
    $('#states').select2();
    
    $("#chkall").click(function(){
        if($("#chkall").is(':checked')){
            $("#states > option").prop("selected", "selected");
            $("#states").trigger("change");
        } else {
            $("#states > option").removeAttr("selected");
            $("#states").trigger("change");
        }
    });
});
</script>

The above script will be executed by onclick() event of the check box. If checked, the script will set all the options of the select control as selected.

If you think this will alone do the job, you're wrong. This will simply keep all items in the dropdown selected, but will not add the selected items to the top of the control. For that we have to explicitly trigger the 'change' event.

select2 select all options example

Read other tutorials of select2,

That explains about jquery select2 and selecting all the options at once on click of the checkbox. The plugin offers so many customizations and adds flexibility to the standard html select box. I hope you like this tutorial. Meet you in another interesting post. Good day!

How to Disable Mouse Right Click using jQuery

On 4/02/2018 Be the first to comment!

Content theft is a serious issue faced by many website / blog owners. This can be limited to a certain level by disabling right click on websites. Disabling mouse right-click will prevent the context menu from appearing, there by preventing the page contents from being copied. Although it is not recommended as the best practice, it is certainly feasible.

It is very easy to disable the right click on your site using jquery. You can do it at page level or element level. You have to capture and cancel the event inside the event handler. We will see how to do it.

jquery disable mouse right click cut copy paste

jQuery - Disable Right Click Context Menu:

You can avoid copying the contents of your website in two ways. One is to disable the right-click context menu altogether and the other is to simply disable the cut, copy and paste operations.

1) To disable the right-click event on the entire web page, use this script,

<script type="text/javascript">
$(document).ready(function(){
    $(this).on('contextmenu', function(e){
        e.preventDefault();
    });
});
</script>

In the above script, the method on() attaches the 'contextmenu' event handler to the document. And the preventDefault() method prevents the default action of the element from happening; here it stops the context menu from showing up.

2) To disable context-menu on mouse right click only on part of the web page, use the element id, class or the element itself.

<script type="text/javascript">
$(document).ready(function(){
    $('#id').on('contextmenu', function(e){
        e.preventDefault();
    });
});
</script>

3) To disable right click context menu on the whole page but on the editable element like textarea, use this,

<script type="text/javascript">
$(document).ready(function(){
    $(this).on('contextmenu', function(e){
        if(e.target.nodeName != "TEXTAREA"){
            e.preventDefault();
        }
    });
});
</script>

Disable Cut, Copy & Paste on Webpage:

The first method will only stop users from copy pasting the contents using mouse. But they can still fire keyboard shortcuts such as CTRL+X (cut), CTRL+C (copy), CTRL+V (paste).

1) To disable just the cut, copy and paste features on your web page, use this,

<script type="text/javascript">
$(document).ready(function(){
    $(this).on('cut copy paste', function(e){
        return false;
    });
});
</script>

2) To disable cut, copy and paste operations on specific page elements, use this,

<script type="text/javascript">
$(document).ready(function(){
    $('#code').on('cut copy paste', function(e){
        return false;
    });
});
</script>
Read Also:

That's a pretty nifty solution for disabling right click on the mouse. In jquery you can use both bind() and on() methods to attach the event handler to an element. Since 'bind' is deprecated from v3.0, use 'on' from here on. I hope this tutorial is useful for you. Please share it on your social circle if you like it.

How to Add Images to Dropdown List using jQuery

On 3/30/2018 Be the first to comment!

Hi! In this post, let's see how to add images to dropdown list using jquery. I had a form with a drop-down element for the list of countries and wanted to insert the corresponding country flag before each country name. But HTML does not support the addition of elements to select box. Then I found some CSS hack but this method is not compatible with all browsers. Finally, I decided to go with java script and found a fairly neat solution.

Actually, it is a jquery plugin called 'select2'. It includes the autocomplete feature to dropdown list, but also allows you to add icons to those select options. Below, I'll show you how to use the select2 add-on to insert country flags before the country names in a drop-down list.

jquery add images to dropdown list

jQuery - Adding Images to the Dropdown List:

STEP-1) First load the 'jQuery' and 'Select2' libraries on the Web page. You need to add both 'css' and 'js' files of the plugin.

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css" rel="stylesheet" />

<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js" type="text/javascript"></script>

STEP-2) Next, load the library for country flag icons. This will help us to display images of flags of all countries.

<link href="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/0.8.2/css/flag-icon.min.css" rel="stylesheet" />

STEP-3) Now create an empty drop down element to add the country names and flags.

<select id="countries">
    <option></option>
</select>

STEP-4) Finally the JavaScript. This is the main part of the task. Here we have to create a JS array that contains all the country names and their IDs and pass it to the drop-down element that we created in the previous step.

<script type="text/javascript">
$(document).ready(function() {
    var options = [
        { id: 'AF', text: 'Afghanistan'},{ id: 'AX', text: 'Aland Islands'},{ id: 'AL', text: 'Albania'},{ id: 'DZ', text: 'Algeria'},{ id: 'AS', text: 'American Samoa'},
        { id: 'AD', text: 'Andorra'},{ id: 'AO', text: 'Angola'},
        { id: 'AI', text: 'Anguilla'},{ id: 'AQ', text: 'Antarctica'},{ id: 'AG', text: 'Antigua And Barbuda'},
        { id: 'AR', text: 'Argentina'},{ id: 'AM', text: 'Armenia'},{ id: 'AW', text: 'Aruba'},
        { id: 'AU', text: 'Australia'},{ id: 'AT', text: 'Austria'},{ id: 'AZ', text: 'Azerbaijan'},{ id: 'BS', text: 'Bahamas'},{ id: 'BH', text: 'Bahrain'},{ id: 'BD', text: 'Bangladesh'},{ id: 'BB', text: 'Barbados'},{ id: 'BY', text: 'Belarus'},{ id: 'BE', text: 'Belgium'},
        { id: 'BZ', text: 'Belize'},{ id: 'BJ', text: 'Benin'},
        { id: 'BM', text: 'Bermuda'},{ id: 'BT', text: 'Bhutan'},
        { id: 'BO', text: 'Bolivia'},{ id: 'BA', text: 'Bosnia And Herzegovina'},{ id: 'BW', text: 'Botswana'},    { id: 'BV', text: 'Bouvet Island'},{ id: 'BR', text: 'Brazil'},
        { id: 'IO', text: 'British Indian Ocean Territory'},{ id: 'BN', text: 'Brunei Darussalam'},{ id: 'BG', text: 'Bulgaria'},{ id: 'BF', text: 'Burkina Faso'},{ id: 'BI', text: 'Burundi'},{ id: 'KH', text: 'Cambodia'},{ id: 'CM', text: 'Cameroon'},{ id: 'CA', text: 'Canada'},
        { id: 'CV', text: 'Cape Verde'},{ id: 'KY', text: 'Cayman Islands'},{ id: 'CF', text: 'Central African Republic'},{ id: 'TD', text: 'Chad'},{ id: 'CL', text: 'Chile'},{ id: 'CN', text: 'China'},{ id: 'CX', text: 'Christmas Island'},{ id: 'CC', text: 'Cocos (Keeling) Islands'},{ id: 'CO', text: 'Colombia'},{ id: 'KM', text: 'Comoros'},{ id: 'CG', text: 'Congo'},{ id: 'CD', text: 'Congo, Democratic Republic Of'},{ id: 'CK', text: 'Cook Islands'},{ id: 'CR', text: 'Costa Rica'},{ id: 'CI', text: 'Cote D\'Ivoire'},{ id: 'HR', text: 'Croatia'},
        { id: 'CU', text: 'Cuba'},{ id: 'CY', text: 'Cyprus'},
        { id: 'CZ', text: 'Czech Republic'},{ id: 'DK', text: 'Denmark'},{ id: 'DJ', text: 'Djibouti'},{ id: 'DM', text: 'Dominica'},{ id: 'DO', text: 'Dominican Republic'},
        { id: 'EC', text: 'Ecuador'},{ id: 'EG', text: 'Egypt'},
        { id: 'SV', text: 'El Salvador'},{ id: 'GQ', text: 'Equatorial Guinea'},{ id: 'ER', text: 'Eritrea'},
        { id: 'EE', text: 'Estonia'},{ id: 'ET', text: 'Ethiopia'},{ id: 'FK', text: 'Falkland Islands (Malvinas)'},
        { id: 'FO', text: 'Faroe Islands'},{ id: 'FJ', text: 'Fiji'},{ id: 'FI', text: 'Finland'},{ id: 'FR', text: 'France'},{ id: 'GF', text: 'French Guiana'},{ id: 'PF', text: 'French Polynesia'},{ id: 'TF', text: 'French Southern Territories'},{ id: 'GA', text: 'Gabon'},{ id: 'GM', text: 'Gambia'},{ id: 'GE', text: 'Georgia'},{ id: 'DE', text: 'Germany'},{ id: 'GH', text: 'Ghana'},{ id: 'GI', text: 'Gibraltar'},{ id: 'GR', text: 'Greece'},
        { id: 'GL', text: 'Greenland'},{ id: 'GD', text: 'Grenada'},{ id: 'GP', text: 'Guadeloupe'},{ id: 'GU', text: 'Guam'},{ id: 'GT', text: 'Guatemala'},{ id: 'GG', text: 'Guernsey'},{ id: 'GN', text: 'Guinea'},{ id: 'GW', text: 'Guinea-Bissau'},{ id: 'GY', text: 'Guyana'},
        { id: 'HT', text: 'Haiti'},{ id: 'HM', text: 'Heard Island & Mcdonald Islands'},{ id: 'VA', text: 'Holy See (Vatican City State)'},{ id: 'HN', text: 'Honduras'},
        { id: 'HK', text: 'Hong Kong'},{ id: 'HU', text: 'Hungary'},{ id: 'IS', text: 'Iceland'},
        { id: 'IN', text: 'India'},{ id: 'ID', text: 'Indonesia'},
        { id: 'IR', text: 'Iran, Islamic Republic Of'},{ id: 'IQ', text: 'Iraq'},{ id: 'IE', text: 'Ireland'},{ id: 'IM', text: 'Isle Of Man'},{ id: 'IL', text: 'Israel'},
        { id: 'IT', text: 'Italy'},{ id: 'JM', text: 'Jamaica'},
        { id: 'JP', text: 'Japan'},{ id: 'JE', text: 'Jersey'},
        { id: 'JO', text: 'Jordan'},{ id: 'KZ', text: 'Kazakhstan'},{ id: 'KE', text: 'Kenya'},{ id: 'KI', text: 'Kiribati'},{ id: 'KR', text: 'Korea'},{ id: 'KW', text: 'Kuwait'},{ id: 'KG', text: 'Kyrgyzstan'},{ id: 'LA', text: 'Lao People\'s Democratic Republic'},{ id: 'LV', text: 'Latvia'},{ id: 'LB', text: 'Lebanon'},{ id: 'LS', text: 'Lesotho'},{ id: 'LR', text: 'Liberia'},{ id: 'LY', text: 'Libyan Arab Jamahiriya'},{ id: 'LI', text: 'Liechtenstein'},{ id: 'LT', text: 'Lithuania'},{ id: 'LU', text: 'Luxembourg'},{ id: 'MO', text: 'Macao'},
        { id: 'MK', text: 'Macedonia'},{ id: 'MG', text: 'Madagascar'},{ id: 'MW', text: 'Malawi'},{ id: 'MY', text: 'Malaysia'},{ id: 'MV', text: 'Maldives'},
        { id: 'ML', text: 'Mali'},{ id: 'MT', text: 'Malta'},
        { id: 'MH', text: 'Marshall Islands'},{ id: 'MQ', text: 'Martinique'},{ id: 'MR', text: 'Mauritania'},{ id: 'MU', text: 'Mauritius'},{ id: 'YT', text: 'Mayotte'},
        { id: 'MX', text: 'Mexico'},{ id: 'FM', text: 'Micronesia, Federated States Of'},{ id: 'MD', text: 'Moldova'},{ id: 'MC', text: 'Monaco'},{ id: 'MN', text: 'Mongolia'},{ id: 'ME', text: 'Montenegro'},{ id: 'MS', text: 'Montserrat'},{ id: 'MA', text: 'Morocco'},{ id: 'MZ', text: 'Mozambique'},{ id: 'MM', text: 'Myanmar'},
        { id: 'NA', text: 'Namibia'},{ id: 'NR', text: 'Nauru'},
        { id: 'NP', text: 'Nepal'},{ id: 'NL', text: 'Netherlands'},{ id: 'AN', text: 'Netherlands Antilles'},
        { id: 'NC', text: 'New Caledonia'},{ id: 'NZ', text: 'New Zealand'},{ id: 'NI', text: 'Nicaragua'},{ id: 'NE', text: 'Niger'},{ id: 'NG', text: 'Nigeria'},{ id: 'NU', text: 'Niue'},{ id: 'NF', text: 'Norfolk Island'},{ id: 'MP', text: 'Northern Mariana Islands'},{ id: 'NO', text: 'Norway'},{ id: 'OM', text: 'Oman'},{ id: 'PK', text: 'Pakistan'},{ id: 'PW', text: 'Palau'},{ id: 'PS', text: 'Palestinian Territory, Occupied'},{ id: 'PA', text: 'Panama'},{ id: 'PG', text: 'Papua New Guinea'},{ id: 'PY', text: 'Paraguay'},{ id: 'PE', text: 'Peru'},
        { id: 'PH', text: 'Philippines'},{ id: 'PN', text: 'Pitcairn'},{ id: 'PL', text: 'Poland'},{ id: 'PT', text: 'Portugal'},{ id: 'PR', text: 'Puerto Rico'},{ id: 'QA', text: 'Qatar'},{ id: 'RE', text: 'Reunion'},
        { id: 'RO', text: 'Romania'},{ id: 'RU', text: 'Russian Federation'},{ id: 'RW', text: 'Rwanda'},{ id: 'BL', text: 'Saint Barthelemy'},{ id: 'SH', text: 'Saint Helena'},
        { id: 'KN', text: 'Saint Kitts And Nevis'},{ id: 'LC', text: 'Saint Lucia'},{ id: 'MF', text: 'Saint Martin'},
        { id: 'PM', text: 'Saint Pierre And Miquelon'},{ id: 'VC', text: 'Saint Vincent And Grenadines'},{ id: 'WS', text: 'Samoa'},{ id: 'SM', text: 'San Marino'},{ id: 'ST', text: 'Sao Tome And Principe'},{ id: 'SA', text: 'Saudi Arabia'},{ id: 'SN', text: 'Senegal'},{ id: 'RS', text: 'Serbia'},{ id: 'SC', text: 'Seychelles'},{ id: 'SL', text: 'Sierra Leone'},{ id: 'SG', text: 'Singapore'},{ id: 'SK', text: 'Slovakia'},{ id: 'SI', text: 'Slovenia'},
        { id: 'SB', text: 'Solomon Islands'},{ id: 'SO', text: 'Somalia'},{ id: 'ZA', text: 'South Africa'},{ id: 'GS', text: 'South Georgia And Sandwich Isl.'},{ id: 'ES', text: 'Spain'},{ id: 'LK', text: 'Sri Lanka'},
        { id: 'SD', text: 'Sudan'},{ id: 'SR', text: 'Suriname'},
        { id: 'SJ', text: 'Svalbard And Jan Mayen'},{ id: 'SZ', text: 'Swaziland'},{ id: 'SE', text: 'Sweden'},{ id: 'CH', text: 'Switzerland'},{ id: 'SY', text: 'Syrian Arab Republic'},{ id: 'TW', text: 'Taiwan'},{ id: 'TJ', text: 'Tajikistan'},{ id: 'TZ', text: 'Tanzania'},
        { id: 'TH', text: 'Thailand'},{ id: 'TL', text: 'Timor-Leste'},{ id: 'TG', text: 'Togo'},{ id: 'TK', text: 'Tokelau'},{ id: 'TO', text: 'Tonga'},{ id: 'TT', text: 'Trinidad And Tobago'},{ id: 'TN', text: 'Tunisia'},
        { id: 'TR', text: 'Turkey'},{ id: 'TM', text: 'Turkmenistan'},{ id: 'TC', text: 'Turks And Caicos Islands'},{ id: 'TV', text: 'Tuvalu'},{ id: 'UG', text: 'Uganda'},{ id: 'UA', text: 'Ukraine'},{ id: 'AE', text: 'United Arab Emirates'},{ id: 'GB', text: 'United Kingdom'},{ id: 'US', text: 'United States'},{ id: 'UM', text: 'United States Outlying Islands'},{ id: 'UY', text: 'Uruguay'},{ id: 'UZ', text: 'Uzbekistan'},{ id: 'VU', text: 'Vanuatu'},{ id: 'VE', text: 'Venezuela'},{ id: 'VN', text: 'Viet Nam'},{ id: 'VG', text: 'Virgin Islands, British'},{ id: 'VI', text: 'Virgin Islands, U.S.'},{ id: 'WF', text: 'Wallis And Futuna'},{ id: 'EH', text: 'Western Sahara'},{ id: 'YE', text: 'Yemen'},
        { id: 'ZM', text: 'Zambia'},{ id: 'ZW', text: 'Zimbabwe'}
    ];
    $('#countries').select2({
        placeholder: '-Select Country-',
        templateResult: formatCountry,
        data: options
    });
    
    function formatCountry(country){
        if (!country.id) {
            return country.text;
        }
        var $country = $(
            '<span class="flag-icon flag-icon-'+ country.id.toLowerCase() +' flag-icon-squared"></span>' + '<span style="margin-left:10px;">'+ country.text+'</span>'
        );
        return $country;
    };
});
</script>

In the above script, the select2() method will simply replace the plain dropdown with a more customizable one. We also have to set the formatting function to the templateResult option. This will execute the function for each option in the drop down and will add a country flag image to it.

Run the script and you will see a nice dropdown that shows the country names with their flags. It also includes an amazing search box which will autosuggest the names of countries when you start typing.

insert country flag images before country names select2
Read Also:

Likewise, you can add images to the select box using the jquery select2 plugin. It's a nifty add-on that gives you more control over the element which you never get with HTML. I hope this tutorial is useful for you. Please share it on social media if you like it.

Dynamic Treeview Menu using PHP, MySQL and AJAX Example

On 3/26/2018 Be the first to comment!

How to Create Dynamic Treeview Menu using PHP, MySQL and AJAX? Most modern websites use tree view to display the dynamic sidebar menu for easy navigation. In case you don't know, a Treeview is a hierarchical representation of elements in a tree-like structure. You can go for jquery solution in this context, but I would recommend 'Bootstrap Treeview' plug-in if you use the bootstrap framework to build your websites.

The plug-in uses JSON dataset to create a hierarchical tree structure. I have already discussed the creation of static treeview menu using bootstrap treeview. But you can also generate a dynamic tree where you pull off the data elements stored in the database. In this tutorial I'm going to show you about creating dynamic treeview using php, mysql, ajax and bootstrap.

bootstrap dynamic treeview example

How to Create Dymanic Treeview in PHP & MySQL?

For the demo, I'm going to load all the required libraries via CDN. So there's no need to download them to your web server.

Here are the simple steps to build a dynamic tree view structure.

STEP-1) First create the mysql database required for the example. I would suggest you follow the same schema given below to maintain the hierarchy structure.

CREATE DATABASE `my_demo`;
USE `my_demo`;

CREATE TABLE `tbl_categories` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `item_name` varchar(50) NOT NULL,
  `parent_id` int(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=18;

INSERT INTO `tbl_categories` (`id`, `item_name`, `parent_id`) VALUES
(1, 'Electronics', 0),
(2, 'Televisions', 1),
(3, 'Tube', 2),
(4, 'LCD', 2),
(5, 'Plasma', 2),
(6, 'Computers and Laptops', 1),
(7, 'Desktops', 6),
(8, 'Laptops', 6),
(9, 'Netbooks', 6),
(10, 'Tablets', 6),
(11, 'Android', 10),
(12, 'iPad', 10),
(13, 'Mobile Phones', 1),
(14, 'Basic Cell Phones', 13),
(15, 'Smartphones', 13),
(16, 'Android Phones', 15),
(17, 'iPhone', 15);

STEP-2) Next create a php script to be executed by ajax call. This will fetch the menu data from the 'tbl_categories' table, create hierarchical tree structure and return it as JSON data.

fetch_categories.php

<?php
$db = mysqli_connect('localhost', 'mysql_username', 'mysql_password', 'my_demo');
$sql = 'select id, item_name as name, item_name as text, parent_id from tbl_categories';
$result = mysqli_query($db, $sql);

$tree_data = mysqli_fetch_all($result, MYSQLI_ASSOC);

foreach($tree_data as $k => &$v){
    $tmp_data[$v['id']] = &$v;
}

foreach($tree_data as $k => &$v){
    if($v['parent_id'] && isset($tmp_data[$v['parent_id']])){
        $tmp_data[$v['parent_id']]['nodes'][] = &$v;
    }
}

foreach($tree_data as $k => &$v){
    if($v['parent_id'] && isset($tmp_data[$v['parent_id']])){
        unset($tree_data[$k]);
    }
}

echo json_encode($tree_data);
?>

STEP-3) Finally, create an HTML file and add placeholder to show the tree view. Here you have to load all the required libraries such as bootstrap, jquery and bootstrap treeview libraries.

index.html

<!DOCTYPE html>
<html>
<head>
    <title>PHP and MySQl Dynamic Treeview Example</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-sm-4">
            <h3 class="text-center bg-primary">Dynamic Treeview Example</h3>
                <div id="myTree"></div>
            </div>

            <div class="col-sm-8">
                <!-- here goes other page contents -->
            </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.js" type="text/javascript"></script>
    
    <script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            url: 'fetch_categories.php',
            method: 'GET',
            dataType: 'json',
            success: function(data){
                $('#myTree').treeview({data: data});
            }
        });
    });
    </script>
</body>
</html>

In the success function of the ajax() call, we have invoked the treeview() method of the 'bootstrap-treeview' library to display the tree structure on the corresponding placeholder.

When you run 'index.html' a tree menu similar to this one will appear,

ajax dynamic treeview php mysql example
Read Also:

Similarly, you can create treeview dynamically using php, mysql and ajax. You can also add icons, check boxes and filters to the nodes of the tree menu. Check the documentation to learn more about it. I hope this tutorial is useful for you. Please share it on social media if you like it.

How to Send AJAX Request at Regular Interval

On 3/15/2018 Be the first to comment!

At times, you may want to update part of a web page repeatedly. Let's say, for example, that you have a website flashing live news or a cricket score update. Here you have to refresh that specific content on a regular basis and ajax is the best way to do it.

You are left with two options when you want to fire ajax request at specific time interval - one is setInterval() and the other is setTimeout() function. Both JavaScript functions are good for doing periodic tasks, but one is much better than the other. In this tutorial we will see what is the best approach and how.

send ajax request at regular interval

Fire Continuous AJAX Request using setInterval():

The setInterval() is the common method used for repeated tasks. It executes a function at specified interval in milliseconds. Repeated calls can only be stopped using the clearInterval() method or by closing the window.

setInterval(function, milliseconds);

Consider the following example. This java script will fire ajax call every 5 seconds to the server and update the news feed.

<script type="text/javascript">
function getFeed() {
    $.ajax({
        url: 'get_news_feed.php',
        type: 'POST',
        success: function(data) {
            $('#result').html(data);
        }
    });
}

$(document).ready(function() {
    setInterval(getFeed, 5000);
});
</script>

At first glance, the script may look fine but it's not. It continuously executes the getFeed() function regardless of whether the previous ajax request is completed or not.

Let's say you are on a slower network, and the first request was not completed, but you start another one. Soon you would end up in a situation where multiple requests are stacked up that consume shared resources and delay each other.

To avoid this problem, you can use the setTimeout() method that allows you to wait until the last request is completed before sending the next one.

Using setTimeout() Method:

The setTimeout() calls a function after the specified delay. Unlike the previous method, it executes the function only once. You have to call again to repeat the execution.

setTimeout(function, milliseconds);
It's best to use setTimeout() method instead of setInterval() for tasks that take longer than the repetition time interval.

Below is an example for its usage.

<script type="text/javascript">
function getFeed() {
    $.ajax({
        url: 'get_news_feed.php',
        type: 'POST',
        success: function(data) {
            $('#result').html(data);
        },
        complete:function(data) {
            setTimeout(getFeed, 5000);
        }
    });
}

$(document).ready(function() {
    setTimeout(getFeed, 5000);
});
</script>

The above script send ajax request after waiting for 5 seconds. Upon successful completion, the next one will be fired. Here we have used the complete callback to verify if the previous request was executed successfully or not.

As you can see, the second example is much better than the first. It simply waits for the first ajax call to finish before sending the second one. So even if there is a delay for server response, multiple requests won't be queued.

Also Read:

We have seen two ways to send an ajax call at specific time interval. And the post also explains why it is better to use setTimeout for repetitive task. I hope this post is useful for you. Please share it on social media if you like it.

AJAX Pagination in CodeIgniter Tutorial

On 3/09/2018 Be the first to comment!

Hi! In this post, we will see how to make ajax pagination in codeigniter using codeigniter pagination library. The Pagination class offers feature rich functions to paginate the query results in view. Although the usage of pagination library is well-documented, paginating the results with jquery ajax is somewhat a mystery. The solutions available around the web are too complicated for beginners. Hence I decided to write a tutorial on the topic that is easy enough for anyone to implement codeigniter pagination with ajax.

For this example, we'll need two libraries which are jQuery and Bootstrap. The jQuery.js is for making ajax call and bootstrap is for designing the user interface.

ajax pagination codeigniter tutorial

CodeIgniter AJAX Pagination Example:

To create ajax pagination, I'm going to use the default pagination library of the code igniter framework. Simply follow the below steps to implement the same.

STEP-1) Create Database

First create the required database, table and the records to use in our example. I'm going to use MySQL here. Just run the following sql queries in mysql and it will take care of DB creation.

CREATE DATABASE `my_demo`;
USE `my_demo`;

CREATE TABLE IF NOT EXISTS `Employees` (
  `EmpID` int(8) NOT NULL AUTO_INCREMENT,
  `EmpName` varchar(50) NOT NULL,
  `DeptName` varchar(30) NOT NULL,
  `Designation` varchar(25) NOT NULL,
  `DOJ` date NOT NULL,
  `Salary` int(10) NOT NULL,
  PRIMARY KEY (`EmpID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

INSERT INTO `Employees` (`EmpID`, `EmpName`, `DeptName`, `Designation`, `DOJ`, `Salary`) VALUES
(1, 'Colleen Hurst', 'HQ', 'Regional Director', '2009-09-15', 205500),
(2, 'Brielle Williamson', 'Software', 'Integration Specialist', '2012-12-02', 372000),
(3, 'Garrett Winters', 'Finance', 'Accountant', '2011-07-25', 170750),
(4, 'Caesar Vance', 'Sales', 'Assistant Manager', '2011-12-12', 106450),
(5, 'Sonya Frost', 'Software', 'Software Engineer', '2008-12-13', 133600),
(6, 'Herrod Chandler', 'Sales', 'Sales Executive', '2012-08-06', 127500),
(7, 'Jena Gaines', 'HQ', 'Manager', '2008-12-19', 112560),
(8, 'Quinn Flynn', 'Software', 'Support Lead', '2013-03-03', 342000);

STEP-2) Create Model

Next, create the codeigniter model to handle database requests. Place this file inside 'application' > 'models' folder. The file contains getEmployees() function to fetch a portion of employees records from the database using the limit condition.

AjaxPaginationModel.php
<?php
class AjaxPaginationModel extends CI_Model {
    function __construct() {
        // Call the Model constructor
        parent::__construct();
    }

    function getEmployees($limit, $start) {
        $query = $this->db->get('Employees', $limit, $start);
        return $query->result();
    }
}
?>

STEP-3) Create Controller

Next we need a controller file to regulate the interaction between the front-end and the back-end. Create this file inside 'application' > 'controllers' folder.

It contains the default index() function which creates paging links and obtain the employee records from the model function and passes them to the view file.

AjaxPaginationController.php
<?php
class AjaxPaginationController extends CI_Controller {
    function __construct() {
        parent::__construct();
        $this->load->helper('url');
        $this->load->database();
        $this->load->library('pagination');
        $this->load->model('AjaxPaginationModel');
    }

    function index() {
        //pagination settings
        $config['base_url'] = site_url('AjaxPaginationController/index');
        $config['total_rows'] = $this->db->count_all('Employees');
        $config['per_page'] = '5';
        $config['uri_segment'] = 3;
        $choice = $config['total_rows'] / $config['per_page'];
        $config['num_links'] = floor($choice);
        $this->pagination->initialize($config);

        $data['page'] = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

        // fetch employees list
        $data['results'] = $this->AjaxPaginationModel->getEmployees($config['per_page'], $data['page']);       
        // create pagination links
        $data['links'] = $this->pagination->create_links();

        if($this->input->post('ajax')) {
            $this->load->view('Data', $data);
        } else {
            $this->load->view('AjaxPaginationView', $data);
        }
    }
}
?>

STEP-4) Create View

Finally we need to create the view file. This is the user interface where the results from the database will be displayed in a neatly organized table along with pagination links at the bottom.

Please note that to keep this tutorial simple, I haven't styled the pagination links. You can check here to apply bootstrap styles to codeigniter pagination links.

The special thing about the view is that we have split it into two files. One is the main view named 'AjaxPaginationView.php' and the other 'Data.php' that contains the markup to display the ajax data.

AjaxPaginationView.php
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>CodeIgniter Pagination with AJAX Example</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
</head>
<body>
    <div class="container">
        <div class="row">
            <h3 class="text-center bg-success">AJAX Pagination in CodeIgniter</h3>
            <div id="ajax_content">
                <?php $this->load->view('Data', $results); ?>
            </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(function() {
        paginate();
        function paginate() {
            $('#ajax_links a').click(function() {
                var url = $(this).attr('href');
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: 'ajax=true',
                    success: function(data) {
                        $('#ajax_content').html(data);
                    }
                });
                return false;
            });
        }
    });
</script>
</body>
</html>
Data.php
<table class="table table-striped table-hover">
    <thead>
        <tr>
        <th>#</th>
        <th>Emp Name</th>
        <th>Department</th>
        <th>Designation</th>
        <th>Joining Date</th>
        <th>Salary</th>
        </tr>
    </thead>
    <tbody>
    <?php for ($i = 0; $i < count($results); ++$i) { ?>
    <tr>
        <td><?php echo ($page+$i+1); ?></td>
        <td><?php echo $results[$i]->EmpName; ?></td>
        <td><?php echo $results[$i]->DeptName; ?></td>
        <td><?php echo $results[$i]->Designation; ?></td>
        <td><?php echo $results[$i]->DOJ; ?></td>
        <td><?php echo $results[$i]->Salary; ?></td>
    </tr>
    <?php } ?>
    </tbody>
</table>
<div id="ajax_links" class="text-center">
    <?php echo $links; ?>
</div>

In the view file, we have included the java script function to make ajax call and update the data received on the view container.

codeigniter ajax pagination example
Read Also:

Likewise, you can create ajax pagination in codeigniter using the regular pagination class itself. You can also try the 'Ajax Pagination' library offered in the code igniter site. The entire concept is simple and easy to implement. I hope you find this tutorial useful. Please share it on social media if you like it.

How to Create Treeview with Bootstrap and jQuery

On 2/12/2018 Be the first to comment!

Hi! Today let's see about creating treeview using bootstrap and jquery. A Treeview is a tree like representation of elements in a hierarchical structure. It offers a quick and easy navigation through websites. Although there are several jquery plugins available for tree view that simplify the task, I wanted something that works well with bootstrap.

And I found out a good library called 'Bootstrap Treeview'. It leverages the best of bootstrap framework and helps you display hierarchical tree structures using the JSON data set. You can do much more than a simple tree, like fetch data from the database and render a dynamic tree, make it collapsible, add icons, checkboxes and filters etc.

how to create treeview in bootstrap

Building Treeview with Bootstrap:

Now let's see how to add treeview in bootstrap. To build the menu, we need three different libraries,

  1. Bootstrap CSS
  2. jQuery
  3. Bootstrap Treeview

These libraries are available in the cdn, so you can load them directly on your projects without downloading. Here is the procedure.

Step-1) Load Stylesheets

First load the required style sheets into your html file. You need to link both 'bootstrap' and 'bootstrap treeview' css files.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.css" rel="stylesheet" type="text/css" />

Step-2) Load JavaScript Libraries

Next you have to load the java script files. Be sure to load jquery before tree view to avoid dependency issues.

<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.js" type="text/javascript"></script>

Step-3) Create Placeholder for Tree View

Next add an html container to work as a placeholder for the tree view. Just a div block would do.

<div id="myTree"></div>

Step-4) Define JSON Data Structure

Now define the JSON structure required to hold the hierarchical data that will be displayed on the tree view menu.

var treeData = [
    {
        text: "Parent-Item-1",
        nodes: [
            {
                text: "Child-Item-1",
                nodes: [
                    {
                        text: "Grandchild-Item-1"
                    },
                    {
                        text: "Grandchild-Item-2"
                    }
                ]
            },
            {
                text: "Child-Item-2"
            }
        ]
    },
    {
        text: "Parent-Item-2"
    },
    {
        text: "Parent-Item-3"
    },
    {
        text: "Parent-Item-4"
    },
    {
        text: "Parent-Item-5"
    }
];

Step-5) Render the Treeview

Finally, display the tree structure in the placeholder element we have created in Step-3. For that, bind the treeview() method to the 'div' container and pass the json data to it.

$('#myTree').treeview({
    data: treeData
});

Above script will produce a tree view similar to this,

bootstrap treeview example

Read: Create Dynamic Treeview using PHP, MySQL and AJAX

Complete Script: index.html

<!DOCTYPE html>
<html>
<head>
    <title>Bootstrap Treeview Example</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div class="col-sm-4">
        <div id="myTree"></div>
    </div>
    <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(document).ready(function(){
        var treeData = [
            {
                text: "Parent-Item-1",
                nodes: [
                    {
                        text: "Child-Item-1",
                        nodes: [
                            {
                                text: "Grandchild-Item-1"
                            },
                            {
                                text: "Grandchild-Item-2"
                            }
                        ]
                    },
                    {
                        text: "Child-Item-2"
                    }
                ]
            },
            {
                text: "Parent-Item-2"
            },
            {
                text: "Parent-Item-3"
            },
            {
                text: "Parent-Item-4"
            },
            {
                text: "Parent-Item-5"
            }
        ];
        $('#myTree').treeview({
            data: treeData
        });
    });
    </script>
</body>
</html>

In our example we have built a basic tree. But the plug-in offers several options to customize the appearance and behavior of the menu. Like changing colors, adding icons, badges and hyperlinks to the node items. Check here to know more about customizing options.

Read Also:

It's a hassle-free way to build a hierarchical tree-view using the bootstrap treeview plug-in. It works well with Apps that use bootstrap. I hope this post is useful for you. Please don't forget to share it on social networks if you like it.

CodeIgniter Autocomplete Search from Database using AJAX Example

On 2/09/2018 3 Comments so far

Hi! In this post, let's see how to autocomplete search from database using codeigniter and ajax. We are going to pull in live search thing something similar to Google search. As soon as you start typing in the textbox, the related suggestions will appear from the database. To implement this auto complete feature we need a jquery plugin called 'Select2'.

Select2 is an excellent plug-in that supercharges the regular select box with search functionality. It's really inappropriate to make the end user to skim through hundreds of options to pick just one. With Select2 the entire process is a breeze. It adds up a search filter to the dropdown (select box), thus populating results on fly with the help of ajax.

codeigniter autocomplete search from database ajax

AJAX Autocomplete Search from Database in CodeIgniter:

To implement the live autocomplete search in codeigniter, we need two JavaScript libraries, 1. jquery.js and 2. select2.js. Either download them or use from the cdn library just like I do in this demo.

Just follow the below steps and you'll be good.

Step-1) Create Database

For database, I'm going to use MySQL here. Create a dummy database, a table and some records to use in the example. Below is a sql file. Run the queries on mysql and it will take care of database creation.

CREATE `db_demo`;
USE `db_demo`;
CREATE TABLE IF NOT EXISTS `tbl_language` (
  `id` int(9) NOT NULL AUTO_INCREMENT,
  `lname` varchar(50) NOT NULL,
  `lcode` varchar(2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6;

INSERT INTO `tbl_language` (`id`, `lname`, `lcode`) VALUES
(1, 'English', 'en'),
(2, 'Afrikaans', 'af'),
(3, 'Greek', 'el'),
(4, 'Finnish', 'fi'),
(5, 'Spanish', 'es');

Step-2) Create Model

We need a codeigniter model to handle the database transactions. So create a model file inside 'application' > 'models' folder. It contains the function getLanguage() to fetch language names from the database that match the search term entered by the user.

SearchModel.php

<?php
class SearchModel extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }
    
    function getLanguage($str)
    {
        $this->db->select('id, lname as text');
        $this->db->like('lname', $str);
        $query = $this->db->get('tbl_language');
        return $query->result();
    }
}
?>

Step-3) Create Controller

Next create a controller file inside 'application' > 'controllers' folder. It contains two functions,

  1. index() - this is the default method that just loads the view file.
  2. search() - This function will be triggered during the ajax call. It receives the incoming search term ('q'), communicate with the model and get the results matching the search term, encode them to json and pass it back to the browser.

SearchController.php

<?php
class SearchController extends CI_Controller {
    function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->database();
    }

    function index()
    {
        $this->load->view('SearchView');
    }
    
    function search()
    {
        $q = $this->input->get('q');
        $this->load->model('SearchModel');
        echo json_encode($this->SearchModel->getLanguage($q));
    }
}
?>

Step-4) Create View

This is the final step. Create a view file inside 'application' > 'views' folder. It contains all the front-end logic, including html markup, css and java script. Here is where we need to fire the ajax call. Just load the js libraries and bind the select2() method to the dropdown that requires auto complete feature.

SearchView.php

<!DOCTYPE html>
<html>
<head>
    <title>CodeIgniter Search from Database Example</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <h3>CodeIgniter Autocomplete Demo</h3>
    <select id="language" name="language" class="itemName form-control" style="width:300px" ></select>

    <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
    
    <script type="text/javascript">
    $('#language').select2({
        placeholder: '-Select Language-',
        minimumInputLength: 1,
        ajax: {
            url: "<?php echo base_url();?>index.php/SearchController/search",
            dataType: 'json',
            delay: 250,
            processResults: function (data) {
                return {
                    results: data
                };
            },
            cache: true
        }
    });
    </script>
</body>
</html>

That's it! We have everything in place. It's time to test the search filter. Just run the controller and if everything is okay, you'll see a drop-down box. Start typing in the textbox and you will see the suggestions popping up below in a list.

ajax autocomplete search select2

With the plug-in, you can not only pull in the results from the database, but from other sources such as a remote REST API or just a local JS array.

Read Also:

That explains about implementing search from database in codeigniter and ajax. Most modern web apps uses autocomplete search and is a sure fire way to increase user experience. Every little detail counts! So make sure you implement it on your next project. I hope this tutorial is useful for you. Please share it on your social circle if you like it.

jQuery Animated Typing Effect using Typed.js Plugin

On 2/01/2018 Be the first to comment!

Hi! Today, we are going to see an interesting tutorial, which is to animate typing effect using jquery typed.js plugin. Not all animations require the skill of a graphics artist. You can pull in some really cool animations just with jquery plugins. jQuery has its share of animation plugins and 'Typed.js' is one among them. It is simple, lightweight and let you add typing effect to web pages. The text will be typed literally character by character thus giving you the impression it is being typed on a terminal.

Come, let's see how to implement this typing effect on websites.

jquery animated typing effect typed.js example

Adding Animated Typing Effect in jQuery:

Typed.js is a jquery library to simulate the terminal typing effect that allows you to print plain text or html as if you were typing on the screen.

How to Use it:

First create a container to print the string.

<div id="container"></div>

Then call the function typed() on the container element that we have created and provide the string(s) to be printed.

$("#container").typed({
    strings: ["String1", "String2", "..."]
});

You can add more than one string separated by commas. And can even style the screen cursor with css like this,

.typed-cursor {
    // add styles here
}

Below is the complete demo to animate dynamic typing.

<!DOCTYPE html>
<html>
<head>
    <title>Animated Typing Effect in jQuery</title>
    <style type="text/css">
    div {
        margin: 0 auto;
        width: 60%;
        min-height: 150px;
        text-align: center;
        background: #222;
    }
    
    #board, .typed-cursor {
        font-size: 40px;
        color: #FFF;
    }
    </style>
</head>
<body>
    <div>
        <span id="board"></span>
    </div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
    <script src="https://cdn.bootcss.com/typed.js/1.1.7/typed.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(document).ready(function(){
        $("#board").typed({
            strings: ["This is the test.", "Have a Good Day!!!"],
            typeSpeed: 30
        });
    });
    </script>
</body>
</html>

Running this script would produce something like this,

typed js demo

You can pass several options to the method typed() and control the way it behaves. Above we have used only two options,

  1. strings - Defines the array of strings to be typed.
  2. typeSpeed - Defines the writing speed in milliseconds.

Apart from these two options, there are several others which you can refer in the official documentation of the plugin.

Read Also:

That explains about creating animated typing effect with jquery and typed.js. In the demo, I have loaded both 'js' libraries from CDN, but you can download and use them from your own server. I hope you find it useful. Please share the post with your friends if you like it.

How to Print Contents of a Div using JavaScript

On 1/12/2018 Be the first to comment!

Hi! Today let's see how to print contents of a div using javascript. Have you ever tried printing a web page or part of a page programmatically? There is an interesting utility in JavaScript called print(). It is one of the methods of the 'Window' object and is used to trigger your system's printing feature.

In case you want to print part of a page area, the simple solution is to place all the printable content inside a 'div' block and invoke the print action with some user event. Let's see how to do it.

javascript print contents of a div

Print Contents of a Div in JavaScript:

Let's first create a div container to hold the printable part.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Print Part of a Webpage with JavaScript</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
    <div id="printableDiv" class="jumbotron">
        <h2>Test Printing</h2>
        <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.</p>
    </div>
</div>
</body>
</html>

In the above markup, we have created a <div> container with an id #printableDiv and placed some text inside. This is the block we need to print.

Next add a button element to trigger the print action when the user clicks on it.

<button type="button" class="btn btn-warning btn-lg" onclick="printIt('printableDiv')">Print this block</button>

Include onclick event to the button and pass the id of the div we have created earlier.

Finally the printing part! Write a simple java script function to print the div contents.

JavaScript:

<script type="text/javascript">
function printIt(divID) {
    var divContent = document.getElementById(divID);
    var WinPrint = window.open('', '', 'width=800,height=600');
    WinPrint.document.write('<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">');
    WinPrint.document.write(divContent.innerHTML);
    WinPrint.document.close();
    WinPrint.focus();
    WinPrint.print();
    WinPrint.close();
}
</script>

The js function will open a window of defined width and height, write the contents of the div to it and invokes printing window using the print() function.

Keep in mind that the contents will be printed without any css styles you have in the webpage. To preserve styles, you must link the css file using windowsobject. document.write() method like I did in the JS code.

One good thing about using this method is it will not fire printing immediately, but the print window as a means of confirmation - just leaving the choice to users in case they clicked on it accidentally.

Read Also:

That explains printing div contents using javascript. The method described in this post is very useful to print a portion of a webpage. You just have to keep all the printable contents in a div block and trigger the java script function. I hope you like this tutorial. Please share it in your social circle if you find it useful.

Submit Form using jQuery AJAX and PHP without Page Refresh

On 12/28/2017 Be the first to comment!

Hi! In this tutorial we will see how to submit form using jquery ajax and php without page refresh. Web Development enhanced with AJAX increases speed and performance thereby improving the overall user experience. It allows you to update part of a web page without refreshing it completely. Basically, when you submit an html form, the entire page will be refreshed. But by using ajax technique, you can submit the form to the web server without having to reload the page. Instead, the form data will be submitted to the server in the background and can be processed in any way you want.

ajax submit form without page refresh using jquery and php

How to Submit Form using jQuery AJAX and PHP?

The jQuery library provides ajax() method which allows you to submit form without refreshing page. It will send an HTTP request to the web server (here is the php script), which is then processed by the server and sends an http response.

Let's see how to do it.

Step 1) Create a Basic HTML Form

First let's create a simple html form containing some input fields and a submit button.

<form id="myForm">
    <input type="text" name="name" placeholder="Enter your name" required />
    <input type="text" name="email" placeholder="Email ID" required />
    <input type="text" name="city" placeholder="City" required />
    <input type="submit" name="submit" value="Submit Form" />
</form>

Step 2) Add a Placeholder for Server Response

Add a div block next to the form. This will act as a placeholder to display the server response.

<div id="postData"></div>

Step 3) Load jQuery

We'll need jquery library to send ajax call. So load it after all the html components but just before the closing body tag.

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

Step 4) The AJAX Script

Now it's time to write the ajax script. Add the following script after loading 'jquery.js' file.

<script type="text/javascript">
$(document).ready(function(){
    $('#myForm').submit(function(e){
        e.preventDefault();
        $.ajax({
            url: "get_data.php",
            type: "POST",
            data: $(this).serialize(),
            success: function(data){
                $("#postData").html(data);
            },
            error: function(){
                alert("Form submission failed!");
            }
        });
    });
});
</script>

In the above JS, we have called ajax() function on form submission event. Using preventDefault() will cancel the original event and prevent the page from reloading.

There are several options that you can configure for the ajax() function and I have used some in the example. Here are the details of what they represent,

  • The url specifies the server script to which the http request should be sent.
  • The type defines the type of request to be sent. Here I set it as 'POST' to send HTTP POST request.
  • The data can be string or object and contain the form data.
  • The success function will be executed when the server responds true.
  • And the error function will be triggered if the request fails.

Complete Script: index.html

<html>
    <head>
        <title>AJAX Form Submit without Page Refresh</title>
    </head>
    <body>
    
    <form id="myForm">
        <input type="text" name="name" placeholder="Enter your name" required />
        <input type="text" name="email" placeholder="Email ID" required />
        <input type="text" name="city" placeholder="City" required />
        <input type="submit" name="submit" value="Submit Form" />
    </form>
    
    <div id="postData"></div>
    
    <script src="js/jquery-1.10.2.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(document).ready(function(){
        $('#myForm').submit(function(e){
            e.preventDefault();
            $.ajax({
                url: "get_data.php",
                type: "POST",
                data: $(this).serialize(),
                success: function(data){
                    $("#postData").html(data);
                },
                error: function(){
                    alert("Form submission failed!");
                }
            });
        });
    });
    </script>
    </body>
</html>

Step 5) Server Script

Finally, you need the php script where the http request should be sent. It receives the submitted form data and you can process it like you want and send back the desired response using 'echo' command.

For this example I have simply encoded the $_POST array to json and sent back to the client, which will then be displayed in the #postData div block we have created in step 2.

get_data.php

<?php
echo json_encode($_POST);
?>

Done! We have the client and server script in place. Now you can run index.html and fill up the form with details and click on 'Submit Form'. You can see that the data you have supplied will be displayed as json string in the web page without the page being refreshed.

Read Also:

Likewise you can submit form without page refresh using ajax and php. Instead of ajax() you can use the jquery's post() method to send http request. We can see about that in some other tutorial later. I hope you find it useful. Please don't forget to share it in social media if you like.

jQuery Datatables with PHP, MySQL and AJAX Example

On 12/25/2017 2 Comments so far

Hi! In this tutorial let's look at the server-side processing of jquery datatables using php, mysql and ajax. In case you don't know, Datatables is an amazing jquery plugin that converts the simple html table into a feature-rich data grid with additional functions like instant search, pagination, multi-column sorting etc. The table works with multiple data sources like DOM, AJAX etc., and supports both client and server side processing. We have already seen about datatables with json data and here we will see about server side processing.

For the server script, we are going to use PHP and MySQL as a data source.

jQuery Datatables Server-side Processing with PHP and MySQL:

Let's see how to fetch records from the server-side using ajax request and list it in the data tables. To use in this example, we need a dummy database. So let's create it first.

Step 1) Create MySQL Database

The following sql will create a mysql database, a table and some sample records in it. Run this script on phpmyadmin to create the database.

CREATE DATABASE `my_demo`;
USE `my_demo`;

CREATE TABLE `customers` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `email` varchar(60) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=14 ;

INSERT INTO `customers` (`id`, `name`, `email`) VALUES
(1, 'Jim Connor', 'jimconnor@yahoo.com'),
(2, 'Mark Higgins', 'mark.higgins21@yahoo.com'),
(3, 'Austin Joseph', 'austin.joseph.boston@gmail.com'),
(4, 'Sean Kennedy', 'seankennedy01@gmail.com'),
(5, 'Rose Harris', 'roseharris@gmail.com'),
(6, 'Lilly Whites', 'lillywhites@outlook.com'),
(7, 'Jennifer Winters', 'jennie.winters001@gmail.com'),
(8, 'Michael Bruce', 'michaelbruce78@yahoo.com'),
(9, 'John Alex', 'johnalex@example.com'),
(10, 'Demi Milan', 'demimilan@gmail.com'),
(11, 'Austin Joseph', 'austin.joseph.boston@gmail.com'),
(12, 'Mark Higgins', 'mark.higgins21@yahoo.com'),
(13, 'Sean Kennedy', 'seankennedy.boss@outlook.com');

Step 2) Load the Required CSS and JS Libraries

Next load the CSS and JS files of the datatables plug-in. And you must also include the 'jquery.js' before loading 'jquery.datatables.js' since it is dependent on jquery.

<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
<script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.js" charset="utf8" type="text/javascript"></script>
Please note that I have loaded the datatables files from the cdn but you can download and use it from your own server though.

Step 3) Create HTML Table

Then create html markup for the table. This will act as a placeholder for data table. Just add the appropriate column headers for the table.

<table id="customersTable" class="display" width="100%" cellspacing="0">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
        </tr>
    </thead>
</table>

Step 4) AJAX Call

Next, make ajax request to the php script to get the data from the server-side. You must also map the table columns with the fields in the database to populate the html table.

$(document).ready(function() {
    $('#customersTable').dataTable({
        "processing": true,
        "ajax": "fetch_data.php",
        "columns": [
            {data: 'id'},
            {data: 'name'},
            {data: 'email'}
        ]
    });
});
The method dataTable() will initialize the datatables and comes with various options. By setting different parameters we can control the way it behaves.

Complete index.html File

<!DOCTYPE html>
<html>
<head>
    <title>Datatables Example using PHP and MySQL</title>
    <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.css">
</head>
<body>
    <h2 style="text-align:center;">Datatables Server-Side Example</h2>
    <table id="customersTable" class="display" width="100%" cellspacing="0">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </thead>
    </table>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
    <script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.js" charset="utf8" type="text/javascript"></script>

    <script type="text/javascript">
    $(document).ready(function() {
        $('#customersTable').dataTable({
            "processing": true,
            "ajax": "fetch_data.php",
            "columns": [
                {data: 'id'},
                {data: 'name'},
                {data: 'email'}
            ]
        });
    });
    </script>
</body>
</html>

Step 5) Fetch Records from Database and Return as JSON

Finally the server script. This will communicate with the backend mysql database, retrieve records, encode it to json along with other necessary values and send it back to the front-end.

fetch_records.php

<?php
// db settings
$hostname = 'localhost';
$username = 'root';
$password = '';
$database = 'my_demo';

// db connection
$con = mysqli_connect($hostname, $username, $password, $database) or die("Error " . mysqli_error($con));

// fetch records
$sql = "select id, name, email from customers";
$result = mysqli_query($con, $sql);

while($row = mysqli_fetch_assoc($result)) {
    $array[] = $row;
}

$dataset = array(
    "echo" => 1,
    "totalrecords" => count($array),
    "totaldisplayrecords" => count($array),
    "data" => $array
);

echo json_encode($dataset);
?>

We have all the code in place. Now run the index.html and you can see data grid like this,

jquery datatables php mysql ajax

You can filter the records using the instant search box at the top this way,

jquery datatables server side processing php
Read Also:

That explains about displaying jquery datatables with database records using php and mysql. Although datatables works fairly well with client data sources such as json, JS Array etc., when you want to work with a huge data-set, going with server side processing is the best route. I hope this tutorial is useful for you. Please, share it in your social circle if you like it.

How to Read and Parse JSON String in jQuery and Display in HTML Table

On 12/11/2017 4 Comments so far

Hi, in today’s post we’ll see How to Read and Parse JSON String in jQuery. JSON is a human readable data exchange format used among web services and it's a necessary skill for modern day web developers (frontend/backend) to deal with JSON data received from various third-party APIs. Keeping that in mind we have discussed about parsing json data using php script sometime back. And now we have come up with this jquery tutorial which walks you through the process of parsing json string using jquery library, convert and display it into an html table.

how-to-read-and-parse-json-string-in-jquery

How to Read and Parse JSON String in jQuery?

jQuery provides several JSON methods like “getJSON”, “parseJSON”, “stringify” and for this post we’ll pickout and use the method “parseJSON”, which parses through well formed json string and returns javascript object.

JSON.parseJSON(JSON STRING)

The function parseJSON() takes the string parameter and returns String, Number, Object, Array or Boolean.

Using this jQuery method we can easily convert the json string to object and display it in a table. Let’s see how to do it.

Step-1: First create a <div> block as a placeholder for the html table.

<div id="datalist"></div>

Step-2: Next add some table formatting with css styles.

<style type="text/css">
    table {
        border: 1px solid #777;
        border-collapse: collapse;
    } 

    table tr th,
    table tr td {
        border: 1px solid #777;
    }
</style>

Step-3: Next load the javascript jQuery library above the closing body tag of the html file.

<script src="/path/to/jquery-1.10.2.min.js"></script>

Step-4: Next add the jquery method to parse a json string and iterate over the collection to display it as a list in a html table element.

<script>
$(document).ready(function() {
    var data = '[{ "firstName": "John", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jason" }, { "firstName": "Alice", "lastName": "Ray" }]';
    var table = '<table><thead><th>First Name</th><th>Last Name</th></thead><tbody>';
    var obj = $.parseJSON(data);
    $.each(obj, function() {
        table += '<tr><td>' + this['firstName'] + '</td><td>' + this['lastName'] + '</td></tr>';
    });
    table += '</tbody></table>';
    document.getElementById("datalist").innerHTML = table;
});
</script>

The variable “data” holds a valid JSON string with first and last names for three different persons and the jquery function “$.parseJSON(data)” converts that json string to java script object. And using the jQuery’s $.each() method we seamlessly iterates over the collection of object and display in a table view.

Now open the file in the browser and you will get the list of names neatly displayed in the html table.

parse-json-and-convert-to-html-table-jquery
JSON Data Displayed in the HTML Table using jQuery

Here is the complete html and javascript for parsing JSON string in jQuery.

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Read and Parse JSON String in jQuery | Example</title>
    <style type="text/css">
    table {
        border: 1px solid #777;
        border-collapse: collapse;
    } 

    table tr th,
    table tr td {
        border: 1px solid #777;
    }
    </style>
</head>
<body>
    <div id="datalist"></div>

    <script src="/path/to/js/jquery-1.10.2.min.js"></script>
    <script>
    $(document).ready(function() {
        var data = '[{ "firstName": "John", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jason" }, { "firstName": "Alice", "lastName": "Ray" }]';
        var table = '<table><thead><th>First Name</th><th>Last Name</th></thead><tbody>';
        var obj = $.parseJSON(data);
        $.each(obj, function() {
            table += '<tr><td>' + this['firstName'] + '</td><td>' + this['lastName'] + '</td></tr>';
        });
        table += '</tbody></table>';
        document.getElementById("datalist").innerHTML = table;
    });
    </script>
</body>
</html>
Read Also:

And that was all about reading and parsing json string using jQuery.

How to Convert JSON Data to HTML Table using jQuery DataTables Plug-in

On 12/11/2017 17 Comments so far

Hi, this time I have come up with a jquery basics tutorial which discusses about how to convert json to html table. In simple terms we are going to use jquery to display data from a json file in neat table format with added pagination and search options to it. To make our life easier there is an excellent jquery plug-in called ‘DataTables’ which we will use for this task. DataTables is a flexible jquery tool which adds up advanced interaction controls to any HTML table. Using this we can easily add pagination, instant search or multi-column ordering to the html table. Moreover it supports all modern day data sources like DOM, JavaScript, Ajax and server-side processing.

Convert JSON Data to HTML Table using jQuery

As an example let’s take the below sample json file which contains an array of objects and display it in html table using datatables.

Don't Miss: How to Create Responsive Carousel Image Slider

Also Read: How to Create Image Lightbox Effect with jQuery

empdata.json

{
  "data": [
    {
      "name": "Garrett Winters",
      "designation": "Accountant",
      "salary": "$170,750",
      "joining_date": "2011/07/25",
      "office": "Tokyo",
      "extension": "8422"
    },
    {
      "name": "Brielle Williamson",
      "designation": "Integration Specialist",
      "salary": "$372,000",
      "joining_date": "2012/12/02",
      "office": "New York",
      "extension": "4804"
    },
    {
      "name": "Ashton Cox",
      "designation": "Junior Technical Author",
      "salary": "$86,000",
      "joining_date": "2009/01/12",
      "office": "San Francisco",
      "extension": "1562"
    },
    {
      "name": "Airi Satou",
      "designation": "Accountant",
      "salary": "$162,700",
      "joining_date": "2008/11/28",
      "office": "Tokyo",
      "extension": "5407"
    },
    {
      "name": "Caesar Vance",
      "designation": "Pre-Sales Support",
      "salary": "$106,450",
      "joining_date": "2011/12/12",
      "office": "New York",
      "extension": "8330"
    },
    {
      "name": "Shad Decker",
      "designation": "Regional Director",
      "salary": "$183,000",
      "joining_date": "2008/11/13",
      "office": "Edinburgh",
      "extension": "6373"
    },
    {
      "name": "Cedric Kelly",
      "designation": "Senior Javascript Developer",
      "salary": "$433,060",
      "joining_date": "2012/03/29",
      "office": "Edinburgh",
      "extension": "6224"
    },
    {
      "name": "Haley Kennedy",
      "designation": "Senior Marketing Designer",
      "salary": "$313,500",
      "joining_date": "2012/12/18",
      "office": "London",
      "extension": "3597"
    },
    {
      "name": "Colleen Hurst",
      "designation": "Javascript Developer",
      "salary": "$205,500",
      "joining_date": "2009/09/15",
      "office": "San Francisco",
      "extension": "2360"
    },
    {
      "name": "Dai Rios",
      "designation": "Personnel Lead",
      "salary": "$217,500",
      "joining_date": "2012/09/26",
      "office": "Edinburgh",
      "extension": "2290"
    },
    {
      "name": "Herrod Chandler",
      "designation": "Sales Assistant",
      "salary": "$137,500",
      "joining_date": "2012/08/06",
      "office": "San Francisco",
      "extension": "9608"
    },
    {
      "name": "Rhona Davidson",
      "designation": "Integration Specialist",
      "salary": "$327,900",
      "joining_date": "2010/10/14",
      "office": "Tokyo",
      "extension": "6200"
    },
    {
      "name": "Sonya Frost",
      "designation": "Software Engineer",
      "salary": "$103,600",
      "joining_date": "2008/12/13",
      "office": "Edinburgh",
      "extension": "1667"
    },
    {
      "name": "Jena Gaines",
      "designation": "Office Manager",
      "salary": "$90,560",
      "joining_date": "2008/12/19",
      "office": "London",
      "extension": "3814"
    },
    {
      "name": "Quinn Flynn",
      "designation": "Support Lead",
      "salary": "$342,000",
      "joining_date": "2013/03/03",
      "office": "Edinburgh",
      "extension": "9497"
    }
  ]
}

Now let's see about converting this json data to html table.

Step 1: First you need the datatables plug-in in place to start working. So download datatables plug-in here and extract its contents and move ‘media’ directory to your working folder.

Step 2: Having the required datatables files in place, now we have to link them to the html file. Create a file ‘index.html’ and link the datatables ‘css’ and ‘js’ files like this.

<html>
<head>
    <!-- link datatables css -->
    <link rel="stylesheet" type="text/css" href="/path/to/jquery.dataTables.css">
</head>
<body>

    ...

    <!-- load jquery -->
    <script type="text/javascript" src="/path/to/jquery-1.10.2.js"></script>
    <!-- load datatables js library -->
    <script type="text/javascript" src="/path/to/jquery.dataTables.js"></script>
</body>
</html>

Remember to include the jquery library before datatables ‘js’ file as the plug in is built over jquery.

Step 3: Now it's time to create a html table structure which we will map to our json data source later. We should determine what are the columns we want to appear on the table and create the table's header and footer with appropriate column names.

<table id="empTable" class="display" width="100%" cellspacing="0">
    <thead>
        <tr>
            <th>Name</th>
            <th>Designation</th>
            <th>Office</th>
            <th>Extension</th>
            <th>Joining Date</th>
            <th>Salary</th>
        </tr>
    </thead>

    <tfoot>
        <tr>
            <th>Name</th>
            <th>Designation</th>
            <th>Office</th>
            <th>Extension</th>
            <th>Joining Date</th>
            <th>Salary</th>
        </tr>
    </tfoot>
</table>

Using the css class ‘.display’ will create the table with alternative striped rows (zebra cross style).

Step 4: Finally we should populate the html table with the data from json source by mapping to the right table columns.

<script type="text/javascript">
$( document ).ready(function() {
    $('#empTable').dataTable({
        "ajax": "empdata.json",
        "columns": [
            {"data": "name"},
            {"data": "designation"},
            {"data": "office"},
            {"data": "extension"},
            {"data": "joining_date"},
            {"data": "salary"}
        ]
    });   
});
</script>

- The dataTable() method will initialize the datatables. Its behavior can be controlled by passing parameters for various options and we have used two options in the above code. (I planned to keep the code as simple as possible and used only the basic options required but you can try out more).

- The ajax option will load the data from the given ajax source. Here in our case it’s the path to the json file.

- The columns option will map the table columns to the data source keys.

Now run the index.html file and you can see a nicely designed html table with added enhancements like instant-search at the top and pagination links at the bottom. You can also sort the table columns like you prefer.

display-json-data-in-html-table-datatables-jquery-example
JSON Data Displayed in HTML Table using jQuery Datatables Plug-in

Complete Code for index.html

<!DOCTYPE html>
<html>
<head>
    <title>Display JSON File Data in Datatables | Example</title>
    <!-- link datatables css -->
    <link rel="stylesheet" type="text/css" href="/path/to/jquery.dataTables.css">
</head>
<body>
    <table id="empTable" class="display" width="100%" cellspacing="0">
        <thead>
            <tr>
                <th>Name</th>
                <th>Designation</th>
                <th>Office</th>
                <th>Extension</th>
                <th>Joining Date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Designation</th>
                <th>Office</th>
                <th>Extension</th>
                <th>Joining Date</th>
                <th>Salary</th>
            </tr>
        </tfoot>
    </table>
    
    <!-- load jquery -->
    <script type="text/javascript" src="/path/to/jquery-1.10.2.js"></script>
    <!-- load datatables js library -->
    <script type="text/javascript" src="/path/to/jquery.dataTables.js"></script>
    
    <script type="text/javascript">
    $(document).ready(function() {
        $('#empTable').dataTable({
            "ajax": "empdata.json",
            "columns": [
                {"data": "name"},
                {"data": "designation"},
                {"data": "office"},
                {"data": "extension"},
                {"data": "joining_date"},
                {"data": "salary"}
            ]
        });   
    });
    </script>
</body>
</html>

I hope this basic jquery tutorial gives you a good idea about converting json data to html table using datatables jquery plugin.

Read Also:

As said earlier it's a highly flexible tool and provides wide range of options to completely customize the looks and behavior of the html tables to meet your requirements. Don't hesitate to try out :-)

Contact Form

Name

Email *

Message *