article

Tuesday, July 21, 2015

Create Collage using jQuery

Create Collage using jQuery

find out how to create a collage using a jQuery plugin called "CollagePlus". This plugin for jQuery will arrange your images to fit exactly within a container.

How to Limit Number of Characters in Textarea using jQuery

How to Limit Number of Characters in Textarea using jQuery
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>jQuery Limit Characters in Textarea</title> 
  <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
  <style type='text/css'>
    body {
    font-family:Calibri;
}
.remaining {
    color:blue;
}
textarea {
    font-family:Calibri;
}
  </style>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
$(function () {
    var nMaxLength = 150;
    $("#txtDesc").keydown(function (event) {
        LimitCharacters($(this));
    });
    $("#txtDesc").keyup(function (event) {
        LimitCharacters($(this));
    });

    function LimitCharacters(txtDesc) {
        if (txtDesc.val().length > nMaxLength) {
            txtDesc.val(txtDesc.val().substring(0, nMaxLength));
        } else {
            var nRemaining = nMaxLength - txtDesc.val().length;
            $('.remaining').text(nRemaining);
        }
    }
});
});//]]>  
</script>
</head>
<body>
  <textarea name="txtDesc" rows="4" cols="50" id="txtDesc" onDrop="return false;" style="width:70%;"></textarea>
<br/>Remaining: <b><span class="remaining">150</span></b>
</body>
</html>

Ajax Shopping Cart with PHP and jQuery

Ajax Shopping Cart with PHP and jQuery

 Create MySql Table
--
-- Table structure for table `products_list`
--

CREATE TABLE IF NOT EXISTS `products_list` (
`id` int(11) NOT NULL,
  `product_name` varchar(60) NOT NULL,
  `product_desc` text NOT NULL,
  `product_code` varchar(60) NOT NULL,
  `product_image` varchar(60) NOT NULL,
  `product_price` decimal(10,2) NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `products_list`
--

INSERT INTO `products_list` (`id`, `product_name`, `product_desc`, `product_code`, `product_image`, `product_price`) VALUES
(1, 'Cool T-shirt', 'Cool T-shirt, Cotton Fabric. Wash in normal water with mild detergent.', 'TSH1', 'tshirt-1.jpg', '8.50'),
(2, 'HBD T-Shirt', 'Cool Happy Birthday printed T-shirt.Crafted from light, breathable cotton.', 'TSH2', 'tshirt-2.jpg', '7.40'),
(3, 'Survival of Fittest', 'Yellow t-shirt makes the perfect addition to your casual wardrobe.', 'TSH3', 'tshirt-3.jpg', '9.50'),
(4, 'Love Hate T-shirt', 'Stylish and trendy, this crew neck short sleeved t-shirt is made with 100% pure cotton.', 'TSH4', 'tshirt-4.jpg', '10.80');

Configuration file
<?php
$db_username        = 'root'; //MySql database username
$db_password        = ''; //MySql dataabse password
$db_name            = 'test'; //MySql database name
$db_host            = 'localhost'; //MySql hostname or IP

$currency   = '₹ '; //currency symbol
$shipping_cost  = 1.50; //shipping cost
$taxes    = array( //List your Taxes percent here.
       'VAT' => 12, 
       'Service Tax' => 5,
       'Other Tax' => 10
       );

$mysqli_conn = new mysqli($db_host, $db_username, $db_password,$db_name); //connect to MySql
if ($mysqli_conn->connect_error) {//Output any connection error
    die('Error : ('. $mysqli_conn->connect_errno .') '. $mysqli_conn->connect_error);
}
Listing Products
<?php
session_start(); //start session
include("config.inc.php"); //include config file
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Ajax Shopping Cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function(){ 
  $(".form-item").submit(function(e){
   var form_data = $(this).serialize();
   var button_content = $(this).find('button[type=submit]');
   button_content.html('Adding...'); //Loading button text 

   $.ajax({ //make ajax request to cart_process.php
    url: "cart_process.php",
    type: "POST",
    dataType:"json", //expect json value from server
    data: form_data
   }).done(function(data){ //on Ajax success
    $("#cart-info").html(data.items); //total items in cart-info element
    button_content.html('Add to Cart'); //reset button text to original text
    alert("Item added to Cart!"); //alert user
    if($(".shopping-cart-box").css("display") == "block"){ //if cart box is still visible
     $(".cart-box").trigger( "click" ); //trigger click to update the cart box.
    }
   })
   e.preventDefault();
  });

 //Show Items in Cart
 $( ".cart-box").click(function(e) { //when user clicks on cart box
  e.preventDefault(); 
  $(".shopping-cart-box").fadeIn(); //display cart box
  $("#shopping-cart-results").html('<img src="images/ajax-loader.gif">'); //show loading image
  $("#shopping-cart-results" ).load( "cart_process.php", {"load_cart":"1"}); //Make ajax request using jQuery Load() & update results
 });
 
 //Close Cart
 $( ".close-shopping-cart-box").click(function(e){ //user click on cart box close link
  e.preventDefault(); 
  $(".shopping-cart-box").fadeOut(); //close cart-box
 });
 
 //Remove items from cart
 $("#shopping-cart-results").on('click', 'a.remove-item', function(e) {
  e.preventDefault(); 
  var pcode = $(this).attr("data-code"); //get product code
  $(this).parent().fadeOut(); //remove item element from box
  $.getJSON( "cart_process.php", {"remove_code":pcode} , function(data){ //get Item count from Server
   $("#cart-info").html(data.items); //update Item count in cart-info
   $(".cart-box").trigger( "click" ); //trigger click on cart-box to update the items list
  });
 });

});
</script>
</head>
<body>
<div align="center">
<h3>Ajax Shopping Cart Example</h3>
</div>

<a href="#" class="cart-box" id="cart-info" title="View Cart">
<?php 
if(isset($_SESSION["products"])){
 echo count($_SESSION["products"]); 
}else{
 echo 0; 
}
?>
</a>

<div class="shopping-cart-box">
<a href="#" class="close-shopping-cart-box" >Close</a>
<h3>Your Shopping Cart</h3>
    <div id="shopping-cart-results">
    </div>
</div>

<?php
//List products from database
$results = $mysqli_conn->query("SELECT product_name, product_desc, product_code, product_image, product_price FROM products_list");
//Display fetched records as you please

$products_list =  '<ul class="products-wrp">';

while($row = $results->fetch_assoc()) {
$products_list .= <<<EOT
<li>
<form class="form-item">
<h4>{$row["product_name"]}</h4>
<div><img src="images/{$row["product_image"]}"></div>
<div>Price : {$currency} {$row["product_price"]}<div>
<div class="item-box">
    <div>
 Color :
    <select name="product_color">
    <option value="Red">Red</option>
    <option value="Blue">Blue</option>
    <option value="Orange">Orange</option>
    </select>
 </div>
 
 <div>
    Qty :
    <select name="product_qty">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    </select>
 </div>
 
 <div>
    Size :
    <select name="product_size">
 <option value="M">M</option>
    <option value="XL">XL</option>
    <option value="XXL">XLL</option>
    </select>
 </div>
 
    <input name="product_code" type="hidden" value="{$row["product_code"]}">
    <button type="submit">Add to Cart</button>
</div>
</form>
</li>
EOT;

}
$products_list .= '</ul></div>';

echo $products_list;
?>
</body>
</html>
Add Cart process
<?php
session_start(); //start session
include_once("config.inc.php"); //include config file
setlocale(LC_MONETARY,"en_US"); // US national format (see : http://php.net/money_format)
############# add products to session #########################
if(isset($_POST["product_code"]))
{
 foreach($_POST as $key => $value){
  $new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING); //create a new product array 
 }
 
 //we need to get product name and price from database.
 $statement = $mysqli_conn->prepare("SELECT product_name, product_price FROM products_list WHERE product_code=? LIMIT 1");
 $statement->bind_param('s', $new_product['product_code']);
 $statement->execute();
 $statement->bind_result($product_name, $product_price);
 

 while($statement->fetch()){ 
  $new_product["product_name"] = $product_name; //fetch product name from database
  $new_product["product_price"] = $product_price;  //fetch product price from database
  
  if(isset($_SESSION["products"])){  //if session var already exist
   if(isset($_SESSION["products"][$new_product['product_code']])) //check item exist in products array
   {
    unset($_SESSION["products"][$new_product['product_code']]); //unset old item
   }   
  }
  
  $_SESSION["products"][$new_product['product_code']] = $new_product; //update products with new item array 
 }
 
  $total_items = count($_SESSION["products"]); //count total items
 die(json_encode(array('items'=>$total_items))); //output json 

}

################## list products in cart ###################
if(isset($_POST["load_cart"]) && $_POST["load_cart"]==1)
{

 if(isset($_SESSION["products"]) && count($_SESSION["products"])>0){ //if we have session variable
  $cart_box = '<ul class="cart-products-loaded">';
  $total = 0;
  foreach($_SESSION["products"] as $product){ //loop though items and prepare html content
   
   //set variables to use them in HTML content below
   $product_name = $product["product_name"]; 
   $product_price = $product["product_price"];
   $product_code = $product["product_code"];
   $product_qty = $product["product_qty"];
   $product_color = $product["product_color"];
   $product_size = $product["product_size"];
   
   $cart_box .=  "<li> $product_name (Qty : $product_qty | $product_color  | $product_size ) — $currency ".sprintf("%01.2f", ($product_price * $product_qty)). " <a href=\"#\" class=\"remove-item\" data-code=\"$product_code\">×</a></li>";
   $subtotal = ($product_price * $product_qty);
   $total = ($total + $subtotal);
  }
  $cart_box .= "</ul>";
  $cart_box .= '<div class="cart-products-total">Total : '.$currency.sprintf("%01.2f",$total).' <u><a href="view_cart.php" title="Review Cart and Check-Out">Check-out</a></u></div>';
  die($cart_box); //exit and output content
 }else{
  die("Your Cart is empty"); //we have empty cart
 }
}

################# remove item from shopping cart ################
if(isset($_GET["remove_code"]) && isset($_SESSION["products"]))
{
 $product_code   = filter_var($_GET["remove_code"], FILTER_SANITIZE_STRING); //get the product code to remove

 if(isset($_SESSION["products"][$product_code]))
 {
  unset($_SESSION["products"][$product_code]);
 }
 
  $total_items = count($_SESSION["products"]);
 die(json_encode(array('items'=>$total_items)));
}
Add View Cart
<?php
session_start(); //start session
include("config.inc.php");
setlocale(LC_MONETARY,"en_US"); // US national format (see : http://php.net/money_format)
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Review Your Cart Before Buying</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h3 style="text-align:center">Review Your Cart Before Buying</h3>
<?php
if(isset($_SESSION["products"]) && count($_SESSION["products"])>0){
 $total    = 0;
 $list_tax   = '';
 $cart_box   = '<ul class="view-cart">';

 foreach($_SESSION["products"] as $product){ //Print each item, quantity and price.
  $product_name = $product["product_name"];
  $product_qty = $product["product_qty"];
  $product_price = $product["product_price"];
  $product_code = $product["product_code"];
  $product_color = $product["product_color"];
  $product_size = $product["product_size"];
  
  $item_price  = sprintf("%01.2f",($product_price * $product_qty));  // price x qty = total item price
  
  $cart_box   .=  "<li> $product_code –  $product_name (Qty : $product_qty | $product_color | $product_size) <span> $currency. $item_price </span></li>";
  
  $subtotal   = ($product_price * $product_qty); //Multiply item quantity * price
  $total    = ($total + $subtotal); //Add up to total price
 }
 
 $grand_total = $total + $shipping_cost; //grand total
 
 foreach($taxes as $key => $value){ //list and calculate all taxes in array
   $tax_amount  = round($total * ($value / 100));
   $tax_item[$key] = $tax_amount;
   $grand_total  = $grand_total + $tax_amount; 
 }
 
 foreach($tax_item as $key => $value){ //taxes List
  $list_tax .= $key. ' '. $currency. sprintf("%01.2f", $value).'<br />';
 }
 
 $shipping_cost = ($shipping_cost)?'Shipping Cost : '.$currency. sprintf("%01.2f", $shipping_cost).'<br />':'';
 
 //Print Shipping, VAT and Total
 $cart_box .= "<li class=\"view-cart-total\">$shipping_cost  $list_tax <hr>Payable Amount : $currency ".sprintf("%01.2f", $grand_total)."</li>";
 $cart_box .= "</ul>";
 
 echo $cart_box;
}else{
 echo "Your Cart is empty";
}
?>
</body>
</html>
Add CSS style
body {
 background-color: #F9F9F9;
 font-family: Georgia, "Times New Roman", Times, serif;
}
ul.products-wrp {
 list-style: none;
 padding: 0;
 max-width: 650px;
 margin-left: auto;
 margin-right: auto;  
 color: #777;  
 text-align: center;
}
ul.products-wrp li{
 display: inline-block;
 border: 1px solid #ECECEC;
 margin: 5px;
 background: #fff;
 text-align: center;
}
ul.products-wrp li h4{
 margin: 0;
 padding: 15px 5px 5px 5px;
 text-align: center;
 border-bottom: 1px solid #FAFAFA;
}
ul.products-wrp li .item-box{
 border: 1px solid #EAEAEA;
 background: #F9F9F9;
 margin: 5px;
 padding: 5px;
 text-align: left;
}
ul.products-wrp li .item-box div{
 margin-bottom:5px;
}
ul.products-wrp li .item-box button{
 margin-left: 5px;
 background: #FA1C5F;
 border: none;
 padding: 3px 8px 3px 8px;
 color: #fff;
}
ul.products-wrp li .item-box button[disabled=disabled]{
 background: #FC84A8;
}

.cart-box {
 display: block;
 width: 30px;
 background: rgba(219, 0, 33, 1) url(../images/cart-icon.png) no-repeat 20px 5px;
 padding: 4px 8px 4px 8px;
 border-radius: 30px;
 color: #fff;
 font-family: Arial;
 font-size: 16px;
 text-decoration: none;
 box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.32);
 margin-right: auto;
 margin-left: auto;
 font-weight: bold;
}
.cart-box:hover{
 background: #FA1C5F url(../images/cart-icon.png) no-repeat 20px 5px;
}
.shopping-cart-box{ 
 position: absolute;
    left:0;
    right:0;
    margin-left:auto;
    margin-right:auto;
 max-width: 450px;
 color: #FFD5D5;
 background: #FA1C5F;
 border-radius: 4px;
 padding: 10px;
 font: small Verdana, Geneva, sans-serif;  
 margin-top: 10px;
 display:none;
}
.shopping-cart-box a{
 color: #FFD5D5;
 text-decoration:none;
}
.shopping-cart-box:after {
 content: '';
 position: absolute;
 bottom: 100%;
 left: 50%;
 margin-left: -8px;
 width: 0; height: 0;
 border-bottom: 8px solid rgba(255, 0, 97, 1);
 border-right: 8px solid transparent;
 border-left: 8px solid transparent;
}
.shopping-cart-box ul.cart-products-loaded{
 margin: 0;
 padding: 0;
 list-style: none;
}
.shopping-cart-box .close-shopping-cart-box{
  float: right;
}
#shopping-cart-results ul.cart-products-loaded li{
 background: #ED0C50;
 margin-bottom: 1px;
 padding: 6px 4px 6px 10px;
}
.shopping-cart-box .remove-item{
 float:right;
 text-decoration:none;
}
.shopping-cart-box .cart-products-total{
 font-weight: bold;
 text-align: right;
 padding: 5px 0px 0px 5px;
}
.shopping-cart-box h3{
 margin: 0;
 padding: 0px 0px 5px 0px;
}

ul.view-cart {
  width: 600px;
  margin-left: auto;
  margin-right: auto;
  background: #fff;
  padding: 15px 15px 15px 25px;
  list-style: none;
}

ul.view-cart {
  width: 600px;
  margin-left: auto;
  margin-right: auto;
  background: #fff;
  padding: 15px 15px 15px 25px;
  list-style: none;
  border: 1px solid #ECECEC;
  border-radius: 4px;
}
ul.view-cart li span{
    float: right;
}
ul.view-cart li.view-cart-total{
  border-top: 1px solid #ddd;
  padding-top: 5px;
  margin-top: 5px;
  text-align: right;
}
hr{
 border: 0;
    height: 0;
    border-top: 1px solid rgba(0, 0, 0, 0.1);
    border-bottom: 1px solid rgba(255, 255, 255, 0.3);
}

Tuesday, May 12, 2015

CSS & HTML Mac Terminal shell look-alike

CSS and HTML Mac Terminal shell look-alike

<style>
.shell-wrap {
  width: 500px;
  margin: 100px auto 0 auto;
  box-shadow: 0 0 30px rgba(0,0,0,0.4);
 
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
}
 
.shell-top-bar {
  text-align: center;
  color: #525252;
  padding: 5px 0;
  margin: 0;
  text-shadow: 1px 1px 0 rgba(255,255,255,0.5);
  font-size: 0.85em;
  border: 1px solid #CCCCCC;
  border-bottom: none;
 
  -webkit-border-top-left-radius: 3px;
  -webkit-border-top-right-radius: 3px;
  -moz-border-radius-topleft: 3px;
  -moz-border-radius-topright: 3px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
 
  background: #f7f7f7; /* Old browsers */
  background: -moz-linear-gradient(top,  #f7f7f7 0%, #B8B8B8 100%); /* FF3.6+ */
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f7f7f7), color-stop(100%,#B8B8B8)); /* Chrome,Safari4+ */
  background: -webkit-linear-gradient(top,  #f7f7f7 0%,#B8B8B8 100%); /* Chrome10+,Safari5.1+ */
  background: -o-linear-gradient(top,  #f7f7f7 0%,#B8B8B8 100%); /* Opera 11.10+ */
  background: -ms-linear-gradient(top,  #f7f7f7 0%,#B8B8B8 100%); /* IE10+ */
  background: linear-gradient(to bottom,  #f7f7f7 0%,#B8B8B8 100%); /* W3C */
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f7f7f7', endColorstr='#B8B8B8',GradientType=0 ); /* IE6-9 */
}
.shell-body {
  margin: 0;
  padding: 5px;
  list-style: none;
  background: #141414;
  color: #45D40C;
  font: 0.8em 'Andale Mono', Consolas, 'Courier New';
  line-height: 1.6em;
 
  -webkit-border-bottom-right-radius: 3px;
  -webkit-border-bottom-left-radius: 3px;
  -moz-border-radius-bottomright: 3px;
  -moz-border-radius-bottomleft: 3px;
  border-bottom-right-radius: 3px;
  border-bottom-left-radius: 3px;
}
 
.shell-body li:before {
  content: '$';
  position: absolute;
  left: 0;
  top: 0;
}
.shell-body li {
  word-wrap: break-word;
  position: relative;
  padding: 0 0 0 15px;
}
</style>
<div class="shell-wrap">
  <p class="shell-top-bar">/Users/ednalan/Documents/websites/</p>
  <ul class="shell-body">
    <li>cd /Users/ednalan/Documents/websites/tutorial101.blogspot.com/git/css-shell/demo/</li>
    <li>cd ../../../../</li>
    <li>pwd</li>
    <li>/Users/ednalan/Documents/websites/</li>
  </ul>
</div>

Sunday, February 8, 2015

Dropdown with dynamic content (Ajax/CodeIgniter)

Dropdown with dynamic content (Ajax/CodeIgniter)  

Controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Ajax_sample extends CI_Controller {
/* file: application/controllers/ajax_sample.php */

    function index(){
        $data = array();

        $data['arr_field1'] = array(
            1 => 'option 1',
            2 => 'option 2',
            3 => 'option 3',
        );

        $this->load->helper('form');

        $this->load->view('sample_dropdown', $data);
    }

    function get_dropdown_values($filter){

        $this->load->model('test_model');

        $result = $this->test_model->get_options($filter);

        $this->load->helper('form');

        echo form_dropdown('field2', $result, NULL, 'id="field2"');
    }
}
Model:
<?php
class Test_model extends CI_Model {
/* file: application/models/test_model.php */

    function get_options($filter=''){

        switch($filter){
            case 1:
                $arr = array('option A', 'option B', 'option C');
            break;
            case 2:
                $arr = array('option D', 'option E', 'option F');
            break;
            case 3:
                $arr = array('option G', 'option H', 'option I');
            break;
            default: $arr = array('option Z');
        }

        return $arr;
    }
}
View:
<?php

/* file: application/views/sample_dropdown.php */


    echo form_open('insert');

        echo form_dropdown('field1', $arr_field1, NULL, 'id="field1" onchange="load_dropdown_content($(\'#field2\'), this.value)"');

        echo form_dropdown('field2', array('0' => '...'), NULL, 'id="field2"');

    echo form_close();

?>
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">

function load_dropdown_content(field_dropdown, selected_value){
    var result = $.ajax({
        'url' : '<?php echo site_url('ajax_sample/get_dropdown_values'); ?>/' + selected_value,
        'async' : false
    }).responseText;
    field_dropdown.replaceWith(result);
}

</script>
URL : http://localhost/codeIgniter_3_1_10/ajax_sample

Wednesday, November 26, 2014

How to limit the number of selected checkboxes

How to limit the number of selected checkboxes

 
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>How to limit the number of selected checkboxes</title>
  <script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
var limit = 3;
$('input.single-checkbox').on('change', function(evt) {
   if($(this).siblings(':checked').length >= limit) {
       this.checked = false;
   }
});
});//]]> 

//option 2
//$(window).load(function(){
//$('input[type=checkbox]').change(function(e){
//  if ($('input[type=checkbox]:checked').length > 3) {
//        $(this).prop('checked', false)
//        alert("allowed only 3");
//   }
//})
//});
 
</script>
</head>
<body>
         <div class="pricing-levels-3">
          <p><strong>Which level would you like? (Select 3 Levels)</strong></p>
          <input class="single-checkbox"type="checkbox" name="vehicle" value="Bike">Level 1<br>
          <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 2<br>
          <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 3<br>
          <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 4<br>
          <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 5<br>
          <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 6<br>
          <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 7<br>
        </div>
  
</body>
</html>

Sunday, November 23, 2014

How to Get Element id Using Jquery

How to Get Element id Using Jquery 

 
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
 <head>
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
 <script type="text/javascript"> 
  $(document).ready(function () {
   $('.test').click(function() { 
     alert('' + $(this).attr('id'));
   });
  });  
 </script> 
 </head>
 <body>
  <input type="button" value="Button A" class="test" id="buttonA"> 
  <input type="button" value="Button B" class="test" id="buttonB">
 </body>
</html>

Jquery .first() and .last() Function Examples

Jquery .first() and .last() Function Examples
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script>
   $(document).ready(function() { 
 
 $("#first").click(function(){       
  $("li").first().css("background-color",'#DD4B39');      
 });
 
 $("#last").click(function(){         
  $("li").last().css("background-color",'#DD4B39');
 });
 
   });
  </script>
   <div>
  <ul>
   <li>First Element</li>
   <li>Second Element</li>
   <li>Third Element</li>
   <li>Forth Element</li>
   <li>.....</li>  
   <li>.....</li>
   <li>Last Element</li>
  </ul>
 </div>
 </div>
  <button id="first" class="btn">First</button>  
  <button id="last" class="btn">Last</button>  

Pagination Using Php Codeigniter

Pagination Using Php Codeigniter 

Create Database table
CREATE TABLE `country` (
  `id` smallint(5) UNSIGNED NOT NULL,
  `printable_name` varchar(255) NOT NULL,
  `CountryAbbrev` varchar(10) DEFAULT NULL,
  `CurrencyAbbr` varchar(4) DEFAULT NULL,
  `CurrencyRate` float DEFAULT NULL,
  `CurrencyCode` varchar(3) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
 
Codeigniter Base Url Configuration 
$config['base_url'] = "http://localhost/codeIgniter3_1_10_pagination/";
 

 
Pagination Controller (pagenation.php) application\controllers\pagenation.php

 
 
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Pagenation extends CI_Controller {
 public function __construct() {
        parent:: __construct();
        $this->load->helper("url");
        $this->load->model("Countries");
        $this->load->library("pagination");
    }
 public function pagenum() 
 {
  $config = array();
        $config["base_url"] = base_url() . "pagenation/pagenum";
   $config["total_rows"] = $this->Countries->record_count();
   $config["per_page"] = 20;
  $config["uri_segment"] = 3;
  $choice = $config["total_rows"] / $config["per_page"];
  $config["num_links"] = round($choice);
     $this->pagination->initialize($config);

    $page = ($this->uri->segment(3))? $this->uri->segment(3) : 0;
    $data["results"] = $this->Countries->fetch_countries($config["per_page"], $page);
    $data["links"] = $this->pagination->create_links();
 
    $this->load->view("expagenation", $data);

 }
}
Pagination Model (Countries.php) application\models\Countries.php
<?php
class Countries extends CI_Model
{
    public function __construct() {
        parent::__construct();
    }
  public function record_count() {
        return $this->db->count_all("country");
    }
 
 public function fetch_countries($limit, $start) {
        $this->db->limit($limit, $start);
        $query = $this->db->get("country");
  if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return false;
      
   }


}
create expagenation.php file under folder name application/views/expagenation.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Codeigniter 3.1.10 Dev - Pagination</title>
  <link href="https://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
  <h1>Countries</h1>
  <div id="body">
<?php
foreach($results as $data) {
    echo $data->printable_name . " - " . $data->CountryAbbrev . "<br>";
}
?>
   <p>
   <div class="pagination">
   <?php echo $links; ?>
   </div>
   </p>
  </div>
  <p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds</p>
 </div>
  <style>
 .pagination a { 
     padding: .5rem .75rem;
    margin-left: -1px;
    line-height: 1.25;
    color: #007bff;
    background-color: #fff;
    border: 1px solid #dee2e6;
 }
 .pagination strong{ 
     z-index: 2;
    color: #fff;
    cursor: default;
    background-color: #428bca;
    border-color: #428bca;
 padding: 6px 16px;
    margin-left: -1px;
    color: #fff;
    text-decoration: none;
 }
 </style>
</body>
</html>
Run
http://localhost/codeIgniter3_1_10_pagination/pagenation/pagenum

Download http://bit.ly/2Ey5xIu

Friday, November 21, 2014

Jquery AJAX post example with Php CodeIgniter framework

Jquery AJAX post example with Php CodeIgniter framework
<HTML>
<HEAD>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function makeAjaxCall(){
 $.ajax({
  type: "post",
  url: "http://localhost/CodeIgnitorTutorial/index.php/usercontroller/verifyUser",
  cache: false,    
  data: $('#userForm').serialize(),
  success: function(json){      
  try{  
   var obj = jQuery.parseJSON(json);
   alert( obj['STATUS']);
     
   
  }catch(e) {  
   alert('Exception while request..');
  }  
  },
  error: function(){      
   alert('Error while request..');
  }
 });
}
</script>
</HEAD>
<BODY>
<form name="userForm" id="userForm" action="">
<table border="1">
 <tr>
  <td valign="top" align="left">  
  Username:- <input type="text" name="userName" id="userName" value="">
  </td>
 </tr>
 <tr>
  <td valign="top" align="left">  
  Password :- <input type="password" name="userPassword" id="userPassword" value="">
  </td>
 </tr>
 <tr>
  <td>
   <input type="button" onclick="javascript:makeAjaxCall();" value="Submit"/>
  </td>
 </tr>
</table>
</form>
 </BODY>
</HTML>
//UserController.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class UserController extends CI_Controller {
 
 public function verifyUser() {
  $userName =  $_POST['userName'];
  $userPassword =  $_POST['userPassword'];
  $status = array("STATUS"=>"false");
  if($userName=='admin' && $userPassword=='admin'){
   $status = array("STATUS"=>"true"); 
  }
  echo json_encode ($status) ; 
 }
}

Thursday, November 20, 2014

How to detect when a youtube video finishes playing using javascript

How to detect when a youtube video finishes playing using javascript


 
<div id="player"></div>
    <script src="http://www.youtube.com/player_api"></script>
    <script>
        // create youtube player
        var player;
        function onYouTubePlayerAPIReady() {
            player = new YT.Player('player', {
              height: '390',
              width: '640',
              videoId: '0Bmhjf0rKe8',
              events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
              }
            });
        }
        // autoplay video
        function onPlayerReady(event) {
            event.target.playVideo();
        }
        // when video ends
        function onPlayerStateChange(event) {        
            if(event.data === 0) {          
                alert('done');
            }
        }
    </script>

Friday, October 24, 2014

How to disable back button in browser using javascript

How to disable back button in browser using javascript
Below JavaScript code needs to be placed in the head section of the page where you don’t want the user to revisit using the back button:
<script>
  function preventBack(){window.history.forward();}
  setTimeout("preventBack()", 0);
  window.onunload=function(){null};
</script>

Saturday, August 23, 2014

The Perfect AJAX Request

The Perfect AJAX Request

$.ajax({
  type: 'POST',
  url: 'http://tutorial101.blogspot.com/feed/',
  data: { postVar1: 'theValue1', postVar2: 'theValue2' },
  beforeSend:function(){
    // this is where we append a loading image
    $('#ajax-panel').html('
Loading...
'); }, success:function(data){ // successful request; do something with the data $('#ajax-panel').empty(); $(data).find('item').each(function(i){ $('#ajax-panel').append('

' + $(this).find('title').text() + '

' + $(this).find('link').text() + '

'); }); }, error:function(){ // failed request; give feedback to user $('#ajax-panel').html('

Oops! Try that again in a few moments.

'); } });

Wednesday, August 20, 2014

Running Python Scripts on Windows with Apache and Xampp

Running Python Scripts on Windows with Apache and Xampp

create a script like the following, and put it in c:\xampp\cgi-bin\tutorial_1.py

#!/Python27/python

print "Content-type: text/html"
print 
print "<html>"
print "<head>"
print "<title>Tutorial CGI</title>"
print "</head>"
print "<body>"
print "<h1>Phython!</h1>"
print "<p>Xampp</p>"
print "<p>Tutorial101</p>"
print "<p>Phython for web</p>"
print "</body>"
print "</html>"


URL = http://localhost/cgi-bin/tutorial_1.py

Tuesday, August 19, 2014

Creating a RESTful Web Service in PHP

Creating a RESTful Web Service in PHP
<?
// process client request via url
header("Content-Type:application/json");
if (!empty($_GET['name'])) {
 
 $name = $_GET['name'];
 $price = get_price($name);
 
 if (empty($name))
  deliver_response(200,"book not found", null);
 else
  deliver_response(200,"book found", $price);
}else{
 deliver_response(400,"Invalid request", null);
}

function deliver_response($status,$status_message,$data)
{
 header("HTTP/1.1 $status $status_message");
 $response['status'] = $status;
 $response['status_message'] = $status_message;
 $response['data']=$data;

 $json_response = json_encode($response); 
 echo $json_response;
}
function get_price($find) {
 $books=array(
  "java" =>299,
  "c" =>348,
  "php" =>267
 );

 foreach ($books as $book=>$price){
 if ($book==$find) {
  return $price;
  break;
 }
 }
}
?>
//.htaccess file
# Turn on the rewrite engin
Options +FollowSymLinks
RewriteEngine On

#request routing
RewriteRule ^([a-zA-Z]*)$ index.php?name=$1 [nc,qsa]

Sunday, May 11, 2014

How to Select / Deselect All Checkboxes using jQuery

How to Select / Deselect All Checkboxes using jQuery
//index.html
<script type="text/javascript" src="jquery.min.js"></script>
<script>
$(document).ready(function() {
    $('#selecctall').click(function(event) {  //on click
        if(this.checked) { // check select status
            $('.checkbox1').each(function() { //loop through each checkbox
                this.checked = true;  //select all checkboxes with class "checkbox1"              
            });
        }else{
            $('.checkbox1').each(function() { //loop through each checkbox
                this.checked = false; //deselect all checkboxes with class "checkbox1"                      
            });        
        }
    });
   
});
</script>
<style>
ul.chk-container li {
    border-bottom: 1px solid #E7E7E7;
    padding: 3px;list-style:none;
}
</style>
<ul class="chk-container">
<li><input type="checkbox" id="selecctall"/> Selecct All</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item1"> This is Item 1</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item2"> This is Item 2</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item3"> This is Item 3</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item4"> This is Item 4</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item5"> This is Item 5</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item6"> This is Item 6</li>
<li><input class="checkbox2" type="checkbox" name="check[]" value="item6"> Do not select this</li>
</ul>

jquery custom selectbox

jquery custom selectbox
//index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html>
 <head>
  <style type='text/css'>
   div.selectBox
   {
    position:relative;
    display:inline-block;
    cursor:default;
    text-align:left;
    line-height:30px;
    clear:both;
    color:#888;
   }
   span.selected
   {
    width:167px;
    text-indent:20px;
    border:1px solid #ccc;
    border-right:none;
    border-top-left-radius:5px;
    border-bottom-left-radius:5px;
    background:#f6f6f6;
    overflow:hidden;
   }
   span.selectArrow
   {
    width:30px;
    border:1px solid #60abf8;
    border-top-right-radius:5px;
    border-bottom-right-radius:5px;
    text-align:center;
    font-size:20px;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -o-user-select: none;
    user-select: none;
    background:#4096ee;
   }
   
   span.selectArrow,span.selected
   {
    position:relative;
    float:left;
    height:30px;
    z-index:1;
   }
   
   div.selectOptions
   {
    position:absolute;
    top:28px;
    left:0;
    width:198px;
    border:1px solid #ccc;
    border-bottom-right-radius:5px;
    border-bottom-left-radius:5px;
    overflow:hidden;
    background:#f6f6f6;
    padding-top:2px;
    display:none;
   }
    
   span.selectOption
   {
    display:block;
    width:80%;
    line-height:20px;
    padding:5px 10%;
   }
   
   span.selectOption:hover
   {
    color:#f6f6f6;
    background:#4096ee; 
   }   
  </style>
  <script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
 </head>
 <body>
 <script type='text/javascript'><!--
   $(document).ready(function() {
    enableSelectBoxes();
   });
   
   function enableSelectBoxes(){
    $('div.selectBox').each(function(){
     $(this).children('span.selected').html($(this).children('div.selectOptions').children('span.selectOption:first').html());
     $(this).attr('value',$(this).children('div.selectOptions').children('span.selectOption:first').attr('value'));
     
     $(this).children('span.selected,span.selectArrow').click(function(){
      if($(this).parent().children('div.selectOptions').css('display') == 'none'){
       $(this).parent().children('div.selectOptions').css('display','block');
      }
      else
      {
       $(this).parent().children('div.selectOptions').css('display','none');
      }
     });
     
     $(this).find('span.selectOption').click(function(){
      $(this).parent().css('display','none');
      $(this).closest('div.selectBox').attr('value',$(this).attr('value'));
      $(this).parent().siblings('span.selected').html($(this).html());
     });
    });    
   }//-->
  </script>
  <div class='selectBox'>
   <span class='selected'></span>
   <span class='selectArrow'>▼</span>
   <div class="selectOptions" >
    <span class="selectOption" value="Option 1">Option 1</span>
    <span class="selectOption" value="Option 2">Option 2</span>
    <span class="selectOption" value="Option 3">Option 3</span>
   </div>
  </div>
 </body>
</html>

Ajax Contact Form with an Attachment (jQuery & PHP)

Ajax Contact Form with an Attachment (jQuery and  PHP)
//index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Ajax Contact Form</title>
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#submit_btn").click(function() { 
        //get input field values
  
        var user_name       = $('input[name=name]').val(); 
        var user_email      = $('input[name=email]').val();
        var user_phone      = $('input[name=phone]').val();
  var attach_file     = $('input[name=file_attach]')[0].files[0];
        var user_message    = $('textarea[name=message]').val();
        
        //simple validation at client's end
        //we simply change border color to red if empty field using .css()
        var proceed = true;
        if(user_name==""){ 
            $('input[name=name]').css('border-color','red'); 
            proceed = false;
        }
        if(user_email==""){ 
            $('input[name=email]').css('border-color','red'); 
            proceed = false;
        }
        if(user_phone=="") {    
            $('input[name=phone]').css('border-color','red'); 
            proceed = false;
        }
        if(user_message=="") {  
            $('textarea[name=message]').css('border-color','red'); 
            proceed = false;
        }

        //everything looks good! proceed...
        if(proceed) 
        {
   $(".loading-img").show(); //show loading image
   $(".submit_btn").hide(); //hide submit button
   
   //data to be sent to server   
   var post_data = new FormData();    
   post_data.append( 'userName', user_name );
   post_data.append( 'userEmail', user_email );
   post_data.append( 'userPhone', user_phone );
   post_data.append( 'userMessage',user_message);
   post_data.append( 'file_attach', attach_file );
   
   //instead of $.post() we are using $.ajax()
   //that's because $.ajax() has more options and can be used more flexibly.
   $.ajax({
     url: 'contact_me.php',
     data: post_data,
     processData: false,
     contentType: false,
     type: 'POST',
     dataType:'json',
     success: function(data){
     //load json data from server and output message     
     if(data.type == 'error')
     {
      output = '<div class="error">'+data.text+'</div>';
     }else{
      output = '<div class="success">'+data.text+'</div>';
      
      //reset values in all input fields
      $('#contact_form input').val(''); 
      $('#contact_form textarea').val(''); 
     }
     
     $("#result").hide().html(output).slideDown(); //show results from server
     $(".loading-img").hide(); //hide loading image
     $(".submit_btn").show(); //show submit button
     }
   });

        }
    });
    //reset previously set border colors and hide all message on .keyup()
    $("#contact_form input, #contact_form textarea").keyup(function() { 
        $("#contact_form input, #contact_form textarea").css('border-color',''); 
        $("#result").slideUp();
    });
});
</script>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<fieldset id="contact_form">
<legend>Contact Form</legend>
    <div id="result"></div>
    <label for="name"><span>Name</span>
    <input type="text" name="name" id="name" placeholder="Enter Your Name" />
    </label>
    
    <label for="email"><span>Email Address</span>
    <input type="email" name="email" id="email" placeholder="Enter Your Email" />
    </label>
    
    <label for="phone"><span>Phone</span>
    <input type="text" name="phone" id="phone" placeholder="Phone Number" />
    </label>
    
    <label for="phone"><span>Attachment</span>
    <input type="file" name="file_attach" id="file_attach" />
    </label>
    
    <label for="message"><span>Message</span>
    <textarea name="message" id="message" placeholder="Enter Your Name"></textarea>
    </label>
    
    <label><span> </span>
    <button class="submit_btn" id="submit_btn">Submit</button>
    <img src="ajax-loader.gif" class="loading-img" style="display:none">
    </label>
</fieldset>
</body>
</html>
//style.css
#contact_form{
 width:350px;
 padding:20px;
 border: 1px solid #DDD;
 border-radius: 5px;
 font-family: Arial, Helvetica, sans-serif;
 font-size: 11px;
 font-weight: bold;
 color: #666666;
 background:#FAFAFA;
 margin-right: auto;
 margin-left: auto;
}
#contact_form legend{
 font-size: 15px;
 color: #C9C9C9;
}
#contact_form label{
 display: block;
 margin-bottom:5px;
}
#contact_form label span{
 float:left;
 width:100px;
 color:#666666;
}
#contact_form input{
 height: 25px;
 border: 1px solid #DBDBDB;
 border-radius: 3px;
 padding-left: 4px;
 color: #666;
 width: 230px;
 font-family: Arial, Helvetica, sans-serif;
}
#contact_form textarea{
 border: 1px solid #DBDBDB;
 border-radius: 3px;
 padding-left: 4px;
 color: #666;
 height:100px;
 width: 230px;
 font-family: Arial, Helvetica, sans-serif;
}
.submit_btn {
 border: 1px solid #D8D8D8;
 padding: 5px 15px 5px 15px;
 color: #8D8D8D;
 text-shadow: 1px 1px 1px #FFF;
 border-radius: 3px;
 background: #F8F8F8;
}
.submit_btn:hover 
{
 background: #ECECEC;
}
.success{
 background: #CFFFF5;
 padding: 10px;
 margin-bottom: 10px;
 border: 1px solid #B9ECCE;
 border-radius: 5px;
 font-weight: normal;
}
.error{
 background: #FFDFDF;
 padding: 10px;
 margin-bottom: 10px;
 border: 1px solid #FFCACA;
 border-radius: 5px;
 font-weight: normal;
}
//contact_me.php
<?php
if($_POST)
{
 $to_Email    = "recipient_email@yourdomain.com"; //Replace with recipient email address
 $subject        = 'contact form'; //Subject line for emails
 
 //check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
 
  //exit script outputting json data
  $output = json_encode(
  array(
   'type'=>'error', 
   'text' => 'Request must come from Ajax'
  ));
  
  die($output);
    } 
 
 //check $_POST vars are set, exit if any missing
 if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userPhone"]) || !isset($_POST["userMessage"]))
 {
  $output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
  die($output);
 }

 //Sanitize input data using PHP filter_var().
 $user_Name        = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
 $user_Email       = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
 $user_Phone       = filter_var($_POST["userPhone"], FILTER_SANITIZE_STRING);
 $user_Message     = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
 
 //additional php validation
 if(strlen($user_Name)<4) // If length is less than 4 it will throw an HTTP error.
 {
  $output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
  die($output);
 }
 if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
 {
  $output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
  die($output);
 }
 if(!is_numeric($user_Phone)) //check entered data is numbers
 {
  $output = json_encode(array('type'=>'error', 'text' => 'Only numbers allowed in phone field'));
  die($output);
 }
 if(strlen($user_Message)<5) //check emtpy message
 {
  $output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
  die($output);
 }
 
 ### Attachment Preparation ###
 $file_attached = false; //initially file is not attached
 
 if(isset($_FILES['file_attach'])) //check uploaded file
 {
  //get file details we need
  $file_tmp_name    = $_FILES['file_attach']['tmp_name'];
  $file_name     = $_FILES['file_attach']['name'];
  $file_size     = $_FILES['file_attach']['size'];
  $file_type     = $_FILES['file_attach']['type'];
  $file_error    = $_FILES['file_attach']['error'];
  
  //exit script and output error if we encounter any
  if($file_error>0)
  {
   $mymsg = array( 
   1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini", 
   2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form", 
   3=>"The uploaded file was only partially uploaded", 
   4=>"No file was uploaded", 
   6=>"Missing a temporary folder" ); 
   
   $output = json_encode(array('type'=>'error', 'text' => $mymsg[$file_error]));
   die($output); 
  }
 
  //read from the uploaded file & base64_encode content for the mail
  $handle = fopen($file_tmp_name, "r");
  $content = fread($handle, $file_size);
  fclose($handle);
  $encoded_content = chunk_split(base64_encode($content));
  
  //now we know we have the file for attachment, set $file_attached to true
  $file_attached = true;
 }

 if($file_attached) //continue if we have the file
 {
  # Mail headers should work with most clients (including thunderbird)
  $headers = "MIME-Version: 1.0\r\n";
  $headers .= "X-Mailer: PHP/" . phpversion()."\r\n";
  $headers .= "From:".$user_Email."\r\n";
  $headers .= "Subject:".$subject."\r\n";
  $headers .= "Reply-To: ".$user_Email."" . "\r\n";
  $headers .= "Content-Type: multipart/mixed; boundary=".md5('boundary1')."\r\n\r\n";
 
  $headers .= "--".md5('boundary1')."\r\n";
  $headers .= "Content-Type: multipart/alternative;  boundary=".md5('boundary2')."\r\n\r\n";
  
  $headers .= "--".md5('boundary2')."\r\n";
  $headers .= "Content-Type: text/plain; charset=ISO-8859-1\r\n\r\n";
  $headers .= $user_Message."\r\n\r\n";
 
  $headers .= "--".md5('boundary2')."--\r\n";
  $headers .= "--".md5('boundary1')."\r\n";
  $headers .= "Content-Type:  ".$file_type."; ";
  $headers .= "name=\"".$file_name."\"\r\n";
  $headers .= "Content-Transfer-Encoding:base64\r\n";
  $headers .= "Content-Disposition:attachment; ";
  $headers .= "filename=\"".$file_name."\"\r\n";
  $headers .= "X-Attachment-Id:".rand(1000,9000)."\r\n\r\n";
  $headers .= $encoded_content."\r\n";
  $headers .= "--".md5('boundary1')."--"; 
 }else{
  # Mail headers for plain text mail
  $headers = 'From: '.$user_Email.'' . "\r\n" .
  'Reply-To: '.$user_Email.'' . "\r\n" .
  'X-Mailer: PHP/' . phpversion();
 }
 
 //send the mail
 $sentMail = @mail($to_Email, $subject, $user_Message, $headers);
 
 if(!$sentMail) //output success or failure messages
 {
  $output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
  die($output);
 }else{
  $output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .' Thank you for your email'));
  die($output);
 }
}
?>

Thursday, May 1, 2014

PHPMailer in CodeIgniter

PHPMailer in CodeIgniter 

The first thing we do download PHPMailer library then move it to /system/application/libraries or /application/libraries/

my_phpmailer.php
//my_phpmailer.php
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class My_PHPMailer {
    public function My_PHPMailer() {
        require_once('PHPMailer/class.phpmailer.php');
    }
}
The controller
<?php
class My_Controller extends Controller {
    public function My_Controller(){
        parent::Controller();
        $this->load->library('My_PHPMailer');
    }
    public function send_mail() {
        $mail = new PHPMailer();
        $mail->IsSMTP(); // we are going to use SMTP
        $mail->SMTPAuth   = true; // enabled SMTP authentication
        $mail->SMTPSecure = "ssl";  // prefix for secure protocol to connect to the server
        $mail->Host       = "smtp.gmail.com";      // setting GMail as our SMTP server
        $mail->Port       = 465;                   // SMTP port to connect to GMail
        $mail->Username   = "myusername@gmail.com";  // user email address
        $mail->Password   = "password";            // password in GMail
        $mail->SetFrom('info@yourdomain.com', 'Firstname Lastname');  //Who is sending the email
        $mail->AddReplyTo("response@yourdomain.com","Firstname Lastname");  //email address that receives the response
        $mail->Subject    = "Email subject";
        $mail->Body      = "HTML message
";
        $mail->AltBody    = "Plain text message";
        $destino = "addressee@example.com"; // Who is addressed the email to
        $mail->AddAddress($destino, "Ednalan");

        $mail->AddAttachment("images/phpmailer.gif");      // some attached files
        $mail->AddAttachment("images/phpmailer_mini.gif"); // as many as you want
        if(!$mail->Send()) {
            $data["message"] = "Error: " . $mail->ErrorInfo;
        } else {
            $data["message"] = "Message sent correctly!";
        }
        $this->load->view('sent_mail',$data);
    }
}

SWFUpload in CodeIgniter

SWFUpload in CodeIgniter

What is SWFUpload?
SWFUpload is a library that allows to our website’s users to upload files to the server, using a combination of Flash and JavaScript.

Download library


The form
application/views
<?php echo form_open('process_form/process'); 
// Here we put the controller's URL and the function which will process the form?>
<div>
<?php
echo form_label('File:','file');
$data = array(  'id' => 'txtFileName',
'value' => '',
'size' => 50,
'disabled' => 'disabled',
'style' => 'border: solid 1px; background-color: #FFFFFF;');
echo form_input($data); //Insert the text field which will hold the file anem once it is uploaded
?>
<span id="spanButtonPlaceholder"></span>
(20 MB max)
</div>
<div id="fsUploadProgress"></div>
<input type="hidden" name="hidFileID" id="hidFileID" value="" />
<br />
<?php
$extra = 'id="btnSubmit"';
echo form_submit('upload','Send',$extra);
echo form_close();
?>
<!-- Add JavaScript files for SWFUpload -->
<script type="text/javascript" src="<?php echo base_url();?>js/swfupload/swfupload.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/swfupload/handlers.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/swfupload/fileprogress.js"></script>
<script type="text/javascript">
var swfu;
window.onload = function () {
swfu = new SWFUpload({
// Backend settings
upload_url: "<?php echo base_url();?>process_form/upload",
file_post_name: "resume_file",
// Flash file settings
file_size_limit : "20 MB", //File size limit
file_types : "*.jpg", // or you could use something like: "*.doc;*.wpd;*.pdf",
file_types_description : "Image Files",
file_upload_limit : 0,
file_queue_limit : 1,
// Event handler settings
swfupload_loaded_handler : swfUploadLoaded,file_dialog_start_handler: fileDialogStart,
file_queued_handler : fileQueued,
file_queue_error_handler : fileQueueError,
file_dialog_complete_handler : fileDialogComplete,
//upload_start_handler : uploadStart, // I could do some client/JavaScript validation here, but I don't need to.
swfupload_preload_handler : preLoad,
swfupload_load_failed_handler : loadFailed,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,
upload_success_handler : uploadSuccess,
upload_complete_handler : uploadComplete,
// Button Settings
button_image_url : "<?php echo base_url();?>img/upload_flash_button_61x22.png",
button_placeholder_id : "spanButtonPlaceholder",
button_width: 61,
button_height: 22,
// Flash Settings
flash_url : "<?php echo base_url();?>swf/swfupload/swfupload.swf",
flash9_url : "<?php echo base_url();?>swf/swfupload/swfupload_fp9.swf",
custom_settings : {
progress_target : "fsUploadProgress",
upload_successful : false
},
// Debug settings
debug: false
});
};
</script>
The controller
<?php
class process_form extends Controller {
public function process()
{
...
//Here we take the file's name
$file_name = $this->input->post('hidFileID');
//Once we have the file's name, we could insert into the database
//or whatever is needed
...
}

public function upload()
{
$config['upload_path'] = "path/to/the/folder/for/the/file/";
 $config['allowed_types'] = 'jpg';
 $size_mb = 20; //Max file size allowed in MB
 $config['max_size'] = $size_mb * 1024; //

 $this->load->library('upload');
 $this->upload->initialize($config);
 if (!$this->upload->do_upload('resume_file'))
 {
     $this->data["params"]["error"] = array('error_upload' => $this->upload->display_errors());
     echo $this->upload->display_errors();
 }
 else
 {
     $uploaded_file = $this->upload->data();

     //Return to the form the final name of the file once it was uploaded
     echo $uploaded_file["file_name"];
 }
}
}

Related Post