article

Tuesday, November 29, 2016

Billing Address Same as Shipping Address jQuery

Billing Address Same as Shipping Address jQuery

<!DOCTYPE html>
<html>
<head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Billing Address Same as Shipping Address jQuery</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.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>
</head>
<body>
 <header class="bg-dark" style="height: 60px; padding: 5px;">
  <h3 class="text-light" style="text-align: center;">Billing Address Same as Shipping Address jQuery</h3>
 </header>
 <div class="container bg-dark">
 <div class="row">
  <div class="col-sm-1"></div>
  <div class="col-sm-2"></div>  
  <div class="col-sm-6 bg-light boxStyle">
   <form name="theform" action="" method="post">
   <div class="form-group">
    <div class="width30 floatL"><label>Firstname</label></div>
    <div class="width70 floatR"><input type="text" id="txtfname" name="txtfname" placeholder="First Name" class="form-control"></div><br><br>
   </div>
   <div class="form-group">
    <div class="width30 floatL"><label>Lastname</label></div>
    <div class="width70 floatR"><input type="text" id="txtlname" name="txtlname" placeholder="Last Name" class="form-control"></div>
   </div><br>
   <div class="form-group">
    <div class="width30 floatL"><label>Address</label></div>
    <div class="width70 floatR"><input type="text" id="txtaddress" name="txtaddress" placeholder="Ship to Address" class="form-control"></div>
   </div><br>
   <div class="form-group">
    <div class="width30 floatL"><label>City</label></div>
    <div class="width70 floatR"><input type="text" id="txtcity" name="txtcity" placeholder="Ship to City" class="form-control"></div>
   </div><br>
   <div class="form-group">
    <div class="width30 floatL"><label>Country</label></div>
    <div class="width70 floatR"><select name="country" size="1" id="country" class="form-control">
     <option value="">Select Country..</option>  
     <option value="Philippines">Philippines</option>
     </select></div>
   </div><br>
   <hr/> 
   <p><b>Billing Information <label><input type="checkbox" value="" id="check-address">Same as billing?</label></b></p> 
   <div class="form-group">
    <div class="width30 floatL"><label>Firstname</label></div>
    <div class="width70 floatR"><input type="text" id="txtfname_billing" name="txtfname_billing" placeholder="First Name" class="form-control">
   </div><br><br>
   <div class="form-group">
    <div class="width30 floatL"><label>Lastname</label></div>
    <div class="width70 floatR"><input type="text" id="txtlname_billing" name="txtlname_billing" placeholder="Last Name" class="form-control"></div>
   </div><br>
   <div class="form-group">
    <div class="width30 floatL"><label>Address</label></div>
    <div class="width70 floatR"><input type="text" id="txtaddress_billing" name="txtaddress_billing" placeholder="Ship to Address" class="form-control"></div>
   </div><br>
   <div class="form-group">
    <div class="width30 floatL"><label>City</label></div>
    <div class="width70 floatR"><input type="text" id="txtcity_billing" name="txtcity_billing" placeholder="Ship to City" class="form-control"></div>
   </div><br>
   <div class="form-group">
    <div class="width30 floatL"><label>Country</label></div>
    <div class="width70 floatR"><select name="country_billing" size="1" id="country_billing" class="form-control">
      <option value="">Select Country..</option>  
     <option value="Philippines">Philippines</option>
      </select></div>
   </div><br> 
   

   <div class="form-group">
   <div class="row">
   <div class="floatR"><br/><input class="btn btn-success" type="submit"   value="Submit" style="font-weight: bold"></div> 
   </div>
   </div>
   </form>      
  </div>
  <div class="col-sm-1"></div>
  <div class="col-sm-2"></div>
  </div> 
 </div> 
<style>
.width30 {
  width: 30%;
 }
 .width70 {
  width: 70%; 
 }
 .floatL{
  float: left;
 }
 .floatR{
  float: right;
 }
 .boxStyle{
  padding: 20px; 
  border-radius: 25px; 
  border-top: 6px solid #dc3545;
  border-bottom: 6px solid #28a745;
 }
</style>
</body>
</html>

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>

Saturday, November 26, 2016

Basic Example using SMTP (no authentication) and attachments

Basic Example using SMTP (no authentication) and attachments
require_once('../class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded

$mail             = new PHPMailer();

$body             = file_get_contents('contents.html');
$body             = eregi_replace("[\]",'',$body);

$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host       = "mail.yourdomain.com"; // SMTP server
$mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
                                           // 1 = errors and messages
                                           // 2 = messages only

$mail->SetFrom('name@yourdomain.com', 'First Last');

$mail->AddReplyTo("name@yourdomain.com","First Last");

$mail->Subject    = "PHPMailer Test Subject via smtp, basic with no authentication";

$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

$mail->MsgHTML($body);

$address = "whoto@otherdomain.com";
$mail->AddAddress($address, "John Doe");

$mail->AddAttachment("images/phpmailer.gif");      // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!";
}

Saturday, August 13, 2016

Notification Box, Alert Boxes using Jquery CSS

Notification Box, Alert Boxes using Jquery CSS
<!DOCTYPE html>
<html lang="en">
<head>
<title>Notification Box, Alert Boxes using Jquery CSS</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<style>
div.alert-message {
 display: block;
 padding: 13px 12px 12px;
 font-weight: bold;
 font-size: 14px;
 color: white;
 background-color: #2ba6cb;
 border: 1px solid rgba(0, 0, 0, 0.1);
 margin-bottom: 12px;
 -webkit-border-radius: 3px;
 -moz-border-radius: 3px;
 -ms-border-radius: 3px;
 -o-border-radius: 3px;
 border-radius: 3px;
 text-shadow: 0 -1px rgba(0, 0, 0, 0.3);
 position: relative;
}
div.alert-message .box-icon {
 display: block;
 float: left;
 background-image: url('images/icon.png');
 width: 30px;
 height: 25px;
 margin-top: -2px;
 background-position: -8px -8px;
}
div.alert-message p {
 margin: 0px;
}
div.alert-message.success {
 background-color: #5da423;
 color: #fff;
 text-shadow: 0 -1px rgba(0, 0, 0, 0.3);
}
div.alert-message.success .box-icon {
 background-position: -48px -8px;
}
div.alert-message.warning {
 background-color: #e3b000;
 color: #fff;
 text-shadow: 0 -1px rgba(0, 0, 0, 0.3);
}
div.alert-message.warning .box-icon {
 background-position: -88px -8px;
}
div.alert-message.error {
 background-color: #c60f13;
 color: #fff;
 text-shadow: 0 -1px rgba(0, 0, 0, 0.3);
}
div.alert-message.error .box-icon {
 background-position: -128px -8px;
}
div.alert-message a.close {
 color: #333;
 position: absolute;
 right: 4px;
 top: -1px;
 font-size: 17px;
 opacity: 0.2;
 padding: 4px;
}
div.alert-message a.close:hover, div.alert-box a.close:focus {
 opacity: 0.4;
}
</style>
<!-- JavaScript Test Zone -->
<script type="text/javascript"> 
$(function(){   
 $(".alert-message").delegate("a.close", "click", function(event) {
   event.preventDefault();
   $(this).closest(".alert-message").fadeOut(function(event){
    $(this).remove();
   });
  });
});
  </script>
</head>
<body>
 <div class="panels">
        <div class="panel" id="panel-1">
          <div class="alert-message info">
            <div class="box-icon"></div>
            <p>This is an info box<a href="" class="close">×</a>
          </div>
          <div class="alert-message success">
            <div class="box-icon"></div>
            <p>This is a success box<a href="" class="close">×</a>
          </div>
          <div class="alert-message warning">
            <div class="box-icon"></div>
            <p>This is a warning box<a href="" class="close">×</a>
          </div>
          <div class="alert-message error">
            <div class="box-icon"></div>
            <p>This is an alert box<a href="" class="close">×</a>
          </div>
        </div>
  </div>
</body>
</html>

Friday, August 12, 2016

CodeIgniter - Upload an Image

CodeIgniter - Upload an Image

Copy the following code and store it at application/view/Upload_form.php.
<html>
   <head> 
      <title>Upload Form</title> 
   </head>
   <body> 
      <?php echo $error;?> 
      <?php echo form_open_multipart('upload/do_upload');?> 
      <form action = "" method = "">
         <input type = "file" name = "userfile" size = "20" /> 
         <br /><br /> 
         <input type = "submit" value = "upload" /> 
      </form> 
   </body>
</html>

Copy the code given below and store it at application/view/upload_success.php

<html>
   <head> 
      <title>Upload Image</title> 
   </head>
   <body>  
      <h3>Upload an Image Success!</h3>  
   </body>
</html>

Copy the code given below and store it at application/controllers/upload.php. Create "uploads" folder at the root of CodeIgniter i.e. at the parent directory of application folder.

<?php
  
   class Upload extends CI_Controller {
 
      public function __construct() { 
         parent::__construct(); 
         $this->load->helper(array('form', 'url')); 
      }
  
      public function index() { 
         $this->load->view('upload_form', array('error' => ' ' )); 
      } 
  
      public function do_upload() { 
         $config['upload_path']   = './uploads/'; 
         $config['allowed_types'] = 'gif|jpg|png'; 
         $config['max_size']      = 100; 
         $config['max_width']     = 1024; 
         $config['max_height']    = 768;  
         $this->load->library('upload', $config);
   
         if ( ! $this->upload->do_upload('userfile')) {
            $error = array('error' => $this->upload->display_errors()); 
            $this->load->view('upload_form', $error); 
         }
   
         else { 
            $data = array('upload_data' => $this->upload->data()); 
            $this->load->view('upload_success', $data); 
         } 
      } 
   } 
?>

Make the following change in the route file in application/config/routes.php and add the following line at the end of file.

$route['upload'] = 'Upload';

Now let us execute this example by visiting the following URL in the browser. Replace the yoursite.com with your URL.

http://yoursite.com/index.php/upload

Download http://bit.ly/2XgSkMN

Django - Template System

Django - Template System 

Django makes it possible to separate python and HTML, the python goes in views and HTML goes in templates.

The Render Function
This function takes three parameters −

Request − The initial request.

The path to the template − This is the path relative to the TEMPLATE_DIRS option in the project settings.py variables.

Dictionary of parameters − A dictionary that contains all variables needed in the template. This variable can be created or you can use locals() to pass all local variable declared in the view.

Displaying Variables
A variable looks like this: {{variable}}. The template replaces the variable by the variable sent by the view in the third parameter of the render function.

hello.html
Hello World!!!Today is {{today}}


Then our view will change to −
def hello(request):
from django.shortcuts import render
from django.http import HttpResponse 

from datetime import datetime

def index(request):
     return render(request, "index.html", {})
 
def hello(request):
   myDate = datetime.now()
   #formatedDate = myDate.strftime("%Y-%m-%d %H:%M:%S")
   #today = myDate.strftime("%A")
   today = myDate.strftime("%a")
   
   daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
   return render(request, "hello.html", {"today" : today, "days_of_week" : daysOfWeek})
   
   #return render(request, "hello.html", {"today" : today}) 

We will now get the following output after accessing the URL/myapp/hello −
Hello World!!!
Today is Sept. 11, 2016

Tag if
Just like in Python you can use if, else and elif in your template −
 
<html>
   <body>
      Hello World!!!<p>Today is {{today}}</p>
      We are
      {% if today == 'Sun' %}
      
      the Sunday day of month.
      {% elif today == 30 %}
      
      the last day of month.
      {% else %}
      
      I don't know.
      {%endif%}
   </body>
</html>
In this new template, depending on the date of the day, the template will render a certain value.
Tag for
Just like 'if', we have the 'for' tag, that works exactly like in Python. Let's change our hello view to transmit a list to our template −
 
def hello(request):
   today = datetime.datetime.now().date()
   
   daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
   return render(request, "hello.html", {"today" : today, "days_of_week" : daysOfWeek})
The template to display that list using {{ for }} −
 
<html>
   <body>
      Hello World!!!<p>Today is {{today}}</p>
      We are
      {% if today.day == 1 %}
      
      the first day of month.
      {% elif today == 30 %}
      
      the last day of month.
      {% else %}
      
      I don't know.
      {%endif%}
      
      <p>
         {% for day in days_of_week %}
         {{day}}
      </p>
  
      {% endfor %}
      
   </body>
</html>
And we should get something like −

Hello World!!!
Today is Sept. 11, 2015
We are I don't know.
Mon
Tue
Wed
Thu
Fri
Sat
Sun

Block and Extend Tags
A template system cannot be complete without template inheritance. Meaning when you are designing your templates, you should have a main template with holes that the child's template will fill according to his own need, like a page might need a special css for the selected tab.

Let’s change the hello.html template to inherit from a main_template.html.

main_template.html

 
<html>
   <head>
      
      <title>
         {% block title %}Page Title{% endblock %}
      </title>
      
   </head>
 
   <body>
   
      {% block content %}
         Body content
      {% endblock %}
      
   </body>
</html>
hello.html
 
{% extends "main_template.html" %}
{% block title %}My Hello Page{% endblock %}
{% block content %}

Hello World!!!Today is {{today}}
We are {% if today.day == 1 %} the first day of month. {% elif today == 30 %} the last day of month. {% else %} I don't know. {%endif%} {% for day in days_of_week %} {{day}}
{% endfor %} {% endblock %}

Cool Notification Messages With CSS3 & jQuery

Cool Notification Messages With CSS3 & jQuery
<!DOCTYPE html>
<html>
<head>
<title>Cool notification messages with CSS3 & Jquery</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var myMessages = ['info','warning','error','success']; // define the messages types   
function hideAllMessages()
{
   var messagesHeights = new Array(); // this array will store height for each
  
   for (i=0; i<myMessages.length; i++)
   {
      messagesHeights[i] = $('.' + myMessages[i]).outerHeight();
      $('.' + myMessages[i]).css('top', -messagesHeights[i]); //move element outside viewport   
   }
}
function showMessage(type)
{
 $('.'+ type +'-trigger').click(function(){
    hideAllMessages();      
    $('.'+type).animate({top:"0"}, 500);
 });
}
$(document).ready(function(){
   // Initially, hide them all
   hideAllMessages();
   // Show message
   for(var i=0;i<myMessages.length;i++)
   {
   showMessage(myMessages[i]);
   }
   // When message is clicked, hide it
   $('.message').click(function(){     
      $(this).animate({top: -$(this).outerHeight()}, 500);
    });   
});       
</script>
<style>
body
{
   margin: 0;
   padding: 0;
   font: 12px Arial, Helvetica, sans-serif;
   background: #f1f1f1;
}
.message
{
  -webkit-background-size: 40px 40px;
  -moz-background-size: 40px 40px;
  background-size: 40px 40px;   
  background-image: -webkit-gradient(linear, left top, right bottom,
        color-stop(.25, rgba(255, 255, 255, .05)), color-stop(.25, transparent),
        color-stop(.5, transparent), color-stop(.5, rgba(255, 255, 255, .05)),
        color-stop(.75, rgba(255, 255, 255, .05)), color-stop(.75, transparent),
        to(transparent));
  background-image: -webkit-linear-gradient(135deg, rgba(255, 255, 255, .05) 25%, transparent 25%,
       transparent 50%, rgba(255, 255, 255, .05) 50%, rgba(255, 255, 255, .05) 75%,
       transparent 75%, transparent);
  background-image: -moz-linear-gradient(135deg, rgba(255, 255, 255, .05) 25%, transparent 25%,
       transparent 50%, rgba(255, 255, 255, .05) 50%, rgba(255, 255, 255, .05) 75%,
       transparent 75%, transparent);
  background-image: -ms-linear-gradient(135deg, rgba(255, 255, 255, .05) 25%, transparent 25%,
       transparent 50%, rgba(255, 255, 255, .05) 50%, rgba(255, 255, 255, .05) 75%,
       transparent 75%, transparent);
  background-image: -o-linear-gradient(135deg, rgba(255, 255, 255, .05) 25%, transparent 25%,
       transparent 50%, rgba(255, 255, 255, .05) 50%, rgba(255, 255, 255, .05) 75%,
       transparent 75%, transparent);
  background-image: linear-gradient(135deg, rgba(255, 255, 255, .05) 25%, transparent 25%,
       transparent 50%, rgba(255, 255, 255, .05) 50%, rgba(255, 255, 255, .05) 75%,
       transparent 75%, transparent);
        
   -moz-box-shadow: inset 0 -1px 0 rgba(255,255,255,.4);
   -webkit-box-shadow: inset 0 -1px 0 rgba(255,255,255,.4);  
   box-shadow: inset 0 -1px 0 rgba(255,255,255,.4);
   width: 100%;
   border: 1px solid;
   color: #fff;
   padding: 15px;
   position: fixed;
   _position: absolute;
   text-shadow: 0 1px 0 rgba(0,0,0,.5);
   -webkit-animation: animate-bg 5s linear infinite;
   -moz-animation: animate-bg 5s linear infinite;
}
.info
{
   background-color: #4ea5cd;
   border-color: #3b8eb5;
}
.error
{
   background-color: #de4343;
   border-color: #c43d3d;
}  
.warning
{
   background-color: #eaaf51;
   border-color: #d99a36;
}
.success
{
   background-color: #61b832;
   border-color: #55a12c;
}
.message h3
{
   margin: 0 0 5px 0;              
}
.message p
{
   margin: 0;              
}
@-webkit-keyframes animate-bg
{
    from {
        background-position: 0 0;
    }
    to {
       background-position: -80px 0;
    }
}
@-moz-keyframes animate-bg 
{
    from {
        background-position: 0 0;
    }
    to {
       background-position: -80px 0;
    }
}
#trigger-list
{
   text-align: center;
   margin: 100px 0;
   padding: 0;
}
#trigger-list li
{
   display: inline-block;
   *display: inline;
   zoom: 1;
}
#trigger-list .trigger
{
   display: inline-block;
   background: #ddd;
   border: 1px solid #777;
   padding: 10px 20px;
   margin: 0 5px;
   font: bold 12px Arial, Helvetica;
   text-decoration: none;
   color: #333;
   -moz-border-radius: 3px;
   -webkit-border-radius: 3px;
   border-radius: 3px;
}
#trigger-list .trigger:hover
{
  background: #f5f5f5;
}
.centered
{
   text-align: center;
}
.twitter-follow-button
{
   position: relative;
   top: 7px;
}
</style>
</head>
<body>
<div class="info message">
   <h3>FYI, something just happened!</h3>
   <p>This is just an info notification message.</p>
</div>
<div class="error message">
   <h3>Ups, an error ocurred</h3>
   <p>This is just an error notification message.</p>

</div>
<div class="warning message">
   <h3>Wait, I must warn you!</h3>
   <p>This is just a warning notification message.</p>
</div>
<div class="success message">
   <h3>Congrats, you did it!</h3>
   <p>This is just a success notification message.</p>

</div>
<ul id="trigger-list">
   <li><a href="#" class="trigger info-trigger">Info</a></li>
   <li><a href="#" class="trigger error-trigger">Error</a></li>
   <li><a href="#" class="trigger warning-trigger">Warning</a></li>
   <li><a href="#" class="trigger success-trigger">Success</a></li>
</ul>
</body>
</html>

Friday, July 29, 2016

Fancy Tooltips using CSS3

Fancy Tooltips using CSS3
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CSS3 Tooltips</title>
<style>
body {
 background:#fafafa;
}
.container {
 width: 800px;
 border: 1px solid #C4CDE0;
 border-radius: 2px;
 margin: 0 auto;
 height: 500px;
 background:#fff;
 padding-left:10px;
 margin-bottom:30px;
}
.css-tooltip-top,
.css-tooltip-bottom,
.css-tooltip-right,
.css-tooltip-left
 {
 position: relative !important;
 display: inline-block !important;
 text-decoration: none !important;    
 }
 
.css-tooltip-top span,
.css-tooltip-bottom span,
.css-tooltip-right span,
.css-tooltip-left span,
.css-tooltip-diagonal-right span,
.css-tooltip-diagonal-left span
 {
 min-width: 180px;
 font-family: arial, sans-serif !important;
 font-size: 13px !important;
 line-height: normal !important;
 text-align: left !important;
 padding: 10px 10px 12px 10px !important;
 visibility: hidden;
    opacity: 0;
 position: absolute;
 z-index: 9999999 !important;

 -webkit-transition-duration: 0.25s;
 -moz-transition-duration: 0.25s;
 -o-transition-duration: 0.25s;
 -ms-transition-duration: 0.25s;
 transition-duration: 0.25s;
 -webkit-transition-timing-function: cubic-bezier(0.35,0,0.35,1);
 -moz-transition-timing-function: cubic-bezier(0.35,0,0.35,1);
 -o-transition-timing-function: cubic-bezier(0.35,0,0.35,1);
 -ms-transition-timing-function: cubic-bezier(0.35,0,0.35,1);
 transition-timing-function: cubic-bezier(0.35,0,0.35,1);
 }

.css-tooltip-top span:before,
.css-tooltip-bottom span:before,
.css-tooltip-right span:before,
.css-tooltip-left span:before,
.css-tooltip-diagonal-right span:before,
.css-tooltip-diagonal-left span:before
 {
 content: "";
 display: block;
 width: 0px;
 height: 0px;
 position: absolute;
 }

/* Tool tip Top */
.css-tooltip-top span
 {
 left: -10px;
 bottom: 100%;
 margin-bottom: 30px;
 
 -webkit-transition-property: opacity, margin-bottom, visibility;
 -moz-transition-property: opacity, margin-bottom, visibility;
 -o-transition-property: opacity, margin-bottom, visibility;
 -ms-transition-property: opacity, margin-bottom, visibility;
 transition-property: opacity, margin-bottom, visibility;
 }
 
.css-tooltip-top span:before
 {
    border-left: 8px solid transparent !important;
    border-right: 8px solid transparent !important;
 border-top: 8px solid #000;
 border-bottom: 0 !important;
 bottom: -8px;
 left: 15px;
 }

.css-tooltip-top:hover span
 { 
 margin-bottom: 10px; /* End Position */
 visibility: visible;
 opacity: 1;
 }

 
/* tooltip left
-------------------------------------------------------------- */

.css-tooltip-left span
 {
 right: 100%;
 top: -7px;
 margin-right: 35px;
 
 -webkit-transition-property: opacity, margin-right, visibility;
 -moz-transition-property: opacity, margin-right, visibility;
 -o-transition-property: opacity, margin-right, visibility;
 -ms-transition-property: opacity, margin-right, visibility;
 transition-property: opacity, margin-right, visibility;
 }
 
.css-tooltip-left span:before
 {
    border-left: 8px solid #000;
    border-right: 0 !important;
 border-top: 8px solid transparent !important;
 border-bottom: 8px solid transparent !important;
 top: 11px;
 right: -8px;
 }

.css-tooltip-left:hover span
 { 
 margin-right: 15px;
 visibility: visible;
 opacity: 1;
 }
 
/* tooltip right
-------------------------------------------------------------- */

.css-tooltip-right span
 {
 left: 100%;
 top: -7px;
 margin-left: 35px;

 -webkit-transition-property: opacity, margin-left, visibility;
 -moz-transition-property: opacity, margin-left, visibility;
 -o-transition-property: opacity, margin-left, visibility;
 -ms-transition-property: opacity, margin-left, visibility;
 transition-property: opacity, margin-left, visibility;
 }
 
.css-tooltip-right span:before {
    border-left: 0 !important;
    border-right: 8px solid #000;
 border-top: 8px solid transparent !important;
 border-bottom: 8px solid transparent !important;
 top: 11px;
 left: -8px;
 }

.css-tooltip-right:hover span
 { 
 margin-left: 15px;
 visibility: visible;
 opacity: 1;
 }
 
 
/*tooltip bottom
-------------------------------------------------------------- */

.css-tooltip-bottom span
 {
 left: -10px;
 top: 100%;
 margin-top: 30px;
 
 -webkit-transition-property: opacity, margin-top, visibility;
 -moz-transition-property: opacity, margin-top, visibility;
 -o-transition-property: opacity, margin-top, visibility;
 -ms-transition-property: opacity, margin-top, visibility;
 transition-property: opacity, margin-top, visibility;
 }
 
.css-tooltip-bottom span:before
 {
    border-left: 8px solid transparent !important;
    border-right: 8px solid transparent !important;
 border-top: 0 !important;
 border-bottom: 8px solid #000;
 top: -8px;
 left: 15px;
 }

.css-tooltip-bottom:hover span
 { 
 margin-top: 10px;
 visibility: visible;
 opacity: 1;
 }
 
/* Tooltip Color */
.color-blue span
 {
 color: #ffffff !important;
 
 background: #31598a;
 background: -moz-linear-gradient(top,  #37659d 0%, #31598a 100%);
 background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#37659d), color-stop(100%,#31598a)); 
 background: -webkit-linear-gradient(top,  #37659d 0%,#31598a 100%);
 background: -o-linear-gradient(top,  #37659d 0%,#31598a 100%);
 background: -ms-linear-gradient(top,  #37659d 0%,#31598a 100%);
 background: linear-gradient(top,  #37659d 0%,#31598a 100%);

 -webkit-border-radius: 4px;
 -moz-border-radius: 4px;
 border-radius: 4px;
 
 text-shadow: 0px 1px 0px rgba(0,0,0,0.4);
 }

.color-blue span:before
 {
 border-color: #31598a;
 }
 
.color-blue span:after
 {
 content: "";
 display: block;
 border-top: 1px solid #6591c3;
 position: absolute;
 left: 0px;
 top: 1px;
 width: 100%;
 height: 10px;
 
 -webkit-border-radius: 4px;
 -moz-border-radius: 4px;
 border-radius: 4px;
 }
 
.color-green span
 {
 color: #ffffff !important;
 
 
 background: #206906; 
 background: -moz-linear-gradient(top,  #37790c 0%, #206906 100%); 
 background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#37790c), color-stop(100%,#206906)); 
 background: -webkit-linear-gradient(top,  #37790c 0%,#206906 100%); 
 background: -o-linear-gradient(top,  #37790c 0%,#206906 100%); 
 background: -ms-linear-gradient(top,  #37790c 0%,#206906 100%); 
 background: linear-gradient(top,  #37790c 0%,#206906 100%); 
 
 -webkit-border-radius: 4px;
 -moz-border-radius: 4px;
 border-radius: 4px;
 
 
 text-shadow: 0px 1px 0px rgba(0,0,0,0.4);
 }


.color-green span:before
 {
 border-color: #206906;
 }
 

.color-green span:after
 {
 content: "";
 display: block;
 border-top: 1px solid #4f9c21;
 position: absolute;
 left: 0px;
 top: 1px;
 width: 100%;
 height: 10px;
 
 
 -webkit-border-radius: 4px;
 -moz-border-radius: 4px;
 border-radius: 4px;
 }
 

.color-green span strong
 {
 background: #246407;
 border-bottom: 1px solid #205a06;
 }
 
/*orange*/

.color-orange span
 {
 color: #ffffff !important;
 
 
 background: #c34722; 
 background: -moz-linear-gradient(top,  #cb581f 0%, #c34722 100%); 
 background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#cb581f), color-stop(100%,#c34722)); 
 background: -webkit-linear-gradient(top,  #cb581f 0%,#c34722 100%); 
 background: -o-linear-gradient(top,  #cb581f 0%,#c34722 100%); 
 background: -ms-linear-gradient(top,  #cb581f 0%,#c34722 100%); 
 background: linear-gradient(top,  #cb581f 0%,#c34722 100%);
 
 -webkit-border-radius: 4px;
 -moz-border-radius: 4px;
 border-radius: 4px;
 
 
 text-shadow: 0px 1px 0px rgba(0,0,0,0.4);
 }


.color-orange span:before
 {
 border-color: #c34722;
 }
 

.color-orange span:after
 {
 content: "";
 display: block;
 border-top: 1px solid #e28266;
 position: absolute;
 left: 0px;
 top: 1px;
 width: 100%;
 height: 10px;
 
 
 -webkit-border-radius: 4px;
 -moz-border-radius: 4px;
 border-radius: 4px;
 }
 

.color-orange span strong
 {
 background: #bf461a;
 border-bottom: 1px solid #ac3f17;
 }
 
 /*red*/

.color-red span
 {
 color: #ffffff !important;
 background: #b01c34; 
 background: -moz-linear-gradient(top,  #c01e38 0%, #b01c34 100%); 
 background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#c01e38), color-stop(100%,#b01c34)); 
 background: -webkit-linear-gradient(top,  #c01e38 0%,#b01c34 100%); 
 background: -o-linear-gradient(top,  #c01e38 0%,#b01c34 100%); 
 background: -ms-linear-gradient(top,  #c01e38 0%,#b01c34 100%); 
 background: linear-gradient(top,  #c01e38 0%,#b01c34 100%); 
 -webkit-border-radius: 4px;
 -moz-border-radius: 4px;
 border-radius: 4px;
 text-shadow: 0px 1px 0px rgba(0,0,0,0.4);
 }
.color-red span:before
 {
 border-color: #b01c34;
 }
.color-red span:after
 {
 content: "";
 display: block;
 border-top: 1px solid #e96e82;
 position: absolute;
 left: 0px;
 top: 1px;
 width: 100%;
 height: 10px;
 -webkit-border-radius: 4px;
 -moz-border-radius: 4px;
 border-radius: 4px;
 }
.color-red span strong
 {
 background: #b0182d;
 border-bottom: 1px solid #9d1628;
 }
</style>
</head>
<body>
<div class="container">
<p>
<a class="css-tooltip-bottom color-red"  target="_blank" href="#"><span>Tutorial101 laravel</span>Bottom tooltip</a>
</p>
<br />
<p>
<a class="css-tooltip-left color-green" href="#" target="_blank"><span>Tutorial101 codeignater</span>Left tooltip</a>
</p>
<br />
<p>
<a class="css-tooltip-right color-orange" target="_blank" href="#"><span>Tutorial101 Cakephp</span>Right tooltip</a>
</p>
</div>
</body>
</html>

Responsive Navigation Menu using CSS and jQuery

Responsive Navigation Menu using CSS and jQuery
<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Resize Nav Menu Demo</title>
    <link href="http://fonts.googleapis.com/css?family=Roboto:700,400&subset=latin" rel="stylesheet" type="text/css">
</head>
<body>
<style>
html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}
body{margin:0}
article,aside,details,figcaption,figure,footer,header,hgroup,main,menu,nav,section,summary{display:block}
audio,canvas,progress,video{display:inline-block;vertical-align:baseline}
audio:not([controls]){display:none;height:0}[hidden],template{display:none}
a{background-color:transparent}a:active,a:hover{outline:0}
abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}
dfn{font-style:italic}h1{font-size:2em;margin:.67em 0}
mark{background:#ff0;color:#000}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{box-sizing:content-box;height:0}pre{overflow:auto}code,kbd,pre,samp{font-family:monospace;font-size:1em}button,input,optgroup,select,textarea{color:inherit;font:inherit;margin:0}button{overflow:visible}button,select{text-transform:none}button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}input{line-height:normal}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}input[type=number]::-webkit-inner-spin-button,input[type=number]::-webkit-outer-spin-button{height:auto}input[type=search]{-webkit-appearance:textfield;box-sizing:content-box}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}legend{border:0;padding:0}textarea{overflow:auto}optgroup{font-weight:700}table{border-collapse:collapse;border-spacing:0}td,th{padding:0}*{box-sizing:border-box}:after,:before{box-sizing:inherit}html{font-size:62.5%;-webkit-tap-highlight-color:rgba(0,0,0,0);font-family:@font-family-base}body{font-family:Roboto,Helvetica Neue,Helvetica,Arial,sans-serif;font-size:1.4rem;line-height:1.42857143;color:#555;background-color:#f7f7f7}a{text-decoration:none}ul{margin:0;padding:0;list-style:none}main{margin-top:10rem;text-align:center}

header{-webkit-align-items:center;-ms-flex-align:center;align-items:center;background-color:#fff;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:row;-ms-flex-direction:row;flex-direction:row;height:7rem;padding:0 15px;position:fixed;-webkit-justify-content:space-between;-ms-flex-pack:justify;justify-content:space-between;top:0;width:100%}
.site-logo{transition:color .2s cubic-bezier(.55,0,.1,1);color:#30acff;font-size:3rem}
.ok-header__logo:hover{color:#546edb}
body.resizeNav-loaded{overflow-x:hidden}
.resizeNav-header{position:fixed;top:0;display:-webkit-flex;display:-ms-flexbox;display:flex;flex-direction:row;width:100%;padding:0 15px;-webkit-align-items:center;-ms-flex-align:center;align-items:center;-webkit-flex-direction:row;-ms-flex-direction:row;-webkit-justify-content:space-between;-ms-flex-pack:justify;justify-content:space-between}
.resizeNav:not(.loaded){visibility:hidden;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}
.resizeNav ul{float:left}
.resizeNav a{position:relative;z-index:1}
.resizeNav__nav--visible{overflow:hidden;white-space:nowrap}
.resizeNav__nav--visible li{display:inline-block}.resizeNav__nav--visible a{display:block;padding:15px;transition:color .2s cubic-bezier(.55,0,.1,1)}
.resizeNav__nav--visible:empty~.resizeNav__menu-toggle{top:0}.resizeNav__nav--invisible{position:fixed;top:7rem;bottom:0;overflow-y:scroll;-webkit-overflow-scrolling:touch}.resizeNav__nav--invisible a{display:block;width:240px;padding:15px;background:#fff}.resizeNav__nav--invisible.nav-left{left:0;-webkit-transform:translateX(-100%);transform:translateX(-100%)}.resizeNav__nav--invisible.nav-right{right:0;-webkit-transform:translateX(100%);transform:translateX(100%)}.resizeNav__nav--invisible.transition-enabled{transition:-webkit-transform .4s cubic-bezier(.55,0,.1,1);transition:transform .4s cubic-bezier(.55,0,.1,1);transition:transform .4s cubic-bezier(.55,0,.1,1),-webkit-transform .4s cubic-bezier(.55,0,.1,1)}.resizeNav__nav--invisible.nav-open{-webkit-transform:translateX(0);transform:translateX(0)}.resizeNav__menu-toggle{position:relative;z-index:1;top:15px;float:left;width:40px;height:20px;cursor:pointer;transition:-webkit-transform .4s cubic-bezier(.55,0,.1,1);transition:transform .4s cubic-bezier(.55,0,.1,1);transition:transform .4s cubic-bezier(.55,0,.1,1),-webkit-transform .4s cubic-bezier(.55,0,.1,1)}.resizeNav__menu-toggle.okay-invisible{position:absolute;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;pointer-events:none;opacity:0}.resizeNav__menu-toggle span{position:absolute;right:0;left:0;display:block;width:4px;height:4px;margin:auto;pointer-events:none;border-radius:50%}.resizeNav__menu-toggle span:nth-child(1){top:0}.resizeNav__menu-toggle span:nth-child(2){top:50%;-webkit-transform:translateY(-50%);transform:translateY(-50%)}.resizeNav__menu-toggle span:nth-child(3){bottom:0}.resizeNav__menu-toggle.icon--active{-webkit-transform:rotate(90deg);transform:rotate(90deg)}
.resizeNav-header{height:7rem;background-color:#fff}
.resizeNav a{color:#2e2e33;font-size:1.4rem;font-weight:700}
.resizeNav__nav--visible a:hover,.resizeNav a:hover{color:#546edb}
.resizeNav__nav--invisible{background:#fff}.resizeNav__menu-toggle span{background:#2e2e33}.resizeNav__menu-toggle.icon--active span{background:#546edb}
</style>
    <header id="header" class="resizeNav-header">
        <a class="resizeNav-header__logo" href="#">
           Logo
        </a>
  <nav role="navigation" id="nav-main" class="resizeNav">
            <ul>
                <li><a href="#">Home</a></li>
                <li><a href="#">Shop</a></li>
                <li><a href="#">Blog</a></li>
                <li><a href="#">Services</a></li>
                <li><a href="#">Contacts</a></li>
                <li><a href="#">About us</a></li>
                <li><a href="#">Testimonials</a></li>
            </ul>
        </nav>
    </header><!-- /header -->
 <main>
        <h1>Resize your browser to preview navigation menu</h1>
    </main>
 <script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
    <script type="text/javascript">
 !function(e){"function"==typeof define&&define.amd?define(["jquery"],e):"object"==typeof module&&module.exports?module.exports=function(n,i){return void 0===i&&(i="undefined"!=typeof window?require("jquery"):require("jquery")(n)),e(i),i}:e(jQuery)}(function(e){function n(n,i){self=this,this.options=e.extend({},s,i),self.options=this.options,self.navigation=e(n),self.document=e(document),self.window=e(window),""==this.options.parent?this.options.parent=self.navigation.parent():"",self.nav_open=!1,self.parent_full_width=0,self.radCoef=180/Math.PI,self.sTouch={x:0,y:0},self.cTouch={x:0,y:0},self.sTime=0,self.nav_position=0,self.percent_open=0,self.nav_moving=!1,self.init()}var i="resizeNav",s={parent:"",toggle_icon_class:"resizeNav__menu-toggle",toggle_icon_content:"<span /><span /><span />",align_right:!0,swipe_enabled:!0,threshold:50,resize_delay:10,beforeOpen:function(){},afterOpen:function(){},beforeClose:function(){},afterClose:function(){},itemHidden:function(){},itemDisplayed:function(){}};n.prototype={init:function(){e("body").addClass("resizeNav-loaded"),self.navigation.addClass("resizeNav loaded").children("ul").addClass("resizeNav__nav--visible"),self.options.align_right?self.navigation.append('<ul class="resizeNav__nav--invisible transition-enabled nav-right" />').append('<a href="#" class="'+self.options.toggle_icon_class+' okay-invisible">'+self.options.toggle_icon_content+"</a>"):self.navigation.prepend('<ul class="resizeNav__nav--invisible transition-enabled nav-left" />').prepend('<a href="#" class="'+self.options.toggle_icon_class+' okay-invisible">'+self.options.toggle_icon_content+"</a>"),self.nav_visible=self.navigation.children(".resizeNav__nav--visible"),self.nav_invisible=self.navigation.children(".resizeNav__nav--invisible"),self.toggle_icon=self.navigation.children("."+self.options.toggle_icon_class),self.toggle_icon_width=self.toggle_icon.outerWidth(!0),self.default_width=self.getChildrenWidth(self.navigation),self.parent_full_width=e(self.options.parent).outerWidth(!0),self.last_visible_child_width=0,self.initEvents(),self.nav_visible.contents().filter(function(){return this.nodeType=Node.TEXT_NODE&&/\S/.test(this.nodeValue)===!1}).remove(),1==self.options.swipe_enabled&&self.initSwipeEvents()},initEvents:function(){self.document.on("click.resizeNav",function(n){var i=e(n.target);self.nav_open===!0&&0==i.closest(".resizeNav").length&&self.closeInvisibleNav(),i.hasClass(self.options.toggle_icon_class)&&(n.preventDefault(),self.toggleInvisibleNav())});var n=self._debounce(function(){self.recalcNav()},self.options.recalc_delay);self.window.on("load.resizeNav resize.resizeNav",n)},initSwipeEvents:function(){self.document.on("touchstart.resizeNav",function(n){if(self.nav_invisible.removeClass("transition-enabled"),1==n.originalEvent.touches.length){var i=n.originalEvent.touches[0];(i.pageX<25&&0==self.options.align_right||i.pageX>e(self.options.parent).outerWidth(!0)-25&&1==self.options.align_right||self.nav_open===!0)&&(self.sTouch.x=self.cTouch.x=i.pageX,self.sTouch.y=self.cTouch.y=i.pageY,self.sTime=Date.now())}}).on("touchmove.resizeNav",function(e){var n=e.originalEvent.touches[0];self._triggerMove(n.pageX,n.pageY),self.nav_moving=!0}).on("touchend.resizeNav",function(e){self.sTouch={x:0,y:0},self.cTouch={x:0,y:0},self.sTime=0,self.percent_open>100-self.options.threshold?(self.nav_position=0,self.closeInvisibleNav()):1==self.nav_moving&&(self.nav_position=self.nav_invisible.width(),self.openInvisibleNav()),self.nav_moving=!1,self.nav_invisible.addClass("transition-enabled")})},_getDirection:function(e){return self.options.align_right?e>0?-1:1:0>e?-1:1},_triggerMove:function(e,n){self.cTouch.x=e,self.cTouch.y=n;var i=Date.now(),s=self.cTouch.x-self.sTouch.x,l=self.cTouch.y-self.sTouch.y,t=l*l,o=Math.sqrt(s*s+t),a=Math.sqrt(t),f=Math.asin(Math.sin(a/o))*self.radCoef;o/(i-self.sTime);if(self.sTouch.x=e,self.sTouch.y=n,20>f){var v=self._getDirection(s),c=self.nav_position+v*o,r=self.nav_invisible.width(),d=0;0>c?d=-c:c>r&&(d=r-c);var _=r-(self.nav_position+v*o+d),p=_/r*100;self.nav_position+=v*o+d,self.percent_open=p,self.nav_invisible.css("transform","translateX("+(self.options.align_right?1:-1)*p+"%)")}},getParent:function(){return self.options.parent},getVisibleNav:function(){return self.nav_visible},getInvisibleNav:function(){return self.nav_invisible},getNavToggleIcon:function(){return self.toggle_icon},_debounce:function(e,n,i){var s;return function(){var l=this,t=arguments,o=function(){s=null,i||e.apply(l,t)},a=i&&!s;clearTimeout(s),s=setTimeout(o,n),a&&e.apply(l,t)}},openInvisibleNav:function(){self.options.enable_swipe?"":self.options.beforeOpen.call(),self.toggle_icon.addClass("icon--active"),self.nav_invisible.addClass("nav-open"),self.nav_open=!0,self.nav_invisible.css({"-webkit-transform":"translateX(0%)",transform:"translateX(0%)"}),self.options.afterOpen.call()},closeInvisibleNav:function(){self.options.enable_swipe?"":self.options.beforeClose.call(),self.toggle_icon.removeClass("icon--active"),self.nav_invisible.removeClass("nav-open"),self.options.align_right?self.nav_invisible.css({"-webkit-transform":"translateX(100%)",transform:"translateX(100%)"}):self.nav_invisible.css({"-webkit-transform":"translateX(-100%)",transform:"translateX(-100%)"}),self.nav_open=!1,self.options.afterClose.call()},toggleInvisibleNav:function(){self.nav_open?self.closeInvisibleNav():self.openInvisibleNav()},getChildrenWidth:function(n){for(var i=0,s=e(n).children(),l=0;l<s.length;l++)i+=e(s[l]).outerWidth(!0);return i},getVisibleItemCount:function(){return e("li",self.nav_visible).length},getHiddenItemCount:function(){return e("li",self.nav_invisible).length},recalcNav:function(){var n=e(self.options.parent).outerWidth(!0),i=self.getChildrenWidth(self.options.parent),s=self.navigation.outerWidth(!0),l=self.getVisibleItemCount(),t=self.nav_visible.outerWidth(!0)+self.toggle_icon_width,o=i+self.last_visible_child_width+self.toggle_icon_width,a=i-s+self.default_width;return n>a?(self._expandAllItems(),void self.toggle_icon.addClass("okay-invisible")):(l>0&&t>=s&&o>=n&&self._collapseNavItem(),n>o+self.toggle_icon_width+15&&self._expandNavItem(),void(0==self.getHiddenItemCount()?self.toggle_icon.addClass("okay-invisible"):self.toggle_icon.removeClass("okay-invisible")))},_collapseNavItem:function(){var n=e("li:last-child",self.nav_visible);self.last_visible_child_width=n.outerWidth(!0),self.document.trigger("resizeNav:collapseItem",n),n.detach().prependTo(self.nav_invisible),self.options.itemHidden.call(),self.recalcNav()},_expandNavItem:function(){var n=e("li:first-child",self.nav_invisible);self.document.trigger("resizeNav:expandItem",n),n.detach().appendTo(self.nav_visible),self.options.itemDisplayed.call()},_expandAllItems:function(){e("li",self.nav_invisible).detach().appendTo(self.nav_visible),self.options.itemDisplayed.call()},_collapseAllItems:function(){e("li",self.nav_visible).detach().appendTo(self.nav_invisible),self.options.itemHidden.call()},destroy:function(){e("li",self.nav_invisible).appendTo(self.nav_visible),self.nav_invisible.remove(),self.nav_visible.removeClass("resizeNav__nav--visible"),self.toggle_icon.remove(),self.document.unbind(".resizeNav"),self.window.unbind(".resizeNav")}},e.fn[i]=function(s){var l=arguments;if(void 0===s||"object"==typeof s)return this.each(function(){e.data(this,"plugin_"+i)||e.data(this,"plugin_"+i,new n(this,s))});if("string"==typeof s&&"_"!==s[0]&&"init"!==s){var t;return this.each(function(){var o=e.data(this,"plugin_"+i);o instanceof n&&"function"==typeof o[s]&&(t=o[s].apply(o,Array.prototype.slice.call(l,1))),"destroy"===s&&e.data(this,"plugin_"+i,null)}),void 0!==t?t:this}}});
        var navigation = $('#nav-main').resizeNav();
    </script>
</body>
</html>

Adding/Removing Class on Hover

Adding/Removing Class on Hover
<script>
jQuery(document).ready(function($){
$('#elm').hover(
       function(){ $(this).addClass('hover') },
       function(){ $(this).removeClass('hover') }
)
});
</script>
<style>
.hover {font-size:33px;}
</style>
<div id="elm">test</div>

PHP - Get Users IP Address

Get Users IP Address 

<?php
class datasource {
 function getIP() {
  $ipaddress = '';
  if (isset($_SERVER['HTTP_CLIENT_IP']))
   $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
  else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
   $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
  else if(isset($_SERVER['HTTP_X_FORWARDED']))
   $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
  else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
   $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
  else if(isset($_SERVER['HTTP_FORWARDED']))
   $ipaddress = $_SERVER['HTTP_FORWARDED'];
  else if(isset($_SERVER['REMOTE_ADDR']))
   $ipaddress = $_SERVER['REMOTE_ADDR'];
  else
   $ipaddress = 'UNKNOWN';
  return $ipaddress;
 }
}

$clasgetip = new datasource;
$ipaddress = $clasgetip->getIP();
echo $ipaddress;
?>

URL Validation

URL Validation
$url = 'http://example.com';
$validation = filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED);

if ( $validation ) $output = 'proper URL';
else $output = 'wrong URL';

echo $output;

Get URL and URL Parts in JavaScript

Get URL and URL Parts in JavaScript

http://tutorial101.blogspot.com/get-url-and-url-parts-in-javaScript

window.location.protocol = "http:"
window.location.host = "tutorial101.blogspot.com"
window.location.pathname = "get-url-and-url-parts-in-javaScript"

full URL path in JavaScript:
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;

get the get url parts
var pathArray = window.location.pathname.split( '/' );
var geturlparts = pathArray[2];
alert(geturlparts);

Friday, July 15, 2016

Magento Store Setup

Magento Store Setup

Magento - Setup Contact

Step (1):
Login to your Magento Admin Panel.
Step (2): Next go to CMS menu and click on the Pages option.
Step (3): Select the page which you would like to edit or else you can create the new page by clicking on Add New Page button.
Step (4):Click on the Content option on the left side of page which will open the WYSIWYG editor and click on the HTML option that display HTML Source Editor window and paste the below code.
<!- CONTACT FORM- >
{{block type="core/template" name="contactForm" form_action="/contacts/index/post" template="contacts/form.phtml"}}
<!- END OF CONTACT FORM- >
Step (5): Click on Save Page button and preview the created page to see the contact form.

Magento - Setup Categories

Step (1):
Login to your Magento Admin Panel.
Step (2): Go to the Catalog menu and click on the Manage Categories option.
Step (3): Next you need to fill the fields like Name of the category, Is Active status which is set to Yes/No and Description of the category and fill the other field's information.
Step (4): Click on Save Category button and your category is ready to have the products added to it.



Magento - Setup Products

Step (1):
Login to your Magento Admin Panel.
Step (2): Next go to Catalog and select the Manage Products option from dropdown menu.
Step (3): Under Manage Products section, you will see a list of products, if you have added to your Magento store. If you want to add new product, click on the Add Product button on the page.
Step (4): Next select the Attribute Set and Product Type. There is no need to change anything just go ahead and click on Continue button.
Step (5): Under General section, fill all the details such as Name of the product, Description, SKU (Stock Keeping Unit), Weight, Status, Visibility etc, and then click on the Save and Continue Edit button.
ex. name : Nike, Description : Nike, Short description : this is the first product in magento, SKU: 45698, Weight: 100.0000, Status: Enable, URL Key: nike, Visibility: catalog, search
Step (6): Enter the Price and Tax Class for your product and you can also add additional price using Group Price, Special Price and Tier Price options. Fill all the necessary fields and click on Save and Continue Edit button to proceed further.
Step (7): If you want to see list of the saved products, just go to the Catalog and click on the Manage Products option.
Step (8): You can customize the product information by clicking on the Inventory option on the left side. You can set quantity of the products, stock availability etc as shown in the screen. Then save the product by clicking on save button.

Magento - Setup InventoryInventory allows setting a product's stock quantity. For instance, you have a product with 100 units in stock. If you set the stock availability to "Out of Stock" then it will force the item to be out of stock.

Step (1): Login to your Magento Admin Panel.
Step (2): Go to System menu and click on the Configuration option.
Step (3): Click on the Inventory option under the Catalog section on the left side which contains two panels Stock Options and Product Stock Options as shown in the screen.
Step (4): The Stock Options panel contains some settings.
Step (5): Product Stock Options panel contains settings related to managing the stock of the products.

Magento - Setup Taxes

Step (1):
Login to your magento admin panel.
Step (2): Go to Sales menu > Tax and click on the Product Tax Classes option.
Step (3): Product class is a type of product that is being purchased. It includes two product tax classes:Taxable Goods and Shipping. To add new product tax class, click on Add New button.
Step (4): Next enter name for your product tax class in the Class Name box and click on the Save Class button in the upper right corner.

Set up Tax Rates

Step (1): Login to Magento Admin Panel.
Step (2): Go to Sales menu > Tax and click on the Manage Tax Zones & Rates option.
Step (3): Under Manage Tax Rates window, click on the Add New Tax Rate button.
Step (4): It provides several options such as:
Tax Identifier. This field defines the title of the newly created tax rate.
Country and State fields describes the country and state to which the specific tax applies. You can select country and state from the dropdown options given to you.
Zip/Post is range(set to Yes) field provides two fields Range From and Range To. These fields show the starting and ending of ZIP code range.
Rate Percent specify the percent of the tax rate.
After done with the settings, click on the Save Rate button.

Setup Tax Rules

Step (1): Login to your Magento Admin Panel.
Step (2): Go to Sales menu > Tax and click on the Manage Tax Rules option.
Step (3): To add new tax rule, click on the Add New Tax Rule button in the top right corner.
Step (4): It contains some settings such as:

Name field specifies name for tax rule,
Customer Tax Class field displays the list of customer tax classes that you have created
Product Tax Class field displays the list of product tax classes that you have created
Tax Rate field selects the tax rate which you want to apply to this rule
Priority field specifies when the tax should be applied to other tax rules
Sort Order field displays the order in which tax rules should be displayed.
After done with the settings, click on the Save Rule button.

Magento - Setup Shipping Rates

Step (1): Login to your Magento Admin Panel.
Step (2): Go to the System menu and click on the Configuration option.
Step (3): On the left side of the navigation, click on the Shipping Methods under Sales section.
Step (4): Next expand the Table Rates section, enable the table rates by selecting Yes from the dropdown menu for the Enabled field. It will turn off flat rate shipping and allow you to specify different rates based on chosen criteria.
Step (5): Fill all the required fields as shown in the screen and click on the Save Config button. It will save your current configuration into Magento.
Step (6): If you want to modify the fields of table rates section, go to Current Configuration Scope menu in the top left corner and select the Main Website option from dropdown menu.

Magento - Setup Payment Plans

Step (1): Login to your Magento Admin Panel.
Step (2): Go to System menu and click on the Configuration option.
Step (3):On the left side of the navigation, click on the Payment Methods under Sales section.
In some of the payment methods, there are some common settings as specified below:

Enabled: This option is used to enable or disable the payment method.
Title: It specifies title for the payment method whic will display during customer checkout and inside order emails and summaries.
New Order Status: It represents the status of an order after processing of payment. It will display either Pending or Processing choices.
Sort Order: During checkout mechanism, it displays the position of the payment method in the list of all the payment choices.
Payment Applicable From: It selects payment from all countries or some specific countries in which countries will offer the payment method you are configuring.
Minimum Order Total: It specifies minimum order amount available for the products order.
Maximum Order Total: It specifies maximum order amount available for the products order.

Step (4): Next under Merchant Location panel, set the merchant country from the dropdown menu.
Step (5): It provides following types of payment methods which adds PayPal as additional payment method to your checkout page.
Step (6): You can click on the Configure button to make PayPal settings. Fill the email field with email address which is associated with PayPal merchant account for accepting the payments and along with all other required fields.
Step (7): Basic and Advanced settings of PayPal payments.
Step (8): Under Basic Settings, enter Title for the payment method, Sort Order option used to sort payment methods in the checkout page, Payment Action section offers to select either Sale or Authorization or Order which defines how the payment will be processed in the PayPal payment system. Under Advanced Settings, select the Payment Applicable From option as All Allowed Countries and along with fill the all other required fields.
Step (9): Next panel is Saved CC which provides credit card payments on your website.
Credit Card Types: It allows for selecting credit card types for the payment processing.
Request Card Security Code: It ask for the credit card's security code which makes fraud little harder by setting it to Yes.
3D Secure Card Validation: It is an additional security functionality where customer needs to provide credit card password to complete the purchase order.
Step (10): Next is the Check/Money Order panel.
Set the values for Make Check Payable to and Send Check to options.
Step (11): The Zero Subtotal Checkout panel is a payment option that displays when order total is zero and not required to enter payment details for the customer.
Step (12): The Bank Transfer Payment panel contains one specific field called instructions which allows to enter bank account details that customer needs to transfer money to you.
Step (13): The Cash on Delivery Payment panel also contains one specific field called instructions which allows to list information related to the cash on delivery payment.
Step (14): The Purchase Order panel contains same options as mentioned above.
Step (15): Next, the Authorize.net Direct Post panel contains some other options such as setting the payment action, API login ID for authorization, setting the transaction key and merchant name, setting the test mode to Yes/No, Gateway URL of authorization, setting the accepting currency, email of customer and merchant, types of credit card used for purchase, enable or disable the credit card verification
Step (16): The Authorize.net panel works as similar to the Authorize.net Direct Post panel, but only difference is that it allows for enable or disable of the 3D secure card validation on the credit cards which makes fraud little harder by setting it to Yes.
Step (17): After done with the settings, click on the Save Config button in top right corner to save your payment methods.

Magento - Setup Payment Gateway

Step (1): Login to your Magento Admin Panel.
Step (2):Go to System menu and click on the Configuration option.
Step (3): Next you will see some list of options on the left side of the page. Scroll down and go to the Sales section and click on the Payment Methods option.
Step (4): Under the Payment Methods section, expand the PayPal Payment Gateways option. It provides two types of payment gateway methods; one is Payflow Pro (Includes Express Checkout) and Payflow Link (Includes Express Checkout). Click on the Configure button to enter details for Payflow Pro and Payflow Link options respectively.

Magento - Setup Payment Methods

Step (1):
Login to your Magento Admin Panel.
Step (2): Go to System menu and click on the Configuration option.
Step (3): Next you will see some list of options on the left side of the page. Scroll down and go to the Sales section and click on the Payment Methods option.
Step (4): Next under Merchant Location panel, set the merchant country from the dropdown menu.
Step (5): It provides following types of payment methods which adds PayPal as additional payment method to your checkout page.
Step (6): You can click on the Configure button to make PayPal settings. Fill the email field with email address which is associated with PayPal Merchant Account for accepting the payments and along with all other required fields.
Step (7): configure Basic and Advanced settings of PayPal payments.
Step (8): Under Basic Settings, enter Title for the payment method, Sort Order option used to sort payment methods in the checkout page, Payment Action section offers to select either Sale or Authorization or Order which defines how the payment will be processed in the PayPal payment system.
Step (9):Under Advanced Settings, select the Payment Applicable From option as All Allowed Countries, Debug Mode option as No, Enable SSL verification as Yes and Transfer Cart Line Items as Yes.
Step (10): After done with the settings, click on the Save Config button in top right corner to save your payment methods. Now you are ready to accept payments through your shopping cart.

Magento - Setup Currencies

Step (1): Login to your Magento Admin Panel   
Step (2): Go to System menu and click on the Configuration option.
Step (3): On the left side of the navigation, click on the Currency Setup option under General section.
Step (4): Expand the Currency Options panel, you will get some settings option.
Step (5): After selecting your currencies option, click on Save Config button in top right corner to save your settings.

Magento - Setup Check Out Options

Checkout options are used for enabling and disabling the one-page checkout

Step (1): Login to your Magento Admin Panel.
Step (2): Go to System menu and click on the Configuration option.
Step (3): Under Sales section on the left side, click on the Checkout option.
Step (4): Expand the Checkout Options panel which includes setting for one-page checkout with enable/disable option, you can also enable/disable guest checkout and last option from which you can enable or disable terms and conditions.
Step (5): Next panel is Shopping Cart which has options
Quote Lifetime (days) which determines lifetime of products in cart, after a customer puts items in the cart
After Adding a Product Redirect to Shopping Cart determines whether customers should be redirected to the shopping cart page after product is placed in the cart,
Grouped Product Image and Configurable Product Image options determine whether the parent image of product should be displayed on the cart and whether configurable product is added to the cart should be displayed on the shopping cart or not.
Step (6): The My Cart Link panel specifies whether the number of quantities in the cart should be shown or whether the number of different products should be shown using the Display Cart Summary field.
Step (7): The Shopping Cart Sidebar panel contains two options:
The Display Shopping Cart Sidebar option can hide or show the cart sidebar on the frontend
Maximum Display Recently Added Item(s) option specifies recently added items should be listed in the cart.
Step (8): The Payment Failed Emails panel has some settings such as:
Payment Failed Email Reciever option stores email address to which payment failed email should be sent
Payment Failed Email Sender option specify from which email address payment failed email should be sent
Payment Failed Template option specifies which template should be used to display message
Send Payment Failed Email Copy To option allows to send copies of emails to additional email addresses and last option
Send Payment Failed Email Copy Method selects either separate emails or blind carbon copies methods to send email copy.
Step (9): After done with all settings, click on the Save Config button to save your settings.




Magento - Setup Google Checkout

Google Checkout is online payment processing service provided by Google.

Step (1): Login to your Magento Admin Panel.
Step (2): Go to System menu and click on the Configuration option.
Step (3): On the left side of the navigation, click on the Google API under Sales section.
Step (4): Expand the Google Analytics panel which shows some settings such as:
Enable option should be set to Yes to activate payment method,
Type option provides two types: Google Analytics and Universal Analytics,
Account Number accepts your account number,
Enable IP anonymization option should be set to Yes.
Step (5): After done with the settings, click on the Save Config button in top right corner to save the changes that you have made.

Magento - Setup Store Live

shows how to setup the live store on your Magento website.

Step (1): Login to your Magento Admin Panel.
Step (2): Go to System menu and click on the Manage Stores option.
Step (3): Under Manage Stores section, you will get website names, store names and Store View Name columns. Click on the Create Store button to begin with setting up the Magento live store.
Step (4): The store information includes some options such as:
Website which allows selecting the website name which you created before
Name option specifies name of your second website name
Root Category option specifies the root category that will be used for store.
Step (5): After done with the settings, click on the Save Store button.

Sunday, July 10, 2016

Service Temporarily Unavailable Magento

Service Temporarily Unavailable Magento

Service Temporarily Unavailable
The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later.

Answers

Check if there is a file called maintenance.flag in your magento root. If so Delete it.

When Magento is performing certain tasks it temporarily creates this file. Magento checks for its existence and if it's there will send users to the page you described.

Saturday, July 9, 2016

Laravel - Controllers

Laravel - Controllers 

Open the command prompt

Execute the following command to create UserController

C:\xampp\htdocs\laraveldev>php artisan make:controller UserController 

After successful execution, you will receive the following output.
Controller created successfully.

You can see the created controller at app/Http/Controller/UserController.php with some basic coding already written for you and you can add your own coding based on your need.

Controller Middleware

Middleware can also be assigned to controller’s route or within your controller’s constructor. You can use the middleware method to assign middleware to the controller. The registered middleware can also be restricted to certain method of the controller.

Assigning Middleware to Route
Route::get('profile', [
   'middleware' => 'auth',
   'uses' => 'UserController@showProfile'
]);
Here we are assigning auth middleware to UserController in profile route.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class UserController extends Controller {
   public function __construct(){
      $this->middleware('auth');
   }
}
Here we are assigning auth middleware using the middleware method in the UserController’s constructor.

Example
Step 1 − Add the following lines to the app/Http/routes.php file and save it.
<?php
Route::get('/usercontroller/path',[
   'middleware' => 'First',
   'uses' => 'UserController@showPath'
]);
Step 2 − Create a middleware called FirstMiddleware by executing the following line.
php artisan make:middleware FirstMiddleware
Add the following code in the handle method of the newly created FirstMiddleware at app/Http/Middleware.
<?php
namespace App\Http\Middleware;
use Closure;

class FirstMiddleware {
   public function handle($request, Closure $next) {
      echo '
First Middleware';
      return $next($request);
   }
}
Step 4 − Create a middleware called SecondMiddleware by executing the following line.
php artisan make:middleware SecondMiddleware
Step 5 − Add the following code in the handle method of the newly created SecondMiddleware at app/Http/Middleware.
<?php
namespace App\Http\Middleware;
use Closure;

class SecondMiddleware {
   public function handle($request, Closure $next){
      echo '
Second Middleware';
      return $next($request);
   }
}
Step 6 − Create a controller called UserController by executing the following line.
php artisan make:controller UserController
Step 7 − After successful execution of the URL, you will receive the following output −
Controller created succesfully

Step 8 − Copy the following code to app/Http/UserController.php file.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class UserController extends Controller {
   public function __construct(){
      $this->middleware('Second');
   }
   public function showPath(Request $request){
      $uri = $request->path();
      echo '
URI: '.$uri; $url = $request->url(); echo '
'; echo 'URL: '.$url; $method = $request->method(); echo '
'; echo 'Method: '.$method; } }
Step 9 − Now launch the php’s internal web server by executing the following command, if you haven’t executed it yet.
php artisan serve
Step 10 − Visit the following URL. http://localhost:8000/usercontroller/path

Friday, July 8, 2016

Laravel - Middleware

Laravel - Middleware 

Define Middleware

Middleware acts as a middle man between request and response. It is a type of filtering mechanism. For example, Laravel includes a middleware that verifies whether user of the application is authenticated or not. If the user is authenticated, he will be redirected to the home page otherwise, he will be redirected to the login page.

Middleware can be created by executing the following command −

php artisan make:middleware

Replace the with the name of your middleware. The middleware that you create can be seen at app/Http/Middleware directory.

Let us now create AgeMiddleware. To create that, we need to execute the following command −

C:\xampp\htdocs\laraveldev>php artisan make:middleware AgeMiddleware

After successful execution of the command, you will receive the following output −
Middleware created succesfully.

AgeMiddlware will be created at app/Http/Middleware. The newly created file will have the following code already created for you.
<?php
namespace App\Http\Middleware;
use Closure;

class AgeMiddleware {
   public function handle($request, Closure $next) {
      return $next($request);
   }
}
Register Middleware
We need to register each and every middleware before using it. There are two types of Middleware in Laravel.

Global Middleware
Route Middleware
The Global Middleware will run on every HTTP request of the application, whereas the Route Middleware will be assigned to a specific route. The middleware can be registered at app/Http/Kernel.php. This file contains two properties $middleware and $routeMiddleware. $middleware property is used to register Global Middleware and $routeMiddleware property is used to register route specific middleware.

To register the global middleware, list the class at the end of $middleware property.
protected $middleware = [
   \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
   \App\Http\Middleware\EncryptCookies::class,
   \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
   \Illuminate\Session\Middleware\StartSession::class,
   \Illuminate\View\Middleware\ShareErrorsFromSession::class,
   \App\Http\Middleware\VerifyCsrfToken::class,
];
To register the route specific middleware, add the key and value to $routeMiddleware property.
protected $routeMiddleware = [
   'auth' => \App\Http\Middleware\Authenticate::class,
   'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
   'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
];
The following is the code for app/Http/Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel {
   protected $middleware = [
      \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
      \App\Http\Middleware\EncryptCookies::class,
      \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
      \Illuminate\Session\Middleware\StartSession::class,
      \Illuminate\View\Middleware\ShareErrorsFromSession::class,
      \App\Http\Middleware\VerifyCsrfToken::class,
   ];
  
   protected $routeMiddleware = [
      'auth' => \App\Http\Middleware\Authenticate::class,
      'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
      'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
      'Age' => \App\Http\Middlware\AgeMiddleware::class,
   ];
}
Middleware Parameters
We can also pass parameters with the Middleware. For example, if your application has different roles like user, admin, super admin etc. and you want to authenticate the action based on role, this can be achieved by passing parameters with middleware. The middleware that we create contains the following function and we can pass our custom argument after the $next argument.

Create RoleMiddleware by executing the following command −

C:\xampp\htdocs\laraveldev>php artisan make:middleware RoleMiddleware 
After successful execution, you will receive the following output
Middleware created succesfully.

Add the following code in the handle method of the newly created RoleMiddlewareat app/Http/Middleware/RoleMiddleware.php.
<?php
namespace App\Http\Middleware;
use Closure;

class RoleMiddleware {
   public function handle($request, Closure $next, $role) {
      echo "Role: ".$role;
      return $next($request);
   }
}
Register the RoleMiddleware in app\Http\Kernel.php file.
protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'Role' => \App\Http\Middleware\RoleMiddleware::class, //add RoleMiddleware 
    ];
Execute the following command to create TestController −

C:\xampp\htdocs\laraveldev>php artisan make:controller TestController 
After successful execution, you will receive the following output −
Controller created successfully

Copy the following code to app/Http/TestController.php file.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class TestController extends Controller {
   public function index(){
      echo "
Test Controller."; } }
Add the following line of code in app/Http/routes.php file.
Route::get('role',[
   'middleware' => 'Role:editor',
   'uses' => 'TestController@index',
]);
Visit the following URL to test the Middleware with parameters http://localhost:8000/role

Laravel 5 Ajax ToDo App Tutorial

Laravel 5 Ajax ToDo App Tutorial

Open the command prompt / terminal

browse to C:\xampp\htdocs

Run the following command to create a new project.

C:\xampp\htdocs>composer create-project laravel/laravel todoapplaravel

The above command create a directory todoapplaravel in the htdocs directory and install Laravel

After the above command has run successfully, run the following command to browse to the new project directory

C:\xampp\htdocs>cd todoapplaravel

Let’s now test the installation. We will work with the built in server.

Run the following command

C:\xampp\htdocs>php artisan serve

Open the following URL in your web browser

http://localhost:8000/

You will see the welcome page for Laravel

Open the command prompt / terminal and browse to the project root.

Run the following command to create a model and migration file at the same time.

C:\xampp\htdocs>php artisan make:model Task --migration

The above command creates a model task and its migration file
Open the model Task in /app/Task.php

Update the code to the following


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    protected $fillable = ['task', 'description','done'];
}
protected $fillable = ['task', 'description','done']; specifies the fields that can be mass assigned.
Open the migration file in /database/migrations/xxxx_xx_xx_xxxxxx_create_tasks_table.php

Update the code to the following
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use App\Task;

class CreateTasksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->increments('id');
            $table->string('task');
            $table->string('description');
            $table->boolean('done');
            $table->timestamps();
        });

        Task::create([
            'task' => 'Weekend hookup',
            'description' => 'Call Helga in the afternoon',
            'done' => false,
            ]);

        Task::create([
            'task' => 'Late night coding',
            'description' => 'Finishing coding POS API',
            'done' => false,
            ]);
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('tasks');
    }
}
Create Database: dblaravel

Open .envfile in the project root.

Set the configurations as shown below

DB_HOST=localhost
DB_DATABASE=dblarave
DB_USERNAME=root
DB_PASSWORD=xxx


Execute the following command to run the migrations

C:\xampp\htdocs>php artisan migrate

Check the database after running the migration files. You should be able to see the tasks table with two records that we seeded in the migration file.

Open /resources/views/welcome.blade.php

Replace the default HTML code with the following
<!DOCTYPE html>
<html lang="en-US">
<head>
    <title>Laravel Ajax ToDo App</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container-narrow">
        <h2>Laravel Ajax ToDo App</h2>
        <button id="btn-add" name="btn-add" class="btn btn-primary btn-xs">Add New Task</button>
        <div>
            <!-- Table-to-load-the-data Part -->
            <table class="table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Task</th>
                        <th>Description</th>
                        <th>Date Created</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="tasks-list" name="tasks-list">
                    @foreach ($tasks as $task)
                    <tr id="task{{$task->id}}">
                        <td>{{$task->id}}</td>
                        <td>{{$task->task}}</td>
                        <td>{{$task->description}}</td>
                        <td>{{$task->created_at}}</td>
                        <td>
                            <button class="btn btn-warning btn-xs btn-detail open-modal" value="{{$task->id}}">Edit</button>
                            <button class="btn btn-danger btn-xs btn-delete delete-task" value="{{$task->id}}">Delete</button>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
            <!-- End of Table-to-load-the-data Part -->
            <!-- Modal (Pop up when detail button clicked) -->
            <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                            <h4 class="modal-title" id="myModalLabel">Task Editor</h4>
                        </div>
                        <div class="modal-body">
                            <form id="frmTasks" name="frmTasks" class="form-horizontal" novalidate="">

                                <div class="form-group error">
                                    <label for="inputTask" class="col-sm-3 control-label">Task</label>
                                    <div class="col-sm-9">
                                        <input type="text" class="form-control has-error" id="task" name="task" placeholder="Task" value="">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="inputEmail3" class="col-sm-3 control-label">Description</label>
                                    <div class="col-sm-9">
                                        <input type="text" class="form-control" id="description" name="description" placeholder="Description" value="">
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-primary" id="btn-save" value="add">Save changes</button>
                            <input type="hidden" id="task_id" name="task_id" value="0">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <meta name="_token" content="{!! csrf_token() !!}" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="{{asset('js/script.js')}}"></script>
</body>
</html>
Next create the file script.js in the directory /public/js/script.js

Add the following code
$(document).ready(function(){

    var url = "tasks";

    //display modal form for task editing
    $('.open-modal').click(function(){
        var task_id = $(this).val();

        $.get(url + '/' + task_id, function (data) {
            //success data
            console.log(data);
            $('#task_id').val(data.id);
            $('#task').val(data.task);
            $('#description').val(data.description);
            $('#btn-save').val("update");

            $('#myModal').modal('show');
        }) 
    });

    //display modal form for creating new task
    $('#btn-add').click(function(){
        $('#btn-save').val("add");
        $('#frmTasks').trigger("reset");
        $('#myModal').modal('show');
    });

    //delete task and remove it from list
    $('.delete-task').click(function(){
  $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
            }
        })
        var task_id = $(this).val(); 
        $.ajax({

            type: "DELETE",
            url: url + '/' + task_id,
            success: function (data) {
                console.log(data);
                $("#task" + task_id).remove();
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    });

    //create new task / update existing task
    $("#btn-save").click(function (e) {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
            }
        })

        e.preventDefault(); 

        var formData = {
            task: $('#task').val(),
            description: $('#description').val(),
        }

        //used to determine the http verb to use [add=POST], [update=PUT]
        var state = $('#btn-save').val();

        var type = "POST"; //for creating new resource
        var task_id = $('#task_id').val();;
        var my_url = url;

        if (state == "update"){
            type = "PUT"; //for updating existing resource
            my_url += '/' + task_id;
        }

        console.log(formData);

        $.ajax({

            type: type,
            url: my_url,
            data: formData,
            dataType: 'json',
            success: function (data) {
                console.log(data);

                var task = '<tr id="task' + data.id + '"><td>' + data.id + '</td><td>' + data.task + '</td><td>' + data.description + '</td><td>' + data.created_at + '</td>';
                task += '<td><button class="btn btn-warning btn-xs btn-detail open-modal" value="' + data.id + '">Edit</button>';
                task += '<button class="btn btn-danger btn-xs btn-delete delete-task" value="' + data.id + '">Delete</button></td></tr>';

                if (state == "add"){ //if user added a new record
                    $('#tasks-list').append(task);
                }else{ //if user updated an existing record

                    $("#task" + task_id).replaceWith( task );
                }

                $('#frmTasks').trigger("reset");

                $('#myModal').modal('hide')
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    });
});
Open /app/Http/routes.php

Add the following routes
<?php
use App\Task;
use Illuminate\Http\Request;
Route::get('/', function () {
    $tasks = Task::all();

    return View::make('welcome')->with('tasks',$tasks);
});
Route::get('/tasks/{task_id?}',function($task_id){
    $task = Task::find($task_id);

    return Response::json($task);
});

Route::post('/tasks',function(Request $request){
    $task = Task::create($request->all());

    return Response::json($task);
});

Route::put('/tasks/{task_id?}',function(Request $request,$task_id){
    $task = Task::find($task_id);

    $task->task = $request->task;
    $task->description = $request->description;

    $task->save();

    return Response::json($task);
});

Route::delete('/tasks/{task_id?}',function($task_id){
    $task = Task::destroy($task_id);

    return Response::json($task);
});
Load the following URL in your web browser

http://localhost/todoapplaravel/public/

Related Post