Monday, May 1, 2017

0 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

0 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>

0 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' );

0 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

0 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>

0 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>

0 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="http://1.bp.blogspot.com/_j82W7u9kZbs/S0Yu1vK-eVI/AAAAAAAAA0E/YoyuRPbbgQM/s400/twitter.gif"/></a><p></p>
    <a class="side-rss" href="/feeds/posts/default"><img src="http://4.bp.blogspot.com/_j82W7u9kZbs/S0YvnW7O-aI/AAAAAAAAA0M/lEQCPW_jPp4/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>

0 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

0 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>

0 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>

0 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

0 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>

0 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

0 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

0 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

0 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 */ }

Thursday, December 1, 2016

0 PHPMailer Upload mail Attachment

PHPMailer Upload mail Attachment
<?php
$msg = '';
if (array_key_exists('userfile', $_FILES)) {
 if (preg_match('/\.(doc|docx|xls|xlsx|pdf|jpeg|png)$/i', $_FILES["userfile"]["name"])) //upload
 {
  $uploadfile = $_FILES['userfile']['name'];
  if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
        // This should be somewhere in your include_path
        require 'PHPMailerAutoload.php';
        $mail = new PHPMailer;
        $mail->setFrom('from@example.com', 'First Last');
        $mail->addAddress('tomail@example.com', 'John Doe');
        $mail->Subject = 'PHPMailer file sender';
        $mail->msgHTML("My message body");
        $mail->addAttachment($uploadfile);
        if (!$mail->send()) {
            $msg = "Mailer Error: " . $mail->ErrorInfo;
        } else {
            $msg = "Message sent!";
        } 
  }else {
   $msg = '<font color=red> ERROR_FAILED_TO_UPLOAD_FILE </font>';
  }
 }else{
  $msg = '<font color=red> ERROR_FAILED_TO_UPLOAD_FILE </font>';
 } 
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>PHPMailer Upload mail Attachment</title>
</head>
<body>
<?php if (empty($msg)) { ?>
    <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="MAX_FILE_SIZE" value="100000"> Send this file: <input name="userfile" type="file">
        <input type="submit" value="Send File">
    </form>
<?php } else {
    echo $msg;
} ?>
</body>
</html>

Tuesday, November 29, 2016

0 Add pagination in wordpress admin in customized plugin

Add pagination in wordpress admin in customized plugin

<?php
$pagenum = isset( $_GET['pagenum'] ) ? absint( $_GET['pagenum'] ) : 1;
$limit = 2; // number of rows in page
$offset = ( $pagenum - 1 ) * $limit;
$total = $wpdb->get_var( "SELECT COUNT('id') FROM {$wpdb->prefix}user" );
$num_of_pages = ceil( $total / $limit );

$entries = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}user LIMIT $offset, $limit" );
$page_links = paginate_links( array(
    'base' => add_query_arg( 'pagenum', '%#%' ),
    'format' => '',
    'prev_text' => __( '«', 'text-domain' ),
    'next_text' => __( '»', 'text-domain' ),
    'total' => $num_of_pages,
    'current' => $pagenum
) );

if ( $page_links ) {
    echo '<div class="tablenav"><div class="tablenav-pages" style="margin: 1em 0">' . $page_links . '</div></div>';
}
?>
<form method="get" action="" id="posts-filter">
 <table class="wp-list-table widefat fixed pages">
 <tbody id="the-list">
  <thead>
   <tr>
    <th class="manage-column column-cb check-column" id="cb" scope="col"></th>
    <th class="manage-column column-name" scope="col">Student</th>
    <th class="manage-column column-name" scope="col">Course Order</th>
    <th class="manage-column column-name" scope="col">Date Schedule</th>
    <th class="manage-column column-name" scope="col" width="60">Invoice #</th>
    <th class="manage-column column-name" scope="col" width="90">Order Status</th>
    <th class="manage-column column-name" scope="col" width="90">Paid By</th>
    <th class="manage-column column-name" scope="col" width="90">Action</th>
   </tr>
  </thead>
  <tfoot>
   <tr>
    <th class="manage-column column-cb check-column" scope="col"></th>
    <th class="manage-column column-name" scope="col">Student</th>
    <th class="manage-column column-name" scope="col">Course Order</th>
    <th class="manage-column column-name" scope="col">Date Schedule</th>
    <th class="manage-column column-name" scope="col" width="60">Invoice #</th>
    <th class="manage-column column-name" scope="col" width="90">Order Status</th>
    <th class="manage-column column-name" scope="col">Paid By</th>
    <th class="manage-column column-name" scope="col">Action</th>
   </tr>
  </tfoot>
  <?php
   $pagenum = isset( $_GET['pagenum'] ) ? absint( $_GET['pagenum'] ) : 1;
   $limit = 2; // number of rows in page
   $offset = ( $pagenum - 1 ) * $limit;
   $total = $wpdb->get_var( "SELECT COUNT('id') FROM {$wpdb->prefix}userorder" );
   $num_of_pages = ceil( $total / $limit );
   $sql_usersorder = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}userorder ORDER BY dateorder DESC LIMIT $offset, $limit");
   $totalrec =  $wpdb->num_rows;
   $isodd=array('','alternate');
   $n=0;
   foreach ($sql_usersorder as $rows_usersorder) 
   {
    $n++;
    $id = $rows_usersorder->id;   
    $user_id = $rows_usersorder->user_id;
    $allcouse_id = $rows_usersorder->allcouse_id;
    $takencourseid = $rows_usersorder->takencourseid;
    $course_invoice = $rows_usersorder->course_invoice;
    $orderstatus = $rows_usersorder->orderstatus;
    $paidby = $rows_usersorder->paidby;
  ?>
  <tr class="type-page <?php=$isodd[$n%2]?>">
   <th class="check-column" scope="row"><center><?php echo $n; ?></center></th> 
   <td class="column-title"><strong><a title="Edit" href="#" class="row-title"><?php echo $fname; ?> <?php echo $lname; ?></a></strong>
    <div class="row-actions">
    <span class="edit"><a title="Edit this item" href="#">Edit</a> | </span>
    <span class="trash"><a href="javascript:delusers('<?php echo $id; ?>','<?php echo $fname; ?>')" title="Move this item to the Trash" class="submitdelete">Trash</a> | </span></div>
   </td>
   <td><?php echo $coursetitle; ?></td> 
   <td><?php echo $orderstatus; ?></td>  
   <td><?php echo $paidby; ?></td>
   <td><a href="#">View</a> | <a href="#">Delete</a></td>
  </tr>
  <?php } ?>
  </tbody>
 </table>
 <div class="tablenav bottom">
  <div class="alignleft actions bulkactions">
   <?php
   $page_links = paginate_links( array(
    'base' => add_query_arg( 'pagenum', '%#%' ),
    'format' => '',
    'prev_text' => __( '«', 'text-domain' ),
    'next_text' => __( '»', 'text-domain' ),
    'total' => $num_of_pages,
    'current' => $pagenum
   ) );
   if ( $page_links ) {
    echo '<div class="tablenav"><div class="tablenav-pages" style="margin: 1em 0">' . $page_links . '</div></div>';
   }
   ?>
  </div>
  <br class="clear">
 </div>
</form>

0 Billing Address Same as Shipping Address jQuery

Billing Address Same as Shipping Address jQuery
 <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
 <script type="text/javascript">
   $(document).ready(function(){ 
    $('#check-address').click(function(){ 
     if ($('#check-address').is(":checked")) {
      $('#txtfname_billing').val($('#txtfname').val());
      $('#txtlname_billing').val($('#txtlname').val());
      $('#txtaddress_billing').val($('#txtaddress').val());
      $('#txtcity_billing').val($('#txtcity').val());
      var country = $('#country option:selected').val();
      $('#country_billing option[value=' + country + ']').attr('selected','selected');
     } else { //Clear on uncheck
      $('#txtfname_billing').val("");
      $('#txtlname_billing').val("");
      $('#txtaddress_billing').val("");
      $('#txtcity_billing').val("");
      $('#country_billing option[value=""]').attr('selected','selected');
     };
    });
   });
   </script>
   
<p>First Name : <input type="text" id="txtfname" name="txtfname" placeholder="First Name"></p>  
<p>Last Name : <input type="text" id="txtlname" name="txtlname" placeholder="Last Name"></p>  
<p>Address : <input type="text" id="txtaddress" name="txtaddress" placeholder="Ship to Address"></p>  
<p>City : <input type="text" id="txtcity" name="txtcity" placeholder="Ship to City"></p>  
<p>Country : <select name="country" size="1" id="country">
      <option value="">Select Country..</option>  
      <option value="Philippines">Philippines</option>
      </select></p>  
 
 <p><b>Billing Information <label><input type="checkbox" value="" id="check-address">Same as billing?</label></b></p>
<p>First Name : <input type="text" id="txtfname_billing" name="txtfname_billing" placeholder="First Name"></p>
<p>Last Name : <input type="text" id="txtlname_billing" name="txtlname_billing" placeholder="Last Name"></p>
<p>Address :  <input type="text" id="txtaddress_billing" name="txtaddress_billing" placeholder="Ship to Address"></p>
<p>City :  <input type="text" id="txtcity_billing" name="txtcity_billing" placeholder="Ship to City"></p>
<p>Country :  <select name="country_billing" size="1" id="country_billing">
      <option value="">Select Country..</option>  
     <option value="Philippines">Philippines</option>
      </select></p>

0 php Randomize Background Image

php Randomize Background Image
<?php
  $bg = array('bg-01.jpg', 'bg-02.jpg', 'bg-03.jpg', 'bg-04.jpg', 'bg-05.jpg', 'bg-06.jpg', 'bg-07.jpg' ); // array of filenames

  $i = rand(0, count($bg)-1); // generate random number size of the array
  $selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
?>
<style type="text/css">
body{
background: url(images/<?php echo $selectedBg; ?>) no-repeat;
}
</style>
Related Posts Plugin for WordPress, Blogger...