article

Saturday, December 26, 2015

How to use captcha in codeigniter

How to use captcha in codeigniter

Create a controller
application/controllers/captcha.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Captcha extends CI_Controller {
   public function __construct()  {
        parent:: __construct();
  $this->load->helper("url");
  $this->load->helper('form');
  $this->load->helper('captcha');
  $this->load->library('form_validation');
    }
  public function index() {
 //validating form fields
    $this->form_validation->set_rules('username', 'Email Address', 'required');
    $this->form_validation->set_rules('user_password', 'Password', 'required');
    $this->form_validation->set_rules('userCaptcha', 'Captcha', 'required|callback_check_captcha');
    $userCaptcha = $this->input->post('userCaptcha');
 
  if ($this->form_validation->run() == false){
      // numeric random number for captcha
      $random_number = substr(number_format(time() * rand(),0,'',''),0,6);
      // setting up captcha config
      $vals = array(
             'word' => $random_number,
             'img_path' => './captcha_images/',
             'img_url' => base_url().'captcha_images/',
             'img_width' => 140,
             'img_height' => 32,
             'expiration' => 7200
            );
      $data['captcha'] = create_captcha($vals);
      $this->session->set_userdata('captchaWord',$data['captcha']['word']);
      $this->load->view('captcha', $data);
    }else {
      // do your stuff here.
      echo 'I m here clered all validations';
    }
 }
  
  public function check_captcha($str){
    $word = $this->session->userdata('captchaWord');
    if(strcmp(strtoupper($str),strtoupper($word)) == 0){
      return true;
    }
    else{
      $this->form_validation->set_message('check_captcha', 'Please enter correct words!');
      return false;
    }
 }
} 
Create folder root directory captcha_images
Create a view 
application/views/captcha.php
<html>
<head>
<title>Adding a Captcha!</title>
</head>
<body>
<h1>Captcha Example</h1>
<?php echo form_open('captcha'); ?>
<div class="formSignIn" >
  <div class="form-group">
    <input autocomplete="off" type="text" id="username" name="username" placeholder="User Email" value="<?php if(!empty($username)){ echo $username;} ?>" />
    <span class="required-server"><?php echo form_error('username','<p style="color:#F83A18">','</p>'); ?></span> </div>
  <div class="form-group">
    <input autocomplete="off" type="password" id="user_password" name="user_password" placeholder="User Password" value="" />
    <span class="required-server"><?php echo form_error('user_password','<p style="color:#F83A18">','</p>'); ?></span> </div>
  <div class="form-group">
    <label for="captcha"><?php echo $captcha['image']; ?></label>
    <br>
    <input type="text" autocomplete="off" name="userCaptcha" placeholder="Enter above text" value="<?php if(!empty($userCaptcha)){ echo $userCaptcha;} ?>" />
    <span class="required-server"><?php echo form_error('userCaptcha','<p style="color:#F83A18">','</p>'); ?></span> </div>
  <div class="form-group">
    <input type="submit" class="btn btn-success" value="Sign In" name="" />
  </div>
</div>
<?php echo form_close(); ?>
</body>
</html>

Download http://bit.ly/2Vgfjph

A Chat Example using CodeIgniter and JQuery

A Chat Example using CodeIgniter and JQuery

Controller 
chat.php
 
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Chat extends CI_Controller {
  /* The default function that gets called when visiting the page */
  public function index() {       
    $this->load->view('chat-view');
  }
  
  public function get_chats() {
    /* Connect to the mySQL database - config values can be found at:
    /application/config/database.php */
    $dbconnect = $this->load->database();
    
    /* Load the database model:
    /application/models/simple_model.php */
    $this->load->model('Chat_model');
    
    /* Create a table if it doesn't exist already */
    $this->Chat_model->create_table();
    
    echo json_encode($this->Chat_model->get_chat_after($_REQUEST["time"]));
  }
  
  public function insert_chat() {
    /* Connect to the mySQL database - config values can be found at:
    /application/config/database.php */
    $dbconnect = $this->load->database();
    
    /* Load the database model:
    /application/models/simple_model.php */
    $this->load->model('Chat_model');
    
    /* Create a table if it doesn't exist already */
    $this->Chat_model->create_table();

    $this->Chat_model->insert_message($_REQUEST["message"]); 
  }
  
  public function time() {
    echo "[{\"time\":" +  time() + "}]";
  }
  
}?>
Models 
chat_model.php
 
class Chat_model extends CI_Model {
  
  function __construct() 
  {
    /* Call the Model constructor */
    parent::__construct();
  }


  function get_last_item()
  {
    $this->db->order_by('id', 'DESC');
    $query = $this->db->get('Chats', 1);
    return $query->result();
  }
  
  
  function insert_message($message)
  {
    $this->message = $message;
    $this-> time = time();  
    $this->db->insert('Chats', $this);
  }

  function get_chat_after($time)
  {
    $this->db->where('time >', $time)->order_by('time', 'DESC')->limit(10); 
    $query = $this->db->get('Chats');
    
    $results = array();
    
    foreach ($query->result() as $row)
    {
      $results[] = array($row->message,$row->time);
    }
    
    return array_reverse($results);
  }

  function create_table()
  { 
    /* Load db_forge - used to create databases and tables */
    $this->load->dbforge();
    
    /* Specify the table schema */
    $fields = array(
                    'id' => array(
                                  'type' => 'INT',
                                  'constraint' => 5,
                                  'unsigned' => TRUE,
                                  'auto_increment' => TRUE
                              ),
                    'message' => array(
                                  'type' => 'TEXT'
                              ),
                    'time' => array(
                        'type' => 'INT'
                      )
              );
    
    /* Add the field before creating the table */
    $this->dbforge->add_field($fields);
    
    
    /* Specify the primary key to the 'id' field */
    $this->dbforge->add_key('id', TRUE);
    
    
    /* Create the table (if it doesn't already exist) */
    $this->dbforge->create_table('Chats', TRUE);
  }
}
Views 
chat-view.php
 
<html>
<head>
  <title> Chat Exmaples! </title>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
  <script> 
    var time = 0;
  
    var updateTime = function (cb) {
      $.getJSON("index.php/chat/time", function (data) {
          cb(~~data);
      });
    };
    
    var sendChat = function (message, cb) {
      $.getJSON("index.php/chat/insert_chat?message=" + message, function (data){
        cb();
      });
    }
    
    var addDataToReceived = function (arrayOfData) {
      arrayOfData.forEach(function (data) {
        $("#received").val($("#received").val() + "\n" + data[0]);
      });
    }
    
    var getNewChats = function () {
      $.getJSON("index.php/chat/get_chats?time=" + time, function (data){
        addDataToReceived(data);
        // reset scroll height
        setTimeout(function(){
           $('#received').scrollTop($('#received')[0].scrollHeight);
        }, 0);
        time = data[data.length-1][1];
      });      
    }
  
    // using JQUERY's ready method to know when all dom elements are rendered
    $( document ).ready ( function () {
      // set an on click on the button
      $("form").submit(function (evt) {
        evt.preventDefault();
        var data = $("#text").val();
        $("#text").val('');
        // get the time if clicked via a ajax get queury
        sendChat(data, function (){
          alert("dane");
        });
      });
      setInterval(function (){
        getNewChats(0);
      },1500);
    });
    
  </script>
</head>
<body>
  <h1> Chat Example on Codeigniter </h1>
  
  <textarea id="received" rows="10" cols="50">
  </textarea>
  <form>
    <input id="text" type="text" name="user">
    <input type="submit" value="Send">
  </form>
</body>
</html>

Saturday, November 14, 2015

Custom 404 Error messages with codeigniter

Custom 404 Error messages with codeigniter

Create controller application\controllers\My404.php


<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class My404 extends CI_Controller
{
   public function __construct()
   {
       parent::__construct();
   }
   public function index()
   {
       $this-<output-<set_status_header('404');
       $this-<load-<view('err404');    
  }
}

Create View application\views\err404.php


<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8">
   <title>404 Page</title>
</head>
<body>
<div>
       <p>How to Create Custom Codeigniter 404 Error Pages </p>
       <p align="center" style="font-size:55px;">Sorry Page Not Found</p>
       <p align="center" style="font-size:55px;">Error 404</p>
       <div>
           <p align="center" ><a href="<?php echo base_url(); ?>">Go Back to Home</a></p>
       </div>
</div>
</body>
</html>

add 404 to application\config\route.php $route['404_override'] = 'my404';

Monday, November 9, 2015

Jquery ajax Selectbox


Jquery ajax Selectbox  


index.php

 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
 jQuery(document).ready(function(){    
  jQuery("select[name='country']").change(function(){   
   var optionValue = jQuery("select[name='country']").val();  
   jQuery.ajax({
    type: "GET",
    url: "city.php",
    data: "country="+optionValue+"&status=1",
    beforeSend: function(){ jQuery("#ajaxLoader").show(); },
    complete: function(){ jQuery("#ajaxLoader").hide(); },
    success: function(response){
     jQuery("#cityAjax").html(response);
     jQuery("#cityAjax").show();
    }
   });    
  });
 });
</script>
Countries: 
<select name="country">
 <option value="">Please Select</option>
 <option value="1">Nepal</option>
 <option value="2">India</option>
 <option value="3">China</option>
 <option value="4">USA</option>
 <option value="5">UK</option>
</select>
<div id="ajaxLoader" style="display:none"><img src="../ajax-loader.gif" alt="loading..."></div>
<div id="cityAjax" style="display:none">
 <select name="city">
  <option value="">Please Select</option>
 </select>
</div>
city.php
<?php
$country = $_GET['country'];
if(!$country) {
 return false;
}
$cities = array(
   1 => array('Kathmandu','Bhaktapur','Patan','Pokhara','Lumbini'),
   2 => array('Delhi','Mumbai','Kolkata','Bangalore','Hyderabad','Pune','Chennai','Jaipur','Goa'),
   3 => array('Beijing','Chengdu','Lhasa','Macau','Shanghai'),
   4 => array('Los Angeles','New York','Dallas','Boston','Seattle','Washington','Las Vegas'),
   5 => array('Birmingham','Bradford','Cambridge','Derby','Lincoln','Liverpool','Manchester')
  );
$currentCities = $cities[$country];
?>
City: 
<select name="city">
 <option value="">Please Select</option>
 <?php
 foreach($currentCities as $city) {
  ?>
  <option value="<?php echo $city; ?>"><?php echo $city; ?></option>
  <?php 
 }
 ?>
</select>

Sunday, November 8, 2015

Jquery Multipele Delete


Jquery Multipele Delete





 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Jquery Multipele Delete</title>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript">
$(function(){
 $("a.delete").click(function(){
  page=$(this).attr("href");
  ids=new Array()
  a=0;
  $("input.chk:checked").each(function(){
   ids[a]=$(this).val();
   a++;
  })
  if(confirm("Are you sure want to delete?")){
    el=$(this)
    $.ajax({
     url:page,
     data:"id="+ids,
     type:"GET",
     success:function(res)
     {
      if(res==1)
      {
       $("input.chk:checked").each(function(){
        $(this).parent().parent().remove();
       })
      }
     }
    })
  }
  return false;
 })
})
</script>
</head>
<body>
<table>
<caption><a href="delete.php" class="delete">delete</a></caption>
<tr>
<td><input type="checkbox" value="1" name="chk[]" class="chk" /></td><td>category a</td>
</tr>
<tr>
<td><input type="checkbox" value="2" name="chk[]" class="chk" /></td><td>category b</td>
</tr>
<tr>
<td><input type="checkbox" value="3" name="chk[]" class="chk" /></td><td>category c</td>
</tr>
<tr>
<td><input type="checkbox" value="4" name="chk[]" class="chk" /></td><td>category d</td>
</tr>
<tr>
<td><input type="checkbox" value="5" name="chk[]" class="chk" /></td><td>category e</td>
</tr>
</table>
</body>
</html>

Add Edit Delete Using PHP Class

Add Edit Delete Using PHP Class






 
<?php
$db['host']     = 'localhost';   //Your database host, I.E. localhost
$db['username'] = 'root';        //Your database username
$db['password'] = '';            //Your database password
$db['db']       = 'mycmsdb';   //Your database name
$db['prefix']   = '';            //Your table prefix, can be left blank

class MySQLDB
{
        var $dbhost;
        var $dbuser;
        var $dbpass;
        var $dbname;
        var $dblink;
        var $qrystr;
        var $result;
        var $dbprefix;
        
        function MySQLDB($dbhost, $dbuser, $dbpass, $dbname, $dbprefix)
        {
                $this->dbhost=$dbhost;
                $this->dbuser=$dbuser;
                $this->dbpass=$dbpass;
                $this->dbname=$dbname;
                $this->dbprefix=$dbprefix;
        }
        
        function connectdb()
        {
                $this->dblink=mysql_connect($this->dbhost,$this->dbuser,$this->dbpass) or die($this->show_error());
        }
        
        function selectdb()
        {
                mysql_select_db($this->dbname) or die($this->show_error());
        }
        
        function show_error()
        {
                print mysql_error($this->dblink);
        }
        
        function query($qry="")
        {
                if(!empty($qry)) $this->qrystr=$qry;
                if(empty($this->qrystr)) die("Error: Query string is empty.");
                else $this->result=mysql_query($this->qrystr,$this->dblink) or die($this->show_error());                
        }
        
        function setqrystr($qry)
        {
                $this->qrystr=$qry;
        }
        
        function get_insert_id()
        {
                return mysql_insert_id($this->dblink);
        }
        
        function getrow()
        {
                return mysql_fetch_row($this->result);
        }
        
        function getarr()
        {
                return mysql_fetch_array($this->result,MYSQL_ASSOC);
        }
        
        function getobj()
        {
                return mysql_fetch_object($this->result);
        }
        
        function getaffectedrows()
        {
                return mysql_affected_rows($this->dblink);
        }
        
        function getrownum()
        {
                return mysql_num_rows($this->result);
        }
        
        function freeresult()
        {
                mysql_free_result($this->result);
        }
        
        function closedb()
        {
                mysql_close($this->dblink);
        }
        
        function __destruct()
        {
                mysql_close($this->dblink);
        }
        
        function tb($tablename)
        {
                if(empty($this->dbprefix))        return $tablename;
                else return $this->dbprefix."_".$tablename;
        }
}
//Hostname,Username,Password,Database,table prefix
$db=new MySQLDB($db['host'], $db['username'], $db['password'], $db['db'], $db['prefix']);
$db->connectdb();
$db->selectdb();
?>

<?
//Examples
$qry="SELECT * FROM rme_bookings WHERE city='angeles'";
$db->query($qry);
$row=$db->getrow();
$maxtime=$row[0]; 
echo $maxtime;
//Udate
$qry="UPDATE ".$db->tb("admin")." SET uname='$uname', pwd='$pwd', email='$email' WHERE uid=$auid";
$db->query($qry);
 if($db->getaffectedrows()==0) $err[0]="Nothing altered! Try again.";
 else  $err[0]="Profile updated successfully."; 

$qry="SELECT conf_value FROM ".$db->tb("configuration")." WHERE conf_name='AUTO_FILE_DELETE'";
$db->query($qry);
$row=$db->getrow();
if($row[0]=="Yes")
{
 $now=time();
 $qry="SELECT dir, file_name FROM ".$db->tb("fileinfo")." WHERE expire_time<$now";
 $db->query($qry);
 while($row=$db->getrow())
 {
  @unlink("uploads/".$row[1]."/".$row[2]);
  @rmdir("uploads/".$row[1]);
 }
 $qry="DELETE FROM ".$db->tb("fileinfo")." WHERE expire_time<$now";
 $db->query($qry);
}

 $qry="SELECT uname, pwd, email FROM ".$db->tb("admin")." WHERE uid=$auid";
$db->query($qry);
 $row=$db->getrow();
 $uname=$row[0];
$pwd=$row[1];
 $email=$row[2];
  
$qry="SELECT * FROM ".$db->tb("fileinfo")." ORDER BY upload_time DESC";
$db->query($qry);
while($row=$db->getarr())
{
 $status="Ok";
 $idkey = $row["idkey"];
 if($row["no_of_dwnld"]>=$row["max_dwnld"]) $status="Count Exceeded";
 if($row["expire_time"]<time()) $status="Expired";
 if($row["link_status"]==0) $status="Suspended";
}   

$qry="DELETE FROM ".$db->tb("adminlog")." WHERE uid=".$row[0]." and timein=".$row1[0];
$db->query($qry);  

$qry="INSERT INTO ".$db->tb("adminlog")."(uid,timein,ip) VALUES(".$row[0].",".time().",'".$_SERVER['REMOTE_ADDR']."')";
$db->query($qry);

$db->query("UPDATE ".$db->tb("admin")." SET `pwd`='".$md5."'");
$row=$db->getrow();
?>

like Rating with Jquery and Ajax

like Rating with Jquery and Ajax
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>like Rating with Jquery and Ajax</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".like").click(function()
{
var id=$(this).attr("id");
var name=$(this).attr("name");
var dataString = 'id='+ id + '&name='+ name;
$("#votebox").slideDown("slow");
$("#flash").fadeIn("slow");
$.ajax
({
type: "POST",
url: "rating.php",
data: dataString,
cache: false,
success: function(html)
{
$("#flash").fadeOut("slow");
$("#content").html(html);
} 
});
});
$(".close").click(function()
{
$("#votebox").slideUp("slow");
});

});
</script>
<style>

body
{
font-family:Arial, Helvetica, sans-serif;
font-size:13px;

}
a
{
text-decoration:none
}
a:hover
{
text-decoration:none

}
#votebox
{
border:solid 1px #dedede; padding:3px;
display:none;
padding:15px;
width:700px;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
}
.close
{
color:#333
}
#greebar
{
float:left;
background-color:#aada37;
border:solid 1px #698a14;
width:0px;
height:12px;
}
#redbar
{
float:left;
background-color:#cf362f;
border:solid 1px #881811;
width:0px;
height:12px;
}

#flash
{
display:none;
font-size:10px;
color:#666666;
}
#close
{
float:right; font-weight:bold; padding:3px 5px 3px 5px; border:solid 1px #333;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
}
h1
{
font-family:'Georgia', Times New Roman, Times, serif;
font-size:36px;
color:#333333;
}
</style>
</head>
<body>
<div style="margin:50px">
<a href="#" class="like" id="1" name="up">Like</a> -- <a href="#" class="like" id="1" name="down">Dislike</a>
<div id="votebox">
<span id='close'><a href="#" class="close" title="Close This">X</a></span>
<div style="height:13px">
<div id="flash">Loading........</div>
</div>
<div id="content"></div>
</div>
</div>
</body>
</html>
rating.php
<?php
$mysql_hostname = "localhost";
$mysql_user = "username";
$mysql_password = "password";
$mysql_database = "database";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) 
or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
if($_POST['id'])
{
$id=mysql_escape_String($_POST['id']);
$name=mysql_escape_String($_POST['name']);
mysql_query("update messages set $name=$name+1 where id='$id'");
$result=mysql_query("select up,down from messages where id='$id'");
$row=mysql_fetch_array($result);
$up_value=$row['up'];
$down_value=$row['down'];
$total=$up_value+$down_value;
$up_per=($up_value*100)/$total;
$down_per=($down_value*100)/$total;
?>
<div style="margin-bottom:10px">
<b>Ratings for this blog</b> ( <?php echo $total; ?> total)
</div>
<table width="700px">
<tr>
<td width="30px"></td>
<td width="60px"><?php echo $up_value; ?></td>
<td width="600px"><div id="greebar" style="width:<?php echo $up_per; ?>%"></div></td>
</tr>
<tr>
<td width="30px"></td>
<td width="60px"><?php echo $down_value; ?></td>
<td width="600px"><div id="redbar" style="width:<?php echo $down_per; ?>%"></div></td>
</tr>
</table>
<?php
}
?>

Friday, November 6, 2015

Using phpMailer to Send Mail through PHP

Using phpMailer to Send Mail through PHP

Download the PHPMailer script  

index.html
<form method="post" action="email.php">
  Email: <input name="email" id="email" type="text" /><br />
  Message:<br />
  <textarea name="message" id="message" rows="15" cols="40"></textarea><br />
  <input type="submit" value="Submit" />
</form>
mail.php
<?php
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;
require("lib/PHPMailer/PHPMailerAutoload.php");
$mail = new PHPMailer();
// set mailer to use SMTP
$mail->IsSMTP();
// As this email.php script lives on the same server as our email server
// we are setting the HOST to localhost
$mail->Host = "localhost";  // specify main and backup server
$mail->SMTPAuth = true;     // turn on SMTP authentication
// When sending email using PHPMailer, you need to send from a valid email address
// In this case, we setup a test email account with the following credentials:
// email: send_from_PHPMailer@tutorial101.blogspot.com
// pass: password
$mail->Username = "send_from_PHPMailer@tutorial101.blogspot.com";  // SMTP username
$mail->Password = "123456789"; // SMTP password
// $email is the user's email address the specified
// on our contact us page. We set this variable at
// the top of this page with:
// $email = $_REQUEST['email'] ;
$mail->From = $email;
// below we want to set the email address we will be sending our email to.
$mail->AddAddress("ednalan@tutorial101.blogspot.com", "Ednalan");
// set word wrap to 50 characters
$mail->WordWrap = 50;
// set email format to HTML
$mail->IsHTML(true);
$mail->Subject = "You have received feedback from your website!";
// $message is the user's message they typed in
// on our contact us page. We set this variable at
// the top of this page with:
// $message = $_REQUEST['message'] ;
$mail->Body    = $message;
$mail->AltBody = $message;
if(!$mail->Send())
{
   echo "Message could not be sent. <p>";
   echo "Mailer Error: " . $mail->ErrorInfo;
   exit;
}
echo "Message has been sent";
?>

Thursday, November 5, 2015

jQuery Get Selected Radio Button Value

jQuery Get Selected Radio Button Value
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Get Selected Radio Button Value</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("input[type='button']").click(function(){
         var radioValue = $("input[name='gender']:checked").val();
            if(radioValue){
                alert("Your are a - " + radioValue);
            }
        });
        
    });
</script>
</head> 
<body>
    <h4>Please select your gender.</h4>
    <p> 
        <label><input type="radio" name="gender" value="male">Male</label> 
        <label><input type="radio" name="gender" value="female">Female</label>
    </p>
    <p><input type="button" value="Get Value"></p>
</body>
</html>      

Friday, October 16, 2015

Jquery UI Datepicker Change background color Unavailable date

Jquery UI Datepicker Change background color Unavailable date
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Change background color Unavailable date</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.17/themes/start/jquery-ui.css">
<script type='text/javascript' src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.17/jquery-ui.min.js"></script>
  <style type='text/css'>
    .ui-datepicker td.ui-state-disabled>span{background:#F70C0C;}
.ui-datepicker td.ui-state-disabled{opacity:100;}
  </style>
<script type='text/javascript'>//<![CDATA[
var unavailableDates = ["17-10-2015", "18-10-2015", "20-10-2015"];
function unavailable(date) {
    dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
    if ($.inArray(dmy, unavailableDates) == -1) {
        return [true, ""];
    } else {
        return [false, "", "Unavailable"];
    }
}
$(function() {
    $("#iDate").datepicker({
        dateFormat: 'dd MM yy',
        beforeShowDay: unavailable
    });

});
//]]> 
</script>
</head>
<body>
  <input id="iDate">
</body>
</html>

Jquery Datepicker Load Specified Date


Jquery Datepicker Load Specified Date
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Datepicker</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/start/jquery-ui.css">
  <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
  <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <script>
  $(function() {
var availableDates = [
<?php 
for ($x = 0; $x <= 10; $x++) {
?>
"<?php echo $x; ?>-10-2015",
<?php } ?>];

function available(date) {
  dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
  if ($.inArray(dmy, availableDates) != -1) {
    return [true, "","Available"];
  } else {
    return [false,"","unAvailable"];
  }
}

$('#date').datepicker({ 
 beforeShowDay: available,
 // The hidden field to receive the date
    altField: "#dateHidden",
    // The format you want
    altFormat: "yy-mm-dd",
    // The format the user actually sees
    dateFormat: "dd/mm/yy",
    onSelect: function (date) {
        alert(date);        
    } 
}); 
});
  </script>
</head>
<body>
<div id="date"></div>
 Not hidden just for the sake of demonstration: <input type="text" id="dateHidden" />
</body>
</html>

Saturday, September 5, 2015

Execute a Python File in Notepad ++?

Execute a Python File in Notepad ++

To set up Notepad++ for Python developing

1. Install http://tutorial101.blogspot.com/2015/09/notepad-python-script.html
2. Create a batch script that would run a python script





Path
C:\Python27\pt.bat


Code pt.bat

@ECHO OFF
C:\Python27\python.exe "%1"
echo.
PAUSE
@ECHO ON 


3. Run notepadd++ ex. helloword.py

paste url C:\Python27\pt.bat "$(FULL_CURRENT_PATH)"
and assign a shortcut. Press that shortcut now with a python file opened

Notepad++ Python Script

Notepad++ Python Script

A Python Scripting plugin for Notepad++.

Complete easy script access to all of the editor's features (including absolutely everything in Scintilla). Configurable menus and toolbar options, assign shortcuts to scripts.

Features
Full scripting access to all Notepad++ features with normal Python function calls (e.g. notepad.new(), notepad.open('filename.txt') )
Full scripting access to all Scintilla features (the edit component in N++)
Configurable menus and toolbars - assign shortcuts to scripts
Respond to Notepad++ and Scintilla events with script functions
Call other plugin menu commands programmatically
Scriptable regular expression search and replace

Notepad++ Python Script Web Site>

Friday, September 4, 2015

AngularJS Forms Custom Model Update Triggers

AngularJS Forms Custom Model Update Triggers

The novalidate attribute

1. updateOn option of the ng-model-options directive. The model value updates when the focus is lost.
2. debounce option delays the model update. update the model after 250 milliseconds
3. updateOn and debounce option. Setting the debounce value of blur event to ‘0’ indicates that the model trigger immediate update when it is out of focus.
<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>AngularJS Custom Model Update</title>  
 </head>
 <body ng-app="formApp">
  <div ng-controller="FormController">
   <form novalidate>
    Name : <input type="text" ng-model="employee.name" ng-model-options="{updateOn:'blur'}"/></br>
    Gender : <input type="text" ng-model="employee.gender" ng-model-options="{debounce:250}"/></br>
    E-mail : <input type="email" ng-model="employee.email" ng-model-options="{updateOn:'blur',debounce:{blur:0} }"/></br>
   </form>
     <p>Name : {{employee.name}}</p>
   <p>Gender : {{employee.gender}}</p>
   <p>Email : {{employee.email}}</p>
  </div>
  </div>
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
 <script type="text/javascript">
  var app = angular.module('formApp', []);
  app.controller('FormController', function($scope) {
   $scope.employee = {};

  });
 </script>
</body>
</html>

AngularJS

AngularJS


AngularJS is a JavaScript framework. It can be added to an HTML page.

AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.

AngularJS is perfect for Single Page Applications (SPAs).

AngularJS is easy to learn.
https://angularjs.org/

Saturday, August 15, 2015

TiTatoggle : CSS Toggle Button for Bootstrap

TiTatoggle : CSS Toggle Button for Bootstrap

Pure css toggle buttons based on the bootstrap checkbox pattern.The Pattern is the same as Twitter-Bootstrap.

Demo     Download

Saturday, August 1, 2015

Example Bootstrap Progress Bar

Example Bootstrap Progress Bar
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Bootstrap Progress Bar</title>
<!-- these are library file of css-->
<link rel="stylesheet" href="bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="bootstrap/3.3.5/css/bootstrap-theme.min.css">
<!-- this is library file of Jquery-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!--this is library file of javascript-->
<script src="bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- this css used for body-->
<script src="js/modernizr.js" type="text/javascript"></script>
</head>
<body>
<script>
$(document).ready(function() {
if (!Modernizr.meter) {
alert('Sorry your browser does not support HTML5 progress bar');
} else {
var progressbar = $('#progressbar'),
max = progressbar.attr('max'),
time = (1000 / max) * 5,
value = progressbar.val();
var loading = function() {
value += 1;
addValue = progressbar.val(value);
$('.progress-value').html(value + '%');
if (value == max) {
clearInterval(animate);
}
};
var animate = setInterval(function() {
loading();
}, time);
}
;
});
</script>
<style>
body {
background-color: #f9f9f9;
}
/*=== This is a hole container part===*/
.container{
width: 890px;
height:130px;
}
/*=== This is a hole progress bar css===*/
.demo-wrapper {
width: 500px;
margin: 30px auto 0;
}
.html5-progress-bar {
padding: 15px 15px;
border-radius: 3px;
background-color: #626262;
box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, .2);
}
.html5-progress-bar progress {
background-color: #F1F1F1;
border: 0;
width: 80%;
height: 18px;
border-radius: 9px;
}
.html5-progress-bar progress::-webkit-progress-bar {
background-color: #f3f3f3;
border-radius: 9px;
}
.html5-progress-bar progress::-webkit-progress-value {
background: #5CB85C;
background: -moz-linear-gradient(top, #5CB85C 0%, #5CB85C 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#5CB85C), color-stop(100%,#a5c956));
background: -webkit-linear-gradient(top, #5CB85C 0%,#a5c956 100%);
background: -o-linear-gradient(top, #5CB85C 0%,#a5c956 100%);
background: -ms-linear-gradient(top, #5CB85C 0%,#a5c956 100%);
background: linear-gradient(to bottom, #5CB85C 0%,#a5c956 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#5CB85C', endColorstr='#a5c956',GradientType=0 );
border-radius: 9px;
}
.html5-progress-bar progress::-moz-progress-bar {
background: #5CB85C;
background: -moz-linear-gradient(top, #5CB85C 0%, #a5c956 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#5CB85C), color-stop(100%,#a5c956));
background: -webkit-linear-gradient(top, #5CB85C 0%,#a5c956 100%);
background: -o-linear-gradient(top, #5CB85C 0%,#a5c956 100%);
background: -ms-linear-gradient(top, #5CB85C 0%,#a5c956 100%);
background: linear-gradient(to bottom, #5CB85C 0%,#a5c956 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#5CB85C', endColorstr='#a5c956',GradientType=0 );
border-radius: 9px;
}
/*=== This is a % value of progress bar css===*/
.html5-progress-bar .progress-value {
padding: 0px 5px;
line-height: 20px;
margin-left: 5px;
font-size: .9em;
color: #F5F5F5;
height: 18px;
float: right;
}
</style>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="demo-wrapper html5-progress-bar">
<div class="progress-bar-wrapper">
<progress id="progressbar" value="0" max="100"></progress>
<span class="progress-value">0%s</span>
</div>
</div>
</div>
</div>
</div>

</body>
</html>

Thursday, July 23, 2015

Example Bootstrap Carousel

Example Bootstrap Carousel
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example of Bootstrap 3 Carousel</title>
<!-- these are library file of css-->
<link rel="stylesheet" href="bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="bootstrap/3.3.5/css/bootstrap-theme.min.css">
<!-- this is library file of Jquery-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!--this is library file of javascript-->
<script src="bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- this css used for body-->
<style type="text/css">
h2{
margin: 0;
color: #666;
padding-top: 90px;
font-size: 52px;
font-family: "trebuchet ms", sans-serif;
}
.item{
background: #333;
text-align: center;
height: 300px !important;
}
.carousel{
margin-top: 20px;
}
.bs-example{
margin: 20px;
}
</style>
</head>
<body>
<!--this DIV use for carousel and sliding time-->
<div class="bs-example">
<div id="myCarousel" class="carousel slide" data-interval="3000" data-ride="carousel">
<!-- this DIV use for carousel indicators for slider-->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
</ol>
<!--Wrapper for carousel items which are show in output form-->
<div class="carousel-inner">
<!--this is first slider page-->
<div class="active item">
<h2>Slide 1</h2>
<div class="carousel-caption">
<h3>First slide label</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
</div>
<!-- this is second slider page-->
<div class="item">
<h2>Slide 2</h2>
<div class="carousel-caption">
<h3>Second slide label</h3>
<p>Aliquam sit amet gravida nibh, facilisis gravida odio.</p>
</div>
</div>
<!-- this is third slider page-->
<div class="item">
<h2>Slide 3</h2>
<div class="carousel-caption">
<h3>Third slide label</h3>
<p>Praesent commodo cursus magna, vel scelerisque nisl consectetur.</p>
</div>
</div>
</div>
<!-- this is carousel controls for used of next and previous pages slider-->
<a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
</body>
</html>

Tuesday, July 21, 2015

Launch Bootstrap Modal on page load

Launch Bootstrap Modal on page load JS
<script type="text/javascript">
    $(window).load(function(){
        $('#myModal').modal('show');
    });
</script>
HTML
<div class="modal hide fade" id="myModal">
  <div class="modal-header">
    <a class="close" data-dismiss="modal">×</a>
    <h3>Modal header</h3>
  </div>
  <div class="modal-body">
    <p>One fine body…</p>
  </div>
  <div class="modal-footer">
    <a href="#" class="btn">Close</a>
    <a href="#" class="btn btn-primary">Save changes</a>
  </div>
</div>

Disable odd checkbox of Checkbox list using jQuery

Disable odd checkbox of Checkbox list using jQuery
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Disable odd checkbox of Checkbox list using jQuery</title>
  <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
  <style type='text/css'>
    body {
    font-family: Calibri;
    font-size : 12pt;
    padding :10px;
}
  </style>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
$(document).ready(function () {
    $("input[name='tech']").filter(':even').attr('disabled', true);
    $("input[name='hobbies']").filter(':odd').attr('disabled', true);
});
});//]]>  

</script>
</head>
<body>
  <b>1st Checkbox List: </b>
<br/>
<input type="checkbox" name="tech" value="jQuery" />jQuery
<br/>
<input type="checkbox" name="tech" value="JavaScript" />JavaScript
<br/>
<input type="checkbox" name="tech" value="Prototype" />Prototype
<br/>
<input type="checkbox" name="tech" value="Dojo" />Dojo
<br/>
<input type="checkbox" name="tech" value="Mootools" />Mootools
<br/>
<br/>
<b>2nd Checkbox List: </b>
<br/>
<input type="checkbox" name="hobbies" value="Sports" />Sports
<br/>
<input type="checkbox" name="hobbies" value="Racing" />Racing
<br/>
<input type="checkbox" name="hobbies" value="Singing" />Singing
<br/>
<input type="checkbox" name="hobbies" value="Writing" />Writing
<br/>
<input type="checkbox" name="hobbies" value="Travelling" />Travelling
<br/>
<input type="checkbox" name="hobbies" value="Cooking" />Cooking
<br/>
</body>
</html>

Image Preview Thumbnails before upload using jQuery & PHP

Image Preview Thumbnails before upload using jQuery & PHP
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script>
$(document).ready(function(){
    $('#file-input').on('change', function(){ //on file input change
        if (window.File && window.FileReader && window.FileList && window.Blob) //check File API supported browser
        {
            $('#thumb-output').html(''); //clear html of output element
            var data = $(this)[0].files; //this file data
            
            $.each(data, function(index, file){ //loop though each file
                if(/(\.|\/)(gif|jpe?g|png)$/i.test(file.type)){ //check supported file type
                    var fRead = new FileReader(); //new filereader
                    fRead.onload = (function(file){ //trigger function on successful read
                    return function(e) {
                        var img = $('<img/>').addClass('thumb').attr('src', e.target.result); //create image element 
                        $('#thumb-output').append(img); //append image to output element
                    };
                    })(file);
                    fRead.readAsDataURL(file); //URL representing the file's data.
                }
            });
            
        }else{
            alert("Your browser doesn't support File API!"); //if File API is absent
        }
    });
});
</script>
<style>
.thumb{
    margin: 10px 5px 0 0;
    width: 100px;
}
.alert-info {
  background-color: #d9edf7;
  border-color: #bce8f1;
  color: #31708f;
}
.alert {
  padding: 5px 10px;
  margin-bottom: 10px;
  border: 1px solid transparent;
  border-radius: 4px;
}
</style>
<div class="alert alert-info">
<input type="file" id="file-input" multiple=""><p></p>
<div id="thumb-output"></div>
</div>

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

Related Post