article

Sunday, June 11, 2017

Python Django - Admin Interface

Python Django - Admin Interface

Django provides a ready-to-use user interface for administrative activities. Django automatically generates admin UI based on your project models.

Starting the Admin Interface

The Admin interface depends on the django.countrib module. To have it working you need to make sure some modules are imported in the INSTALLED_APPS and MIDDLEWARE_CLASSES tuples of the myproject/settings.py file.

For INSTALLED_APPS make sure you have −

INSTALLED_APPS = (
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'myapp', #created application myapp folder
)

For MIDDLEWARE_CLASSES −

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

Before launching your server, to access your Admin Interface, you need to initiate the database −

C:\myprojectdjango>python manage.py migrate

migrate will create necessary tables or collections depending on your db type, necessary for the admin interface to run.

Create user

C:\myprojectdjango>python manage.py createsuperuser

input username, email address and password
Superuser created succesfully

Now to start the Admin Interface, we need to make sure we have configured a URL for our admin interface. Open the myproject/url.py and you should have something like −
 
from django.conf.urls import patterns, include, url
from django.contrib import admin

from django.contrib import admin
admin.autodiscover()

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]

Now just run the server.

 C:\myprojectdjango>python manage.py runserver

 And your admin interface is accessible at: http://127.0.0.1:8000/admin/

login using created username and password

Python Django - Install Create project and run

Python Django - Install Create project and run

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Django makes it easier to build better web apps quickly and with less code.

You can download the latest version of Django from the link http://www.djangoproject.com/download 

Windows Installation

C:\>pip install Django==1.9.7
c:\>python -c "import django; print(django.get_version())"

Create a Project
c:\>django-admin startproject myprojectdjango

This will create a "myprojectdjango" folder with the following structure −
myprojectdjango/
   manage.py
   myproject/
      __init__.py
      settings.py
      urls.py
      wsgi.py

manage.py − This file is kind of your project local django-admin for interacting with your project via command line (start the development server, sync db...). To get a full list of command accessible via manage.py you can use the code −
__init__.py − Just for python, treat this folder as package.
settings.py − As the name indicates, your project settings.
urls.py − All links of your project and the function to call. A kind of ToC of your project.
wsgi.py − If you need to deploy your project over WSGI.

Setting Up Your Project
Your project is set up in the subfolder myproject/settings.py. Following are some important options you might need to set −

DEBUG = True

This option lets you set if your project is in debug mode or not. Debug mode lets you get more information about your project's error. Never set it to ‘True’ for a live project. However, this has to be set to ‘True’ if you want the Django light server to serve static files. Do it only in the development mode.

DATABASES = {
   'default': {
      'ENGINE': 'django.db.backends.sqlite3',
      'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
      'USER': '',
      'PASSWORD': '',
      'HOST': '',
      'PORT': '',
   }
}

Database is set in the ‘Database’ dictionary. The example above is for SQLite engine. As stated earlier, Django also supports −

MySQL (django.db.backends.mysql)
PostGreSQL (django.db.backends.postgresql_psycopg2)
Oracle (django.db.backends.oracle) and NoSQL DB
MongoDB (django_mongodb_engine)
Before setting any new engine, make sure you have the correct db driver installed.

Now that your project is created and configured make sure it's working −

c:\>myprojectdjango>python manage.py runserver

Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Monday, May 29, 2017

Python Function and Loop Example code

Python Function and Loop Example code
 
#!/usr/bin/python

#A function is created with the def keyword
def function():
    pass
#-------------------------------------------------------   
def printme( str ):
   "This prints a passed string into this function"
   print (str)
   return
# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")
#-------------------------------------------------------
# Function definition is here
def changeme( mylist ):
   "This changes a passed list into this function"
   print ("Values inside the function before change: ", mylist)
   mylist[2]=50
   print ("Values inside the function after change: ", mylist)
   return

# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
#-------------------------------------------------------
# Function definition is here
def printinfo( name, age ):
   "This prints a passed info into this function"
   print ("Name: ", name)
   print ("Age ", age)
   return
# Now you can call printinfo function
printinfo( age=50, name="miki" )
#-------------------------------------------------------

print "1 + 1 =", 1 + 1
print "2 * (2 + 3) =", 2 * (2+3)
print "1.2 / 0.3 =", 1.2 / 0.3
print "5 / 2 =", 5 / 2
# 1 + 1 = 2
# 2 * (2 + 3) = 10
# 1.2 / 0.3 = 4.0
# 5 / 2 = 2

#functions
def square(number):
 sqr_num = number **2
 return sqr_num
 
input_num = 5
output_num = square(input_num)
print "print output", output_num 

#function morethan one input
def returnDifference(n1, n2):
 """Return the difference between two numbers.
 Subtracts n2 from n1."""
 return n1 - n2
print "print output", returnDifference(1,1)
 
def add_two_numbers(num1, num2):
 sum = num1 + num2
 return sum
print "print output", add_two_numbers(1,1)
print "print output", add_two_numbers(1,2) 

#loop
n = 1
while (n < 5):
 print "n =", n
 n = n +1
 print "Loop finished "
 
for n in range(1, 5):
 print"n =", n
 print "Loop finished " 
 
for i in range(0, 4):
 if i == 2:
    break
 print i
print "Finished with i = ", str(i) 

phrase = "it marks the spot"
for letter in phrase:
  if letter == "ks":
    print "yes ks" 
  break
else:
  print "There was no 'X' in the phrase"

tries = 0
while tries < 3:
 password = raw_input("Password: ")
 if password == "ednalan":
     break
 else:
     tries = tries +1
else:
     print "Suspicious activity. The authorities have been alerted."

total = 0 # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
   # Add both the parameters and return them."
   total = arg1 + arg2; # Here total is local variable.
   print ("Inside the function local total : ", total)
   return total
# Now you can call sum function
sum( 10, 20 )
print ("Outside the function global total : ", total )  
#-------------------------------------------------------------------
def add_two_numbers(num1, num2):
    sum = num1 + num2
    return sum
    print(add_two_numbers(1,1)) #2
#---------------------------------------------------------------------
n = 1
while (n < 5):
  print("n =", n)
  n = n + 1
print("Loop finished")    
#---------------------------------------------------------------------
numbers = [22, 34, 12, 32, 4]
sum = 0
i = len(numbers)
while (i != 0):
   i -= 1
   sum = sum + numbers[i]
print "The sum is: ", sum
#---------------------------------------------------------------------
import random
while (True):
   val = random.randint(1, 30)
   print val, # 14 14 30 16 16 20 23 15 17 22
   if (val ==  22):
      break
#---------------------------------------------------------------------
import random
num = 0
while (num < 1000):
   num = num + 1
   if (num % 2) == 0:
      continue
   print num,   
#---------------------------------------------------------------------
import random as rnd
for i in range(10):
   print rnd.randint(1, 10),    # 1 2 5 10 10 8 2 9 7 2

def root(x):
   return x * x
#---------------------------------------------------------------------
def root(x):
   return x * x
a = root(2)
b = root(15)
print a, b  
#---------------------------------------------------------------------
x = 15
def function():
   global x
   x = 45
function()
print x # 45
#---------------------------------------------------------------------
print 4 in (2, 3, 5, 6)
for i in range(25):
   print i, # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#---------------------------------------------------------------------
def gen():
   x = 11
   yield x
it = gen()
print it.next() # 11
#---------------------------------------------------------------------
def showModuleName():
    print __doc__
def getModuleFile():
   return __file__
a = showModuleName()
b = getModuleFile()
print a, b
#---------------------------------------------------------------------
def f():
    """This function prints a message """
    print "Today it is a cloudy day"
print isinstance(f, object) # True
print id(f) # 3077407212
print f.func_doc # This function prints a message 
print f.func_name # f
#---------------------------------------------------------------------
from math import sqrt
def cube(x):
    return x * x * x     
print abs(-1)
print cube(9)
print sqrt(81)
#---------------------------------------------------------------------
def showMessage(msg):
    print msg
def cube(x):
    return x * x * x   
x = cube(3)    
print x # 27
showMessage("Computation finished.") # Computation finished.
print showMessage("Ready.") # Ready.
#---------------------------------------------------------------------
n = [1, 2, 3, 4, 5]
def stats(x):
    mx = max(x)
    mn = min(x)
    ln = len(x)
    sm = sum(x)
    return mx, mn, ln, sm    
mx, mn, ln, sm = stats(n)
print stats(n) # (5, 1, 5, 15)
print mx, mn, ln, sm # 5 1 5 15
#---------------------------------------------------------------------
def C2F(c):
    return c * 9/5 + 32
print C2F(100) # 212
print C2F(0) # 32
print C2F(30) # 86
#---------------------------------------------------------------------
def power(x, y=2):
    r = 1
    for i in range(y):
       r = r * x
    return r
print power(3) # 9
print power(3, 3) #27
print power(5, 5) # 3125
#---------------------------------------------------------------------
def display(name, age, sex):
   print "Name: ", name
   print "Age: ", age
   print "Sex: ", sex
display("Lary", 43, "M") # Name:  Lary Age:  43 Sex:  M
display("Joan", 24, "F") # Name:  Joan Age:  24 Sex:  F


Monday, May 1, 2017

Create Custom Shortcode in WordPress Post, Page and Plugin

Create Custom Shortcode in WordPress Post, Page and Plugin

Edit current theme's function.php add this code


function recent_posts_func( $atts, $content = NULL ){
    $content = $content?$content:'Latest Posts';
    $a = shortcode_atts(
        array(
            'posts'=>5
        ),
        $atts
    );
    $args = array('numberposts'=>$a['posts']);
    $recent_posts = wp_get_recent_posts( $args, ARRAY_A );
    echo '<div class="recent-posts">';
    echo '<h1>'.$content.'</h1>';
    foreach($recent_posts as $post){
    ?>
    <div class="updated"><p><?php echo $post['post_title']; ?>. <a href="<?php echo get_permalink($post["ID"]); ?>"><span>Show Details</span>.</a></p></div>
    <?php
    }
    echo '</div>';
}
add_shortcode( 'latestposts', 'recent_posts_func' );

Shortcode content view:

Insert the shortcode through the WordPress admin panel editor, use the below code.

[latestposts posts="2"]Recent Posts[/latestposts]

Sunday, April 30, 2017

WordPress – Adding custom fields to the post

WordPress – Adding custom fields to the post

This extra custom fields data is known as meta-data. Meta data allow you to add some additional data to the post.

Edit current theme's functions.php below code 
/*
* Add the Custom Meta Box
*/

function add_custom_meta_box() {
    add_meta_box(
        'custom_meta_box', // $id
        'Custom Meta Box', // $title 
        'show_custom_meta_box', // $callback
        'post', // $page
        'normal', // $context
        'high' // $priority
    ); 
}
add_action('add_meta_boxes', 'add_custom_meta_box');
// Custom meta fields array
$prefix = 'custom_';
$custom_meta_fields = array(
    array(
        'label'=> 'Author Name',
        'desc'  => 'Enter post author name to be displayed',
        'id'    => $prefix.'author_name',
        'type'  => 'text',
    ),
 array(
  'label'=> 'Photo',
        'desc'  => 'Enter url author photo',
        'id'    => $prefix.'photo_author',
        'type'  => 'text'
    )
);

// The callback function
function show_custom_meta_box() {

    global $custom_meta_fields, $post;
    
    // Use nonce for verification
    echo '<input type="hidden" name="custom_meta_box_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />';
     
    // Begin the field table and loop
    echo '<table class="form-table">';
    
    foreach ($custom_meta_fields as $field) {
        // get value of this field if it exists for this post
        $meta = get_post_meta($post->ID, $field['id'], true);
        // begin a table row with
        echo '<tr>
                <th><label for="'.$field['id'].'">'.$field['label'].'</label></th>
                <td>';
                switch($field['type']) {
                    // text field
                    case 'text':
                        echo '<input type="text" name="'.$field['id'].'" id="'.$field['id'].'" value="'.$meta.'" size="30" />
                            <br /><span class="description">'.$field['desc'].'</span>';
                    break;
nbsp;               }
        echo '</td></tr>';
    }
    
    echo '</table>';
    
}

// Save the custom meta data
function save_custom_meta($post_id) {

    global $custom_meta_fields;
     
    // verify nonce
    if (!wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__))) 
        return $post_id;
        
    // check autosave
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
        return $post_id;
        
    // check permissions
    if ('page' == $_POST['post_type']) {
        if (!current_user_can('edit_page', $post_id))
            return $post_id;
        } elseif (!current_user_can('edit_post', $post_id)) {
            return $post_id;
    }
     
    // loop through fields and save the data
    foreach ($custom_meta_fields as $field) {
        $old = get_post_meta($post_id, $field['id'], true);
        $new = $_POST[$field['id']];
        if ($new && $new != $old) {
            update_post_meta($post_id, $field['id'], $new);
        } elseif ('' == $new && $old) {
            delete_post_meta($post_id, $field['id'], $old);
        }
    }
}
add_action('save_post', 'save_custom_meta');

Go to the post adding page and you can see the custom meta box and custom post fields under the post content editor.

Display the Custom Field Value

Edit current theme's single.php and add this code below


<?php 
    // Get the post meta data
    $meta = get_post_meta( get_the_ID() );
    
    // Get custom meta value
    $post_author_name = $meta['custom_author_name'][0];
    $post_photo_author = $meta['custom_photo_author'][0];
?>
<p>Author: <?php echo $post_author_name; ?> </p>
<p>Photo: <img src="<?php echo $post_photo_author; ?>"/> </p>

How to Create a Custom WordPress Widget

How to Create a Custom WordPress Widget

Add this code to your themes or functions.php
<?php
// Creating the widget 
class wpb_widget extends WP_Widget {

function __construct() {
parent::__construct(
// Base ID of your widget
'wpb_widget', 

// Widget name will appear in UI
__('Simple Widget', 'wpb_widget_domain'), 

// Widget description
array( 'description' => __( 'Simple widget', 'wpb_widget_domain' ), ) 
);
}

// Creating widget front-end
// This is where the action happens
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
// before and after widget arguments are defined by themes
echo $args['before_widget'];
if ( ! empty( $title ) )
echo $args['before_title'] . $title . $args['after_title'];

// This is where you run the code and display the output
echo __( 'Hello, World!', 'wpb_widget_domain' );
echo $args['after_widget'];
}
  
// Widget Backend 
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'New title', 'wpb_widget_domain' );
}
// Widget admin form
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> 
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
</p>
<?php 
}
 
// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
} // Class wpb_widget ends here

// Register and load the widget
function wpb_load_widget() {
 register_widget( 'wpb_widget' );
}
add_action( 'widgets_init', 'wpb_load_widget' );

PayPal Payment Gateway Integration in CodeIgniter

PayPal Payment Gateway Integration in CodeIgniter

We’ll create two tables called products and payments.

Products table


CREATE TABLE `products` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `price` float(10,2) NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1',
 PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

payments


CREATE TABLE `payments` (
 `payment_id` int(11) NOT NULL AUTO_INCREMENT,
 `user_id` int(11) NOT NULL,
 `product_id` int(11) NOT NULL,
 `txn_id` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `payment_gross` float(10,2) NOT NULL,
 `currency_code` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
 `payer_email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `payment_status` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 PRIMARY KEY (`payment_id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Controller

We’ll create two controllers Products and Paypal

Products:

This controller has two methods, index(), and buy(). index()


<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Products extends CI_Controller
{
    function  __construct() {
        parent::__construct();
        $this->load->library('paypal_lib');
        $this->load->model('product');
    }
    
    function index(){
        $data = array();
        //get products data from database
        $data['products'] = $this->product->getRows();
        //pass the products data to view
        $this->load->view('products/index', $data);
    }
    
    function buy($id){
        //Set variables for paypal form
        $returnURL = base_url().'paypal/success'; //payment success url
        $cancelURL = base_url().'paypal/cancel'; //payment cancel url
        $notifyURL = base_url().'paypal/ipn'; //ipn url
        //get particular product data
        $product = $this->product->getRows($id);
        $userID = 1; //current user id
        $logo = base_url().'assets/images/logo.png';
        
        $this->paypal_lib->add_field('return', $returnURL);
        $this->paypal_lib->add_field('cancel_return', $cancelURL);
        $this->paypal_lib->add_field('notify_url', $notifyURL);
        $this->paypal_lib->add_field('item_name', $product['name']);
        $this->paypal_lib->add_field('custom', $userID);
        $this->paypal_lib->add_field('item_number',  $product['id']);
        $this->paypal_lib->add_field('amount',  $product['price']);        
        $this->paypal_lib->image($logo);
        
        $this->paypal_lib->paypal_auto_form();
    }
}

Paypal: controller

This controller has three methods, success(), cancel(), and ipn(). success()

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Paypal extends CI_Controller 
{
     function  __construct(){
        parent::__construct();
        $this->load->library('paypal_lib');
        $this->load->model('product');
     }
     
     function success(){
        //get the transaction data
        $paypalInfo = $this->input->get();
          
        $data['item_number'] = $paypalInfo['item_number']; 
        $data['txn_id'] = $paypalInfo["tx"];
        $data['payment_amt'] = $paypalInfo["amt"];
        $data['currency_code'] = $paypalInfo["cc"];
        $data['status'] = $paypalInfo["st"];
        
        //pass the transaction data to view
        $this->load->view('paypal/success', $data);
     }
     
     function cancel(){
        $this->load->view('paypal/cancel');
     }
     
     function ipn(){
        //paypal return transaction details array
        $paypalInfo    = $this->input->post();

        $data['user_id'] = $paypalInfo['custom'];
        $data['product_id']    = $paypalInfo["item_number"];
        $data['txn_id']    = $paypalInfo["txn_id"];
        $data['payment_gross'] = $paypalInfo["mc_gross"];
        $data['currency_code'] = $paypalInfo["mc_currency"];
        $data['payer_email'] = $paypalInfo["payer_email"];
        $data['payment_status']    = $paypalInfo["payment_status"];

        $paypalURL = $this->paypal_lib->paypal_url;        
        $result    = $this->paypal_lib->curlPost($paypalURL,$paypalInfo);
        
        //check whether the payment is verified
        if(preg_match("/VERIFIED/i",$result)){
            //insert the transaction data into the database
            $this->product->insertTransaction($data);
        }
    }
}

Model (Product) Creation

Product model has two methods, getRows() and insertTransaction(). getRows()
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Product extends CI_Model{
    //get and return product rows
    public function getRows($id = ''){
        $this->db->select('id,name,image,price');
        $this->db->from('products');
        if($id){
            $this->db->where('id',$id);
            $query = $this->db->get();
            $result = $query->row_array();
        }else{
            $this->db->order_by('name','asc');
            $query = $this->db->get();
            $result = $query->result_array();
        }
        return !empty($result)?$result:false;
    }
    //insert transaction data
    public function insertTransaction($data = array()){
        $insert = $this->db->insert('payments',$data);
        return $insert?true:false;
    }
}
View Creation

Into the views directory, we’ll create two folders called products and paypal. products/ holds the view file of the Products controller and paypal/ holds the view files of Paypal controller.

products:
This directory has only one view file (index.php). This file holds the HTML for all the products listing.
<div class="row">
    <?php if(!empty($products)): foreach($products as $product): ?>
    <div class="thumbnail">
        <img src="<?php echo base_url().'assets/images/'.$product['image']; ?>" alt="">
        <div class="caption">
            <h4 class="pull-right">$<?php echo $product['price']; ?> USD</h4>
            <h4><a href="javascript:void(0);"><?php echo $product['name']; ?></a></h4>
        </div>
        <a href="<?php echo base_url().'products/buy/'.$product['id']; ?>"><img src="<?php echo base_url(); ?>assets/images/x-click-but01.gif" style="width: 70px;"></a>
    </div>
    <?php endforeach; endif; ?>
</div>

paypal:
This directory has two view file, success.php and cancel.php.
The success.php file holds the HTML for displaying the transaction success notification.
<div>
    <h2>Dear Member</h2>
    <span>Your payment was successful, thank you for purchase.</span><br/>
    <span>Item Number : 
        <strong><?php echo $item_number; ?></strong>
    </span><br/>
    <span>TXN ID : 
        <strong><?php echo $txn_id; ?></strong>
    </span><br/>
    <span>Amount Paid : 
        <strong>$<?php echo $payment_amt.' '.$currency_code; ?></strong>
    </span><br/>
    <span>Payment Status : 
        <strong><?php echo $status; ?></strong>
    </span><br/>
</div>
The cancel.php file holds the HTML for displaying the transaction cancel notification.
<div>
    <h3>Dear Member</h3>
    <p>We are sorry! Your last transaction was cancelled.</p>
</div>

paypal_lib.php file will be placed in the application/libraries/ directory and paypallib_config.php file will be placed in the application/config/ directory.

Paypal_lib.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); 
class paypal_lib {
 var $last_error;   // holds the last error encountered
 var $ipn_log;    // bool: log IPN results to text file?
 var $ipn_log_file;   // filename of the IPN log
 var $ipn_response;   // holds the IPN response from paypal 
 var $ipn_data = array(); // array contains the POST values for IPN
 var $fields = array();  // array holds the fields to submit to paypal
 var $submit_btn = '';  // Image/Form button
 var $button_path = '';  // The path of the buttons
 
 var $CI;
 
 function __construct()
 {
  $this->CI =& get_instance();
  $this->CI->load->helper('url');
  $this->CI->load->helper('form');
  $this->CI->load->config('paypallib_config');
  
  $sanbox = $this->CI->config->item('sandbox');
  $this->paypal_url = ($sanbox == TRUE)?'https://www.sandbox.paypal.com/cgi-bin/webscr':'https://www.paypal.com/cgi-bin/webscr';
                
  $this->last_error = '';
  $this->ipn_response = '';
  $this->ipn_log_file = $this->CI->config->item('paypal_lib_ipn_log_file');
  $this->ipn_log = $this->CI->config->item('paypal_lib_ipn_log'); 
  
  $this->button_path = $this->CI->config->item('paypal_lib_button_path');
  
  // populate $fields array with a few default values.  See the paypal
  // documentation for a list of fields and their data types. These defaul
  // values can be overwritten by the calling script.
  $businessEmail = $this->CI->config->item('business');
  $this->add_field('business',$businessEmail);
  $this->add_field('rm','2');     // Return method = POST
  $this->add_field('cmd','_xclick');
  
  $this->add_field('currency_code', $this->CI->config->item('paypal_lib_currency_code'));
      $this->add_field('quantity', '1');
  $this->button('Pay Now!');
 }
 function button($value)
 {
  // changes the default caption of the submit button
  $this->submit_btn = form_submit('pp_submit', $value);
 }
 function image($file)
 {
  $this->submit_btn = '<input type="image" name="add" src="' . site_url($this->button_path .'/'. $file) . '" border="0" />';
 }
 function add_field($field, $value) 
 {
  // adds a key=>value pair to the fields array, which is what will be 
  // sent to paypal as POST variables.  If the value is already in the 
  // array, it will be overwritten.
  $this->fields[$field] = $value;
 }
 function paypal_auto_form() 
 {
  // this function actually generates an entire HTML page consisting of
  // a form with hidden elements which is submitted to paypal via the 
  // BODY element's onLoad attribute.  We do this so that you can validate
  // any POST vars from you custom form before submitting to paypal.  So 
  // basically, you'll have your own form which is submitted to your script
  // to validate the data, which in turn calls this function to create
  // another hidden form and submit to paypal.
  $this->button('Click here if you\'re not automatically redirected...');
  echo '<html>' . "\n";
  echo '<head><title>Processing Payment...</title></head>' . "\n";
  echo '<body style="text-align:center;" onLoad="document.forms[\'paypal_auto_form\'].submit();">' . "\n";
  echo '<p style="text-align:center;">Please wait, your order is being processed and you will be redirected to the paypal website.</p>' . "\n";
  echo $this->paypal_form('paypal_auto_form');
  echo '</body></html>';
 }
 function paypal_form($form_name='paypal_form') 
 {
  $str = '';
  $str .= '<form method="post" action="'.$this->paypal_url.'" name="'.$form_name.'"/>' . "\n";
  foreach ($this->fields as $name => $value)
   $str .= form_hidden($name, $value) . "\n";
  $str .= '<p>'. $this->submit_btn . '</p>';
  $str .= form_close() . "\n";
  return $str;
 }
 
 function validate_ipn()
 {
  // parse the paypal URL
  $url_parsed = parse_url($this->paypal_url);    
  // generate the post string from the _POST vars aswell as load the
  // _POST vars into an arry so we can play with them from the calling
  // script.
  $post_string = '';  
  if ($this->CI->input->post())
  {
   foreach ($this->CI->input->post() as $field=>$value)
   { 
    $this->ipn_data[$field] = $value;
    $post_string .= $field.'='.urlencode(stripslashes($value)).'&'; 
   }
  }
  
  $post_string.="cmd=_notify-validate"; // append ipn command
  // open the connection to paypal
  $fp = fsockopen($url_parsed['host'],"80",$err_num,$err_str,30); 
  if(!$fp)
  {
   // could not open the connection.  If loggin is on, the error message
   // will be in the log.
   $this->last_error = "fsockopen error no. $errnum: $errstr";
   $this->log_ipn_results(false);   
   return false;
  } 
  else
  { 
   // Post the data back to paypal
   fputs($fp, "POST $url_parsed[path] HTTP/1.1\r\n"); 
   fputs($fp, "Host: $url_parsed[host]\r\n"); 
   fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); 
   fputs($fp, "Content-length: ".strlen($post_string)."\r\n"); 
   fputs($fp, "Connection: close\r\n\r\n"); 
   fputs($fp, $post_string . "\r\n\r\n"); 
   // loop through the response from the server and append to variable
   while(!feof($fp))
    $this->ipn_response .= fgets($fp, 1024); 
   fclose($fp); // close connection
  }
  if (preg_match("/VERIFIED/",$this->ipn_response))
  {
   // Valid IPN transaction.
   $this->log_ipn_results(true);
   return true;   
  } 
  else 
  {
   // Invalid IPN transaction.  Check the log for details.
   $this->last_error = 'IPN Validation Failed.';
   $this->log_ipn_results(false); 
   return false;
  }
 }
 function log_ipn_results($success) 
 {
  if (!$this->ipn_log) return;  // is logging turned off?
  // Timestamp
  $text = '['.date('m/d/Y g:i A').'] - '; 
  // Success or failure being logged?
  if ($success) $text .= "SUCCESS!\n";
  else $text .= 'FAIL: '.$this->last_error."\n";
  // Log the POST variables
  $text .= "IPN POST Vars from Paypal:\n";
  foreach ($this->ipn_data as $key=>$value)
   $text .= "$key=$value, ";
  // Log the response from the paypal server
  $text .= "\nIPN Response from Paypal Server:\n ".$this->ipn_response;
  // Write to log
  $fp=fopen($this->ipn_log_file,'a');
  fwrite($fp, $text . "\n\n"); 
  fclose($fp);  // close file
 }
 function dump() 
 {
  // Used for debugging, this function will output all the field/value pairs
  // that are currently defined in the instance of the class using the
  // add_field() function.
  ksort($this->fields);
  echo '<h2>ppal->dump() Output:</h2>' . "\n";
  echo '<code style="font: 12px Monaco, \'Courier New\', Verdana, Sans-serif;  background: #f9f9f9; border: 1px solid #D0D0D0; color: #002166; display: block; margin: 14px 0; padding: 12px 10px;">' . "\n";
  foreach ($this->fields as $key => $value) echo '<strong>'. $key .'</strong>: '. urldecode($value) .'<br/>';
  echo "</code>\n";
 }
 
 
 function curlPost($paypalurl,$paypalreturnarr)
 {
  
  $req = 'cmd=_notify-validate';
  foreach($paypalreturnarr as $key => $value) 
  {
   $value = urlencode(stripslashes($value));
   $req .= "&$key=$value";
  }
   
  $ipnsiteurl=$paypalurl;
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $ipnsiteurl);
  curl_setopt($ch, CURLOPT_HEADER, false);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
  $result = curl_exec($ch);
  curl_close($ch);
 
  return $result;
 }
}
?>
paypallib_config.php
<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
// ------------------------------------------------------------------------
// Paypal IPN Class
// ------------------------------------------------------------------------
// Use PayPal on Sandbox or Live
$config['sandbox'] = TRUE; // FALSE for live environment
// PayPal Business Email ID
$config['business'] = 'InsertPayPalBusinessEmail';
// If (and where) to log ipn to file
$config['paypal_lib_ipn_log_file'] = BASEPATH . 'logs/paypal_ipn.log';
$config['paypal_lib_ipn_log'] = TRUE;
// Where are the buttons located at 
$config['paypal_lib_button_path'] = 'buttons';
// What is the default currency?
$config['paypal_lib_currency_code'] = 'USD';
?>


Test PayPal Transaction

Open the Products controller (http://localhost/codeigniter/products)

Friday, April 28, 2017

Back to Top Button using jQuery and CSS

Back to Top Button using jQuery and CSS
<!DOCTYPE html>
<html>
<head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Back to Top Button using jQuery and CSS</title>

</head>
<body>
<style type="text/css">
/* page text content css */
h1{font-size:45px;text-align:center; text-decoration:underline;}
h3{font-size:40px;color:#FA0530}
p{font-size:40px;}

/* BackToTop button css */
#scroll {
position:fixed;
right:10px;
bottom:10px;
cursor:pointer;
width:50px;
height:50px;
background-color:#3498db;
text-indent:-9999px;
display:none;
-webkit-border-radius:60px;
-moz-border-radius:60px;
border-radius:60px
}
#scroll span {
position:absolute;
top:50%;
left:50%;
margin-left:-8px;
margin-top:-12px;
height:0;
width:0;
border:8px solid transparent;
border-bottom-color:#ffffff
}
#scroll:hover {
background-color:#e74c3c;
opacity:1;filter:"alpha(opacity=100)";
-ms-filter:"alpha(opacity=100)";}
</style>
<div class="row">
        <div class="col-lg-12">
            <div >
                <!-- BackToTop Button -->
<a href="#" id="scroll" title="Scroll to Top" style="display: none;">Top<span></span></a>

<h1>jQuery Back to Top Button</h1>
<h3>Scroll down the page, the BackToTop button would be appear at the right side corner. Once you click on this button, the page would be scrolling up to the top.</h3>
<!-- Demo Text -->
<p>Cras dui massa, dapibus eget nulla gravida, tempus vestibulum neque. Vestibulum ut euismod tellus, id facilisis velit. Sed vitae nunc at ex lobortis sagittis sit amet a ex. Mauris mollis tellus et tortor euismod scelerisque. In non facilisis lorem, non egestas nisl. Suspendisse potenti. Nunc in enim sed ipsum volutpat ultricies. Curabitur porta eros eget lacus maximus iaculis. Nulla ac sapien fermentum, lobortis risus eget, pellentesque eros. Aliquam erat volutpat. Vestibulum nulla erat, pulvinar nec condimentum sed, faucibus at velit.</p>

<p>Mauris eleifend facilisis pharetra. Nullam vestibulum malesuada dictum. Nulla blandit sit amet massa nec tempor. Vestibulum sit amet urna ut eros placerat vehicula in id felis. Curabitur quis imperdiet urna. Sed dictum suscipit velit, eget bibendum lectus fermentum sed. Nunc eget quam enim. Vivamus eget nisi non erat rhoncus accumsan vel vitae neque. Nam cursus felis sed elementum consectetur. Vivamus mattis, felis vel eleifend luctus, nisl ante dictum massa, sit amet semper lorem odio consectetur risus.</p>

<p>Aliquam erat volutpat. Cras consequat lacus nec enim imperdiet convallis. Quisque tincidunt et mi quis euismod. Aenean faucibus tincidunt libero, vitae vulputate ante commodo vel. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque laoreet est eu lectus aliquam iaculis a nec enim. Etiam aliquet mi ac lectus laoreet luctus. Nulla quis ante nisl. Ut sit amet nibh non odio suscipit posuere. Donec ac tellus quis ante efficitur tincidunt et sit amet neque. Integer aliquet neque eget tellus luctus gravida. Sed maximus lobortis cursus. Praesent et felis ante. Mauris massa justo, tristique at lacus ut, consectetur ultrices purus. Vivamus et ex nec sem tempor tincidunt. Suspendisse elementum sem erat, sed euismod felis sodales et.</p>

<p>Vivamus ut massa quis risus bibendum condimentum. Nunc commodo libero eu tincidunt facilisis. Morbi ut tellus eu lacus interdum egestas. Pellentesque faucibus porttitor lacus, vitae efficitur nulla suscipit sed. Aenean dapibus magna quis dui blandit, nec aliquam tellus consectetur. Curabitur porttitor lacus nec quam finibus, quis iaculis ante sodales. Ut egestas varius arcu, id condimentum lorem congue a. Duis in tellus eget leo lobortis placerat vel sed tortor. Curabitur eu risus mi.</p>

<p>Proin non odio laoreet, sollicitudin nulla quis, laoreet velit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Morbi vel tellus a libero venenatis pharetra. Praesent ac bibendum tortor. In varius metus quis vehicula auctor. Nullam viverra id odio vel convallis. Sed tortor est, aliquam quis suscipit ac, tempus nec purus. Curabitur euismod congue dui, id rutrum quam dictum sit amet. In a metus maximus, condimentum lorem volutpat, feugiat lectus.</p>
            </div>
        </div>
    </div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){ 
 $(window).scroll(function(){ 
  if ($(this).scrollTop() > 100) { 
   $('#scroll').fadeIn(); 
  } else { 
   $('#scroll').fadeOut(); 
  } 
 }); 
 $('#scroll').click(function(){ 
  $("html, body").animate({ scrollTop: 0 }, 600); 
  return false; 
 }); 
});
</script>
</body>
</html>

Google Map with marker and info window using JavaScript

Google Map with marker and info window using JavaScript
<!DOCTYPE html>
<html>
<head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Google Map with marker and info window using JavaScript</title>

</head>
<style>
      html, body, #map-canvas {
        height: 600px;
        margin: 0px;
        padding: 0px;
  margin-top:20px;
      }
    </style>
<body>
 <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
    <script type="text/javascript">
 function initialize() {
  
  /****** Change latitude and longitude here ******/
    var myLatlng = new google.maps.LatLng(14.831634, 120.281559);
  
  /****** Map Options *******/
    var mapOptions = {
       zoom: 14,
       center: myLatlng
     };

    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  
  /****** Info Window Contents *******/
    var contentString = '<div id="content">'+
     '<div id="siteNotice">'+
     '</div>'+
     '<h1 id="firstHeading" class="firstHeading">Olongapo City</h1>'+
     '<div id="bodyContent">'+ '<div style="float:left; width:20%;"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/50/OlongapoCityjf9265_13.JPG/250px-OlongapoCityjf9265_13.JPG" width="120" height="80"/></div>' +
     '<div style="float:right; width:80%;margin-top: -6px;"><p>Olongapo, officially the City of Olongapo (Ilocano: Ciudad ti Olongapo; Sambali: Syodad nin Olongapo; Filipino: Lungsod ng Olongapo) and often referred to as Olongapo City, is a highly urbanized city in the Philippines. Located in the province of Zambales but governed independently from the province, it has a population of 233,040 people according to the 2015 census.[4] Along with the town/municipality of Subic (and later, Castillejos as well as the municipalities of Dinalupihan, Hermosa and Morong in Bataan), it comprises Metro Olongapo, one of the twelve metropolitan areas in the Philippines.'+
     'https://en.wikipedia.org/wiki/Olongapo</a> '+
     '.</p></div>'+
     '</div>'+
     '</div>';

  var infowindow = new google.maps.InfoWindow({
      content: contentString
   });
  
  /****** Map Marker Options *******/
  var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: 'Olongapo City (Philippines)'
   });
  
  /****** Info Window With Click *******/
  google.maps.event.addListener(marker, 'click', function() {
   infowindow.open(map,marker);
  });
  
    /****** Info Window Without Click *******/
     infowindow.open(map,marker);
 }

 google.maps.event.addDomListener(window, 'load', initialize);
 </script>
<div class="row">
            <div class="col-lg-12">
    <div >
                    <div id="map-canvas"></div>
                </div>
   </div>
        </div>
</body>
</html>

Social popup on page scroll using jQuery and CSS

Social popup on page scroll using jQuery and CSS
<!DOCTYPE html>
<html>
<head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Select / Deselect all checkboxes using jQuery</title>

</head>
       <style type="text/css">
/* page text content css */
h1{font-size:45px;text-align:center; text-decoration:underline;}
h3{font-size:40px;color:#FA0530}
p{font-size:40px;}

/* popup css*/
#spopup{
 background:#f3f3f3;
 border-radius:9px;
 -moz-border-radius:9px;
 -webkit-border-radius:9px;
 -moz-box-shadow:inset 0 0 3px #333;
 -webkit-box-shadow:inset 0 0 3px #333;
 box-shadow:inner 0 0 3px #333;
 padding:12px 14px 12px 14px;
 width:300px;
 position:fixed;
 bottom:13px;
 right:2px;
 display:none;
 z-index:90;
}
</style>
<body>
<div class="container">

    <div class="row">
        <div class="col-lg-12">
            <div>
            
            <h3>Scroll down the page, the social popup would be appear at the right side corner. </h3>
            
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ornare facilisis risus venenatis mattis. Fusce convallis vehicula dui sed rhoncus. Donec lorem velit, bibendum ac libero in, feugiat dapibus eros. Donec faucibus enim ac ligula tempus, vitae dignissim felis fermentum. Curabitur lectus orci, tincidunt sit amet ornare ac, scelerisque quis ligula. Nunc iaculis ligula non gravida consequat. Curabitur efficitur placerat odio. Aliquam ut aliquet nunc, in mollis purus. Morbi id orci ut odio suscipit placerat eu suscipit justo. Sed condimentum ligula eu odio bibendum, ac convallis erat finibus.</p>
            
            <p>Fusce pellentesque, dui eget auctor luctus, nisl orci aliquam tortor, in blandit mi nulla at urna. Maecenas felis leo, ullamcorper sed vehicula quis, tincidunt non nisi. Praesent iaculis lacus nec commodo facilisis. Sed sagittis ipsum vel cursus venenatis. Mauris dapibus commodo blandit. In tristique diam sem, quis vulputate quam congue sed. Sed cursus nulla a lectus hendrerit ultricies. In vulputate feugiat mauris. Nullam suscipit sed nisl nec facilisis. Nulla luctus justo id semper accumsan. Ut ultricies nisl et cursus convallis. Sed vel arcu ac eros tristique posuere eget ac nibh.</p>
            
            <p>Vivamus placerat leo id turpis varius, sit amet vehicula sapien pretium. Etiam quam est, viverra at dui nec, tincidunt volutpat elit. Vestibulum varius velit ut imperdiet tincidunt. Sed venenatis sem sit amet rhoncus hendrerit. Mauris eu accumsan ante. Mauris in accumsan purus. Sed blandit vehicula pharetra. Donec a vehicula elit, sed auctor lectus. Morbi lobortis tempus nulla, sed sollicitudin libero porttitor eu. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed convallis arcu vitae sem pulvinar mattis. Duis ac enim dui. Sed et eros pellentesque, bibendum est id, tincidunt mi.</p>
            
            <p>Sed ut varius lorem. Duis ac ex sagittis, facilisis eros eu, venenatis quam. Pellentesque sed nunc dui. Praesent scelerisque urna at enim condimentum faucibus. Proin pharetra pellentesque enim, in suscipit neque. Sed sit amet felis nunc. Curabitur eu urna elementum, congue lectus vel, feugiat enim. Nunc commodo euismod metus vitae lobortis. Nullam sit amet ullamcorper justo.</p>
            
            </div>

            <div id="spopup" style="display: none;">
                <a style="position:absolute;top:14px;right:10px;color:#555;font-size:10px;font-weight:bold;" href="javascript:void(0);" onClick="return closeSPopup();"><b style="font-size:18px;">X</b></a>
                <div class="sidebox">
    <a class="side-twitter" href="http://twitter.com/kenshin0023"><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi7Gr4Wc9bgsUdsyzeXWbNV1r8jMcL0iW5SkjwexRWzWyfsIGZl2FpsVKWWWgWmmMG2KuJikWQLl1OYTubGwc-nhfC4q0PCYI5FRs7_1FuqRWSyXkn0W7G0bB_6aQEXijRZzeDfG0TrEWdE/s400/twitter.gif"/></a><p></p>
    <a class="side-rss" href="/feeds/posts/default"><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgfGHlsDThchOtiET0kwI_1K7zZoq6JH78WftafRUUHRCsZow5zJTFfXBYjVukhZn_5Ljhyl3JCtqEqtmZcYGt-mtZvUV7PmEuLqW95ACwj-WujO4DwY_v2RM9kf_AgufifpuInlS7nxSiM/s400/rss.gif"/></a>
    </div>
              </div>
            </div>
    </div>
    </div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" async >
$(window).scroll(function(){
 if($(document).scrollTop()>=$(document).height()/5)
  $("#spopup").show("slow");else $("#spopup").hide("slow");
});
function closeSPopup(){
 $('#spopup').hide('slow');
}
</script>
</body>
</html>

Select / Deselect all checkboxes using jQuery

Select / Deselect all checkboxes using jQuery
<!DOCTYPE html>
<html>
<head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Select / Deselect all checkboxes using jQuery</title>

</head>
<body>
<ul class="main">
    <li><input type="checkbox" id="select_all" /> Select all</li>
    <ul>
        <li><input type="checkbox" class="checkbox" value="1"/>Item 1</li>
        <li><input type="checkbox" class="checkbox" value="2"/>Item 2</li>
        <li><input type="checkbox" class="checkbox" value="3"/>Item 3</li>
        <li><input type="checkbox" class="checkbox" value="4"/>Item 4</li>
        <li><input type="checkbox" class="checkbox" value="5"/>Item 5</li>
    </ul>
</ul>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('#select_all').on('click',function(){
        if(this.checked){
            $('.checkbox').each(function(){
                this.checked = true;
            });
        }else{
             $('.checkbox').each(function(){
                this.checked = false;
            });
        }
    });
    
    $('.checkbox').on('click',function(){
        if($('.checkbox:checked').length == $('.checkbox').length){
            $('#select_all').prop('checked',true);
        }else{
            $('#select_all').prop('checked',false);
        }
    });
});
</script>
</body>
</html>

Saturday, April 22, 2017

Smooth scroll to div using jQuery

Smooth scroll to div using jQuery
<!DOCTYPE html>
<html>
<head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Smooth scroll to div using jQuery</title>
            <style>
  h1{font-size: 40px;}
        p{ font-size: 35px;}
  #top a {padding: 10px;}
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-lg-12">
            <div id="top">
                <a href="#section1">Go Section 1</a>|
                <a href="#section2">Go Section 2</a>|
                <a href="#section3">Go Section 3</a>|
                <a href="#section4">Go Section 4</a>|
                <a href="#section5">Go Section 5</a>
            </div>
            <div id="section1">
                <h1>Section 1</h1>
                <p>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</p>
           </div>
            <div id="section2">
                <h1>Section 2</h1>
                <a href="#top">BackToTop</a>
                <p>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</p>
            </div>
            <div id="section3">
                <h1>Section 3</h1>
                <a href="#top">BackToTop</a>
    <p>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</p>
   </div>
            <div id="section4">
                <h1>Section 4</h1>
                <a href="#top">BackToTop</a>
            <p>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</p>
   </div>
            <div id="section5">
                <h1>Section 5</h1>
                <a href="#top">BackToTop</a>
            <p>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</p>
   </div>
      </div>
    </div>
</div>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
     <script>
$(function() {
 $('a[href*=#]:not([href=#])').click(function() {
  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.substr(1) +']');
  if (target.length) {
   $('html,body').animate({
     scrollTop: target.offset().top
   }, 1000);
   return false;
  }
 });
});
</script>
</body>
</html>

Redirect page delay 5 second using JavaScript

Redirect page delay 5 second using JavaScript
<!DOCTYPE html>
<html>
<head>
            <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Redirect page delay 5 second using JavaScript</title>
         <script>
    function delayRedirect(){
        document.getElementById('delayMsg').innerHTML = 'Please wait you\'ll be redirected after <span id="countDown">5</span> seconds....';
        var count = 5;
        setInterval(function(){
            count--;
            document.getElementById('countDown').innerHTML = count;
            if (count == 0) {
                window.location = 'http://tutorial101.blogspot.com/'; 
            }
        },1000);
    }
    </script>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-lg-12">
         <div class="div-center">
            <div id="delayMsg" style="margin-bottom:10px;"></div>
            <input type="button" onclick="delayRedirect()" value="Click to Redirect"/>
            </div>
        </div>
   </div>
</div>
     </body>
</html>

Preview Image before Upload using jQuery

Preview Image before Upload using jQuery
<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Preview Image before Upload using jQuery</title>
        <style type="text/css">
form{float: left;width: 100%;}
.div-center img{float: left;margin-top: 20px;}
embed{float: left;margin-top: 20px;}
</style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-lg-12">
            <div class="div-center">
                <form method="post" action="" enctype="multipart/form-data" id="uploadForm">
                    <input type="file" name="file" id="file" />
                </form>
            </div>
     </div>
   </div>
</div>
 
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
     <script>
function filePreview(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#uploadForm + embed').remove();
            $('#uploadForm').after('<embed src="'+e.target.result+'" width="450" height="300">');
        }
        reader.readAsDataURL(input.files[0]);
    }
}

$("#file").change(function () {
    filePreview(this);
});
</script>
</body>
</html>

Friday, April 21, 2017

Create Loader Animation with CSS

Create Loader Animation with CSS
<!DOCTYPE HTML>
<html>
<head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title> Loader Animation with CSS</title>
        <style type="text/css">
h2{font-size: 33px;margin-bottom: 10px;}
.loader {
    border-top: 16px solid #4285F4;
    border-right: 16px solid #EA4335;
    border-bottom: 16px solid #FBBC05;
    border-left: 16px solid #34A853;
    border-radius: 50%;
    width: 80px;
    height: 80px;
    -webkit-animation: rotate 2s linear infinite;
    animation: rotate 2s linear infinite;
}
@keyframes rotate {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}
@-webkit-keyframes rotate {
    0% { -webkit-transform: rotate(0deg); }
    100% { -webkit-transform: rotate(360deg); }
}


.loader-container {
    border: 1px solid rgba(255, 255, 255, 0.2);
    width: 240px;
    height: 240px;
    float: left;
    position: relative;
    overflow: hidden;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}
.loader2, .loader2:before, .loader2:after {
    background: #000000;
    -webkit-animation: animate 1s infinite ease-in-out;
    animation: animate 1s infinite ease-in-out;
    width: 1em;
    height: 4em;
}
.loader2 {
    color: #000000;
    text-indent: -9999em;
    margin: 88px auto;
    position: relative;
    font-size: 11px;
    -webkit-transform: translateZ(0);
    -ms-transform: translateZ(0);
    transform: translateZ(0);
    -webkit-animation-delay: -0.16s;
    animation-delay: -0.16s;
}
.loader2:before, .loader2:after {
    position: absolute;
    top: 0;
    content: '';
}
.loader2:before {
    left: -1.5em;
    -webkit-animation-delay: -0.32s;
    animation-delay: -0.32s;
}
.loader2:after {
    left: 1.5em;
}
@-webkit-keyframes animate {
    0%, 80%, 100% {
        box-shadow: 0 0;
        height: 4em;
    }
    40% {
        box-shadow: 0 -2em;
        height: 5em;
    }
}
@keyframes animate {
    0%, 80%, 100% {
          box-shadow: 0 0;
          height: 4em;
    }
    40% {
        box-shadow: 0 -2em;
        height: 5em;
    }
}
</style>
</head>

<body>
<div class="container">
    <div class="row">
        <div class="col-lg-12">
            <div class="">
             <h2>Loader Style 1</h2>
                <div class="loader"></div>
                
                <h2 style="margin-bottom:0px;">Loader Style 2</h2>
                <div class="loader-container">
                    <div class="loader2"></div>
                </div>
            </div>
  </div>
    </div>
</div>
</body>
</html>

Social Media Floating Sidebar with CSS

Social Media Floating Sidebar with CSS
<!DOCTYPE HTML>
<html>
<head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Social Media Floating Sidebar with CSS</title>
<style>  
body { background-color: #02c54c ;}
/* Sticky Social Icons */
.sticky-container{ padding:0px; margin:0px; position:fixed; right:-130px;top:230px; width:210px; z-index: 1100;}
.sticky li{list-style-type:none;background-color:#fff;color:#efefef;height:43px;padding:0px;margin:0px 0px 1px 0px; -webkit-transition:all 0.25s ease-in-out;-moz-transition:all 0.25s ease-in-out;-o-transition:all 0.25s ease-in-out; transition:all 0.25s ease-in-out; cursor:pointer;}
.sticky li:hover{margin-left:-115px;}
.sticky li img{float:left;margin:5px 4px;margin-right:5px;}
.sticky li p{padding-top:5px;margin:0px;line-height:16px; font-size:11px;}
.sticky li p a{ text-decoration:none; color:#2C3539;}
.sticky li p a:hover{text-decoration:underline;}
/* Sticky Social Icons */
</style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-lg-12">
            <div class="sticky-container">
                <ul class="sticky">
                    <li>
                        <img src="img/facebook-circle.png" width="32" height="32">
                        <p><a href="#" target="_blank">Like Us on<br>Facebook</a></p>
                    </li>
                    <li>
                        <img height="32" src="img/twitter-circle.png" width="32" height="32">
                        <p><a href="#" target="_blank">Follow Us on<br>Twitter</a></p>
                    </li>
                    <li>
                        <img src="img/gplus-circle.png" width="32" height="32">
                        <p><a href="#" target="_blank">Follow Us on<br>Google+</a></p>
                    </li>
                    <li>
                        <img src="img/linkedin-circle.png" width="32" height="32">
                        <p><a href="#" target="_blank">Follow Us on<br>LinkedIn</a></p>
                    </li>
                    <li>
                        <img src="img/youtube-circle.png" width="32" height="32">
                        <p><a href="#" target="_blank">Subscribe on<br>YouYube</a></p>
                    </li>
                    <li>
                        <img src="img/pin-circle.png" width="32" height="32">
                        <p><a href="#" target="_blank">Follow Us on<br>Pinterest</a></p>
                    </li>
                </ul>
            </div>
  </div>
    </div>
</div>
     </body>
</html>

Thursday, April 13, 2017

Bootstrap Modal Popup Form Submit with Ajax & PHP

Bootstrap Modal Popup Form Submit with Ajax and PHP


//index.php
<!-- Latest minified bootstrap css -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<!-- Latest minified bootstrap js -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Button to trigger modal -->
<button class="btn btn-success btn-lg" data-toggle="modal" data-target="#modalForm">
    Open Contact Form
</button>

<!-- Modal -->
<div class="modal fade" id="modalForm" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <!-- Modal Header -->
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">
                    <span aria-hidden="true">×</span>
                    <span class="sr-only">Close</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">Contact Form</h4>
            </div>
            
            <!-- Modal Body -->
            <div class="modal-body">
                <p class="statusMsg"></p>
                <form role="form">
                    <div class="form-group">
                        <label for="inputName">Name</label>
                        <input type="text" class="form-control" id="inputName" placeholder="Enter your name"/>
                    </div>
                    <div class="form-group">
                        <label for="inputEmail">Email</label>
                        <input type="email" class="form-control" id="inputEmail" placeholder="Enter your email"/>
                    </div>
                    <div class="form-group">
                        <label for="inputMessage">Message</label>
                        <textarea class="form-control" id="inputMessage" placeholder="Enter your message"></textarea>
                    </div>
                </form>
            </div>
            
            <!-- Modal Footer -->
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary submitBtn" onclick="submitContactForm()">SUBMIT</button>
            </div>
        </div>
    </div>
</div>
<script>
function submitContactForm(){
    var reg = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
    var name = $('#inputName').val();
    var email = $('#inputEmail').val();
    var message = $('#inputMessage').val();
    if(name.trim() == '' ){
        alert('Please enter your name.');
        $('#inputName').focus();
        return false;
    }else if(email.trim() == '' ){
        alert('Please enter your email.');
        $('#inputEmail').focus();
        return false;
    }else if(email.trim() != '' && !reg.test(email)){
        alert('Please enter valid email.');
        $('#inputEmail').focus();
        return false;
    }else if(message.trim() == '' ){
        alert('Please enter your message.');
        $('#inputMessage').focus();
        return false;
    }else{
        $.ajax({
            type:'POST',
            url:'submit_form.php',
            data:'contactFrmSubmit=1&name='+name+'&email='+email+'&message='+message,
            beforeSend: function () {
                $('.submitBtn').attr("disabled","disabled");
                $('.modal-body').css('opacity', '.5');
            },
            success:function(msg){
                if(msg == 'ok'){
                    $('#inputName').val('');
                    $('#inputEmail').val('');
                    $('#inputMessage').val('');
                    $('.statusMsg').html('<span style="color:green;">Thanks for contacting us, we\'ll get back to you soon.</p>');
                }else{
                    $('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
                }
                $('.submitBtn').removeAttr("disabled");
                $('.modal-body').css('opacity', '');
            }
        });
    }
}
</script>
<?php
//submit_form.php
if(isset($_POST['contactFrmSubmit']) && !empty($_POST['name']) && !empty($_POST['email']) && (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) && !empty($_POST['message'])){
    
    // Submitted form data
    $name   = $_POST['name'];
    $email  = $_POST['email'];
    $message= $_POST['message'];
    
    /*
     * Send email to admin
     */
    $to     = 'admin@example.com';
    $subject= 'Contact Request Submitted';
    
    $htmlContent = '
    <h4>Contact request has submitted at tutorial101, details are given below.</h4>
    <table cellspacing="0" style="width: 300px; height: 200px;">
        <tr>
            <th>Name:</th><td>'.$name.'</td>
        </tr>
        <tr style="background-color: #e0e0e0;">
            <th>Email:</th><td>'.$email.'</td>
        </tr>
        <tr>
            <th>Message:</th><td>'.$message.'</td>
        </tr>
    </table>';
    
    // Set content-type header for sending HTML email
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    
    // Additional headers
    $headers .= 'From: tutorial101<sender@example.com>' . "\r\n";
    
    // Send email
    if(mail($to,$subject,$htmlContent,$headers)){
        $status = 'ok';
    }else{
        $status = 'err';
    }
    
    // Output status
    echo $status;die;
}

Friday, January 13, 2017

Wordpress Remove Menu admin page

Wordpress Remove Menu admin page

locate wp-admin\includes\plugin.php then add this code
function remove_menus(){
  remove_menu_page( 'index.php' );                  //Dashboard
  remove_menu_page( 'jetpack' );                    //Jetpack* 
  remove_menu_page( 'edit.php' );                   //Posts
  remove_menu_page( 'upload.php' );                 //Media
  remove_menu_page( 'edit.php?post_type=page' );    //Pages
  remove_menu_page( 'edit-comments.php' );          //Comments
  remove_menu_page( 'themes.php' );                 //Appearance
  remove_menu_page( 'plugins.php' );                //Plugins
  remove_menu_page( 'users.php' );                  //Users
  remove_menu_page( 'tools.php' );                  //Tools
  remove_menu_page( 'options-general.php' );        //Settings
}
add_action( 'admin_menu', 'remove_menus' );

Saturday, January 7, 2017

CSS target desktop, tablet and mobile?

@media (min-width:320px)  { /* smartphones, iPhone, portrait 480x320 phones */ }
@media (min-width:481px)  { /* portrait e-readers (Nook/Kindle), smaller tablets @ 600 or @ 640 wide. */ }
@media (min-width:641px)  { /* portrait tablets, portrait iPad, landscape e-readers, landscape 800x480 or 854x480 phones */ }
@media (min-width:961px)  { /* tablet, landscape iPad, lo-res laptops ands desktops */ }
@media (min-width:1025px) { /* big landscape tablets, laptops, and desktops */ }
@media (min-width:1281px) { /* hi-res laptops and desktops */ }

Related Post