article

Sunday, July 22, 2018

Jquery Notification Boxes

Jquery Notification Boxes

<!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>Jquery Notification Boxes</title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
   $('.notification').hover(function() {
     $(this).css('cursor','pointer');
    }, function() {
     $(this).css('cursor','auto');
   });
   $('.notification span').click(function() {
                $(this).parents('.notification').fadeOut(800);
            });
   
   $('.notification').click(function() {
                $(this).fadeOut(800);
            });
   
});
</script>
</head>

<body>
 <h1>Notification Boxes</h1>
    <div class="notification success">
        <span></span>
        <div class="text">
         <p><strong>Success!</strong> This is a success notification. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla varius eros et risus suscipit vehicula.</p>
        </div>
    </div>
 
    <div class="notification warning">
        <span></span>
        <div class="text">
         <p><strong>Warning!</strong> This is a warning notification. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla varius eros et risus suscipit vehicula.</p>
     </div>
    </div>
 
    <div class="notification tip">
        <span></span>
        <div class="text">
         <p><strong>Quick Tip!</strong> This is a quick tip notification. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla varius eros et risus suscipit vehicula.</p>
     </div>
    </div> 
 
 <div class="notification error">
        <span></span>
        <div class="text">
         <p><strong>Error!</strong> This is a error notification. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla varius eros et risus suscipit vehicula.</p>
        </div>
    </div>
    
     <div class="notification secure">
        <span></span>
        <div class="text">
         <p><strong>Secure Area!</strong> This is a secure area notification. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla varius eros et risus suscipit vehicula.</p>
     </div>        
    </div>
    
     <div class="notification info">
        <span></span>
        <div class="text">
         <p><strong>Info!</strong> This is a info notification. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla varius eros et risus suscipit vehicula.</p>
     </div>
    </div>
    
    <div class="notification message">
        <span></span>
        <div class="text">
         <p><strong>Message!</strong> This is a message notification. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla varius eros et risus suscipit vehicula.</p>
     </div>
    </div>
    
    <div class="notification download">
        <span></span>
        <div class="text">
         <p><strong>Download!</strong> This is a download notification. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla varius eros et risus suscipit vehicula.</p>
     </div>
    </div>
   
    <div class="notification purchase">
        <span></span>
        <div class="text">
         <p><strong>Purchase!</strong> This is a purchase notification. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla varius eros et risus suscipit vehicula.</p>
        </div>
    </div>
    
    <div class="notification print">
        <span></span>
        <div class="text">
         <p><strong>Print!</strong> This is a print notification. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla varius eros et risus suscipit vehicula.</p>
     </div>
    </div>
 
</body>
</html>
//css/style.css
body {
 margin: 70px;
 padding: 0;
 background: #e5e5e5;
}

#new {
 margin-bottom: 20px; 
}

h1 {
 font-family: Arial, Helvetica, sans-serif;
 font-size: 18px;
 font-style: normal;
 font-weight: bold;
 color: #323232;
 margin: 50px;
}
/*NOTIFICATION BOX - NO DESCRIPTION */
.notification {
 min-height: 70px;
 width: 580px;
 display: block;
 position: relative;
 /*Border Radius*/
 border-radius: 5px;
 -moz-border-radius: 5px;
 -webkit-border-radius: 5px; 
 /*Box Shadow*/
 -moz-box-shadow: 2px 2px 2px #cfcfcf;
 -webkit-box-shadow: 2px 2px 4px #cfcfcf;
 box-shadow: 2px 2px 2px #cfcfcf;
 margin-bottom: 30px;
}
.notification span {
 background: url(../images/close.png) no-repeat right top;
 display: block;
 width: 19px;
 height: 19px;
 position: absolute;
 top:-9px;
 right: -8px;
}
.notification .text {
 overflow: hidden;
}
.notification p {
 width: 500px; 
 font-family: Arial, Helvetica, sans-serif;
 color: #323232;
 font-size: 14px;
 line-height: 21px;
 text-align: justify;
 float: right;
 margin-right: 15px;
 /* TEXT SHADOW */
  text-shadow: 0px 0px 1px #f9f9f9;
}

/*SUCCESS BOX*/
.success {
 border-top: 1px solid #edf7d0;
 border-bottom: 1px solid #b7e789;
 /*Background Gradients*/
 background: #dff3a8;
 background: -moz-linear-gradient(top,#dff3a8,#c4fb92);
 background: -webkit-gradient(linear, left top, left bottom, from(#dff3a8), to(#c4fb92));
}
.success:before {
 content: url(../images/success.png);
 float: left;
 margin: 23px 15px 0px 15px;
}
.success strong {
 color: #61b316;
 margin-right: 15px;
}

/*WARNING BOX*/
.warning {
 border-top: 1px solid #fefbcd;
 border-bottom: 1px solid #e6e837;
 /*Background Gradients*/
 background: #feffb1;
 background: -moz-linear-gradient(top,#feffb1,#f0f17f);
 background: -webkit-gradient(linear, left top, left bottom, from(#feffb1), to(#f0f17f));
}
.warning:before {
 content: url(../images/warning.png);
 float: left;
 margin: 15px 15px 0px 25px;
}
.warning strong {
 color: #e5ac00;
 margin-right: 15px;
}

/*QUICK TIP BOX*/
.tip {
 border-top: 1px solid #fbe4ae;
 border-bottom: 1px solid #d9a87d;
 /*Background Gradients*/
 background: #f9d9a1;
 background: -moz-linear-gradient(top,#f9d9a1,#eabc7a);
 background: -webkit-gradient(linear, left top, left bottom, from(#f9d9a1), to(#eabc7a));
}
.tip:before {
 content: url(../images/tip.png);
 float: left;
 margin: 20px 15px 0px 15px;
}
.tip strong {
 color: #b26b17;
 margin-right: 15px;
}
/*ERROR BOX*/
.error {
 border-top: 1px solid #f7d0d0;
 border-bottom: 1px solid #c87676;
 /*Background Gradients*/
 background: #f3c7c7;
 background: -moz-linear-gradient(top,#f3c7c7,#eea2a2);
 background: -webkit-gradient(linear, left top, left bottom, from(#f3c7c7), to(#eea2a2));
}
.error:before {
 content: url(../images/error.png);
 float: left;
 margin: 20px 15px 0px 15px;
}
.error strong {
 color: #b31616;
 margin-right: 15px;
}
/*SECURE AREA BOX*/
.secure {
 border-top: 1px solid #efe0fe;
 border-bottom: 1px solid #d3bee9;
 /*Background Gradients*/
 background: #e5cefe;
 background: -moz-linear-gradient(top,#e5cefe,#e4bef9);
 background: -webkit-gradient(linear, left top, left bottom, from(#e5cefe), to(#e4bef9));
}
.secure:before {
 content: url(../images/secure.png);
 float: left;
 margin: 18px 15px 0px 15px;
}
.secure strong {
 color: #6417b2;
 margin-right: 15px;
}
/*INFO BOX*/
.info {
 border-top: 1px solid #f3fbff;
 border-bottom: 1px solid #bedae9;
 /*Background Gradients*/
 background: #e0f4ff;
 background: -moz-linear-gradient(top,#e0f4ff,#d4e6f0);
 background: -webkit-gradient(linear, left top, left bottom, from(#e0f4ff), to(#d4e6f0));
}
.info:before {
 content: url(../images/info.png);
 float: left;
 margin: 18px 15px 0px 21px;
}
.info strong {
 color: #177fb2;
 margin-right: 15px;
}
/*MESSAGE BOX*/
.message {
 border-top: 1px solid #f4f4f4;
 border-bottom: 1px solid #d7d7d7;
 
 /*Background Gradients*/
 background: #f0f0f0;
 background: -moz-linear-gradient(top,#f0f0f0,#e1e1e1);
 background: -webkit-gradient(linear, left top, left bottom, from(#f0f0f0), to(#e1e1e1));
}
.message:before {
 content: url(../images/message.png);
 float: left;
 margin: 25px 15px 0px 15px;
}
.message strong {
 color: #323232;
 margin-right: 15px;
}
/*DONWLOAD BOX*/
.download {
 border-top: 1px solid #ffffff;
 border-bottom: 1px solid #eeeeee;
 
 /*Background Gradients*/
 background: #f7f7f7;
 background: -moz-linear-gradient(top,#f7f7f7,#f0f0f0);
 background: -webkit-gradient(linear, left top, left bottom, from(#f7f7f7), to(#f0f0f0));
}

.download:before {
 content: url(../images/download.png);
 float: left;
 margin: 16px 15px 0px 18px;
}

.download strong {
 color: #037cda;
 margin-right: 15px;
}

/*PURCHASE BOX*/

.purchase {
 border-top: 1px solid #d1f7f8;
 border-bottom: 1px solid #8eabb1;
 
 /*Background Gradients*/
 background: #c4e4e4;
 background: -moz-linear-gradient(top,#c4e4e4,#97b8bf);
 background: -webkit-gradient(linear, left top, left bottom, from(#c4e4e4), to(#97b8bf));
}

.purchase:before {
 content: url(../images/purchase.png);
 float: left;
 margin: 19px 15px 0px 15px;
}

.purchase strong {
 color: #426065;
 margin-right: 15px;
}

/*PRINT BOX*/

.print {
 border-top: 1px solid #dde9f3;
 border-bottom: 1px solid #8fa6b2;
 
 /*Background Gradients*/
 background: #cfdde8;
 background: -moz-linear-gradient(top,#cfdde8,#9eb3bd);
 background: -webkit-gradient(linear, left top, left bottom, from(#cfdde8), to(#9eb3bd));
}

.print:before {
 content: url(../images/print.png);
 float: left;
 margin: 19px 15px 0px 15px;
}

.print strong {
 color: #3f4c6b;
 margin-right: 15px;
}

Download Source Code and Images

Ajax Image Upload using PHP and jQuery

Ajax Image Upload using PHP and jQuery
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ajax Image Upload using PHP and jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
 e.preventDefault();
 $("#message").empty();
 $('#loading').show();
 $.ajax({
  url: "ajax_php_file.php", // Url to which the request is send
  type: "POST",             // Type of request to be send, called as method
  data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
  contentType: false,       // The content type used when sending data to the server.
  cache: false,             // To unable request pages to be cached
  processData:false,        // To send DOMDocument or non processed data file it is set to false
  success: function(data)   // A function to be called if request succeeds
  {
   $('#loading').hide();
   $("#message").html(data);
  }
 });
}));

// Function to preview image after validation
$(function() {
 $("#file").change(function() {
  $("#message").empty(); // To remove the previous error message
  var file = this.files[0];
  var imagefile = file.type;
  var match= ["image/jpeg","image/png","image/jpg"];
  if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
  {
   $('#previewing').attr('src','img/noimage.png');
   $("#message").html("<p id='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
   return false;
  }
  else
  {
   var reader = new FileReader();
   reader.onload = imageIsLoaded;
   reader.readAsDataURL(this.files[0]);
  }
 });
});
function imageIsLoaded(e) {
 $("#file").css("color","green");
 $('#image_preview').css("display", "block");
 $('#previewing').attr('src', e.target.result);
 $('#previewing').attr('width', '250px');
 $('#previewing').attr('height', '230px');
};
});
</script>
</head>
<body>
<div class="main">
<h1>Ajax Image Upload</h1><br/>
<hr>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="img/noimage.png"/></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</div>
</form>
</div>
<h4 id='loading'><img id="previewing" src="img/loader.gif"/> Loading..</h4>
<div id="message"></div>
<style>
body {
font-family: 'Roboto Condensed', sans-serif;
}
h1
{
text-align: center;
background-color: #FEFFED;
height: 70px;
color: rgb(95, 89, 89);
margin: 0 0 -29px 0;
padding-top: 14px;
border-radius: 10px 10px 0 0;
font-size: 35px;
}
.main {
position: absolute;
top: 50px;
left: 20%;
width: 450px;
height:530px;
border: 2px solid gray;
border-radius: 10px;
}
.main label{
color: rgba(0, 0, 0, 0.71);
margin-left: 60px;
}
#image_preview{
width:100%;
height:auto;
text-align: center;
color: #C0C0C0;
overflow: auto;
}
#selectImage{
padding: 19px 21px 14px 15px;
position: absolute;
bottom: 0px;
width: 414px;
background-color: #FEFFED;
border-radius: 10px;
}
.submit{
font-size: 16px;
background: linear-gradient(#ffbc00 5%, #ffdd7f 100%);
border: 1px solid #e5a900;
color: #4E4D4B;
font-weight: bold;
cursor: pointer;
width: 300px;
border-radius: 5px;
padding: 10px 0;
outline: none;
margin-top: 20px;
margin-left: 15%;
}
.submit:hover{
background: linear-gradient(#ffdd7f 5%, #ffbc00 100%);
}
#file {
color: red;
padding: 5px;
border: 5px solid #8BF1B0;
background-color: #8BF1B0;
margin-top: 10px;
border-radius: 5px;
box-shadow: 0 0 15px #626F7E;
margin-left: 15%;
width: 72%;
}
#message{
position:absolute;
top:120px;
left:815px;
}
#success
{
color:green;
}
#invalid
{
color:red;
}
#line
{
margin-top: 274px;
}
#error
{
color:red;
}
#error_message
{
color:blue;
}
#loading
{
display:none;
position:absolute;
top:50px;
left:850px;
font-size:25px;
}
</style>
</body>
</html>
<?php
if(isset($_FILES["file"]["type"]))
{
 $validextensions = array("jpeg", "jpg", "png");
 $temporary = explode(".", $_FILES["file"]["name"]);
 $file_extension = end($temporary);
 if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
 ) && ($_FILES["file"]["size"] < 100000)//Approx. 100kb files can be uploaded.
 && in_array($file_extension, $validextensions)) {
  if ($_FILES["file"]["error"] > 0){
   echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
  }else{
   if (file_exists("upload/" . $_FILES["file"]["name"])) {
    echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
   }else{
    $sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
    $targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
    move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
    echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
    echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
    echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
    echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
   }
  }
 }else{
  echo "<span id='invalid'>***Invalid file Size or Type***<span>";
 }
}
?>

Thursday, July 19, 2018

Bootstrap Drop Down Sub Menu

Bootstrap Drop Down Sub Menu

A simple way to show navbar submenus on hover in Bootstrap 4
<!DOCTYPE html>
<html >
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Drop Down Sub Menu</title>
  <base target="_self">
  <meta name="description" content="A simple way to show navbar submenus on hover in Bootstrap 4" />
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
  <style type="text/css">.navbar-nav li:hover > ul.dropdown-menu {
    display: block;
}
.dropdown-submenu {
    position:relative;
}
.dropdown-submenu>.dropdown-menu {
    top:0;
    left:100%;
    margin-top:-6px;
}
/* rotate caret on hover */
.dropdown-menu > li > a:hover:after {
    text-decoration: underline;
    transform: rotate(-90deg);
} 
</style>
</head>
<body >
  <nav class="navbar navbar-expand-md navbar-light bg-light">
  <a class="navbar-brand pb-2" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNavDropdown">
    <ul class="navbar-nav">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown
        </a>
        <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
          <li><a class="dropdown-item" href="#">Action</a></li>
          <li><a class="dropdown-item" href="#">Another action</a></li>
          <li class="dropdown-submenu"><a class="dropdown-item dropdown-toggle" href="http://google.com">Google</a>
            <ul class="dropdown-menu">
              <li><a class="dropdown-item" href="#">Submenu</a></li>
              <li><a class="dropdown-item" href="#">Submenu0</a></li>
              <li class="dropdown-submenu"><a class="dropdown-item dropdown-toggle" href="#">Submenu 1</a>
                <ul class="dropdown-menu">
                  <li><a class="dropdown-item" href="#">Subsubmenu1</a></li>
                  <li><a class="dropdown-item" href="#">Subsubmenu1</a></li>
                </ul>
              </li>
              <li class="dropdown-submenu"><a class="dropdown-item dropdown-toggle" href="#">Submenu 2</a>
                <ul class="dropdown-menu">
                  <li><a class="dropdown-item" href="#">Subsubmenu2</a></li>
                  <li><a class="dropdown-item" href="#">Subsubmenu2</a></li>
                </ul>
              </li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </div>
</nav>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</body>
</html>

Using Stripe with PHP

Using Stripe with PHP

1. Setup the PHP SDK

We are going to use the Stripe PHP download on Github from Stripe.

2. HTML code index.html



<html>
<head>
<title>stripe php</title>
<style>
.StripeElement {
    background-color: white;
    padding: 8px 12px;
    border-radius: 4px;
    border: 1px solid transparent;
    box-shadow: 0 1px 3px 0 #e6ebf1;
    -webkit-transition: box-shadow 150ms ease;
    transition: box-shadow 150ms ease;
}
.StripeElement--focus {
    box-shadow: 0 1px 3px 0 #cfd7df;
}
.StripeElement--invalid {
    border-color: #fa755a;
}
.StripeElement--webkit-autofill {
    background-color: #fefde5 !important;
}
</style>
</head>
<body>
<form action="charge.php" method="post" id="payment-form">
  <div class="form-row">
    <label for="card-element">Credit or debit card</label>
    <div id="card-element">
      <!-- a Stripe Element will be inserted here. -->
    </div>
    <!-- Used to display form errors -->
    <div id="card-errors"></div>
  </div>
  <button>Submit Payment</button>
</form>
<!-- The needed JS files -->
<!-- JQUERY File -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Stripe JS -->
<script src="https://js.stripe.com/v3/"></script>
<!-- Your JS File -->
<script src="charge.js"></script>
</body>
</html>
3. charge.js file
// Stripe API Key
var stripe = Stripe('pk_test_Agw01Kg5ZpIuuzUwR8tGLUME'); //YOUR_STRIPE_PUBLISHABLE_KEY
var elements = stripe.elements();
// Custom Styling
var style = {
    base: {
        color: '#32325d',
        lineHeight: '24px',
        fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
        fontSmoothing: 'antialiased',
        fontSize: '16px',
        '::placeholder': {
            color: '#aab7c4'
        }
    },
    invalid: {
        color: '#fa755a',
        iconColor: '#fa755a'
    }
};
// Create an instance of the card Element
var card = elements.create('card', {style: style});
// Add an instance of the card Element into the `card-element` <div>
card.mount('#card-element');
// Handle real-time validation errors from the card Element.
card.addEventListener('change', function(event) {
    var displayError = document.getElementById('card-errors');
if (event.error) {
        displayError.textContent = event.error.message;
    } else {
        displayError.textContent = '';
    }
});
// Handle form submission
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
    event.preventDefault();
stripe.createToken(card).then(function(result) {
        if (result.error) {
            // Inform the user if there was an error
            var errorElement = document.getElementById('card-errors');
            errorElement.textContent = result.error.message;
        } else {
            stripeTokenHandler(result.token);
        }
    });
});
// Send Stripe Token to Server
function stripeTokenHandler(token) {
    // Insert the token ID into the form so it gets submitted to the server
    var form = document.getElementById('payment-form');
// Add Stripe Token to hidden input
    var hiddenInput = document.createElement('input');
    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'stripeToken');
    hiddenInput.setAttribute('value', token.id);
    form.appendChild(hiddenInput);
// Submit form
    form.submit();
}
4. charge.php file
<?php
require_once('/stripe-php-6.10.3/init.php');
\Stripe\Stripe::setApiKey('sk_test_mnT9JSEucLntq5fFi5hdNlce'); //YOUR_STRIPE_SECRET_KEY
// Get the token from the JS script
$token = $_POST['stripeToken'];
// This is a $20.00 charge in US Dollar.
//Charging a Customer
// Create a Customer
$name_first = "Batosai";
$name_last = "Ednalan";
$address = "New Cabalan Olongapo City";
$state = "Zambales";
$zip = "22005";
$country = "Philippines";
$phone = "09306408219";
$user_info = array("First Name" => $name_first, "Last Name" => $name_last, "Address" => $address, "State" => $state, "Zip Code" => $zip, "Country" => $country, "Phone" => $phone);
$customer = \Stripe\Customer::create(array(
    "email" => "rednalan23@gmail.com",
    "source" => $token,
 'metadata' => $user_info,
));
// Save the customer id in your own database!
// Charge the Customer instead of the card
$charge = \Stripe\Charge::create(array(
    "amount" => 2000,
 "description" => "Purchase off Caite watch",
    "currency" => "usd",
    "customer" => $customer->id,
 'metadata' => $user_info
));
print_r($charge);
// You can charge the customer later by using the customer id.

//Making a Subscription Charge
// Get the token from the JS script
//$token = $_POST['stripeToken'];
// Create a Customer
//$customer = \Stripe\Customer::create(array(
//    "email" => "paying.user@example.com",
//    "source" => $token,
//));
// or you can fetch customer id from the database too.
// Creates a subscription plan. This can also be done through the Stripe dashboard.
// You only need to create the plan once.
//$subscription = \Stripe\Plan::create(array(
//    "amount" => 2000,
//    "interval" => "month",
//    "name" => "Gold large",
//    "currency" => "cad",
//    "id" => "gold"
//));
// Subscribe the customer to the plan
//$subscription = \Stripe\Subscription::create(array(
//    "customer" => $customer->id,
//    "plan" => "gold"
//));
//print_r($subscription);
?>

Sunday, July 15, 2018

Create a JavaScript All Check Radio Buttons

Create a JavaScript All Check Radio Buttons





<html>
<head>
</head>
<body>
<script>
 function checkall(formname,checkname,thestate){
 var el_collection=eval("document.forms."+formname+"."+checkname)
 for (c=0;c<el_collection.length;c++)
 el_collection[c].checked=thestate
 }
</script>
<form name="test">
<input type="checkbox" name="v1"> Peter<br />
<input type="checkbox" name="v1"> Jane<br />
<input type="checkbox" name="v1"> George<br />
<input type="checkbox" name="v1"> Ednalan<br />
</form>
<a href="javascript:checkall('test','v1',true)">Check All</a><br />
<a href="javascript:checkall('test','v1',false)">Uncheck All</a>
</body>
</html>

Manage Table Add Edit Delete jquery ajax mysqli

Manage Table Add Edit Delete jquery ajax mysqli

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manage Table Add Edit Delete jquery ajax mysqli</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript">
function deleteuser(id){
 if (confirm('Are you sure want to delete?')) {
 $.post('manage_functions.php', {id: +id, action: 'delete_user'},
 function(response){
  $("#row_"+id).fadeOut("slow");
  $(".info_message").html(response);
  $(".info_message").animate({opacity : '0.9'}).fadeIn().delay(3000).fadeOut(1000);
   });
 }
}
function edituser(id){
 $.post('manage_functions.php', {id: +id, action: 'edit_user'},
    function(response){
      $(".edit_user").html(response);
 });
}
$(document).ready( function () {
  $('tr').hover( function () {
   $(this).toggleClass('tr-hover');
  });
  
  $('#Register').click(function () {
        var str = $('#register_form').serialize();
        $.ajax({
            type: "POST",
            url: "register.php",
            data: str,
            success: function (msg) {
                if (msg.length == "") {
     $('.registration_error').html("You Have Successfully Registered.")
     .fadeIn()
     .delay(3000)
     .slideUp();
     $('.registration_box_wrap,.registration_box').delay(1500).fadeOut();
                } else {
                      $('.registration_error').html(msg)
      .fadeIn()
      .delay(3000)
      .slideUp();
                }
            }
        });
  return false;
    });
 $('.register').click(function () {
        $('.registration_box_wrap').fadeIn(500);
        $('.registration_box').fadeIn(200);
  return false;
    });
 $('.cancel').click(function () {
        $('.registration_box_wrap').fadeOut(500);
        $('.registration_box').fadeOut(200);
  return false;
    });
});
</script>
</head>
<body>
<div class="main">
<a class='register' href="" id="button">Add New User</a> 
<div class="edit_user"></div>
<table width="587" border="0" align="center" cellpadding="5" cellspacing="0">
  <thead>
    <tr>
      <th width="35">ID</th>
      <th>User Name</th>
      <th>Email</th>
      <th>Registration Date</th>
      <th width="130">Actions</th>
    </tr>
  </thead>
  <tbody>
<?php
include("dbcon.php");
$sql = $conn->query("SELECT * from users");
while($row = $sql->fetch_assoc()) {
?>
    <tr id="row_<?php echo $row['id']; ?>">
       <td><?php echo $row['id']; ?></td>
       <td><?php echo $row['username']; ?></td>
       <td><?php echo $row['email']; ?></td> 
       <td><?php echo $row['reg_date']; ?></td>
       <td><a href="#" id="button" onclick="edituser(<?php echo $row['id']; ?>)">Edit</a>
   <a href="#" id="button"  onclick="deleteuser(<?php echo $row['id']; ?>)"> Delete</a>
       </td>
 </tr>
<?php }  ?>
  </tbody></table>
</div>
<div class="registration_box" style="display:none;">
 <h2>Register</h2>
  <div class="registration_error" style="display:none;"></div>
  <form id="register_form" name="form1" method="post" action="">
    Username<br />
    <input type="text" name="username" id="username" />
    <br />
    Password<br />
    <input type="password" name="password" id="textfield2" />
    <br />
    Email<br />
    <input type="text" name="email" id="email" />
    <br />
    <br />
    <input type="submit" name="Register" id="Register" value="Register" />
  or <a class="cancel" href="#">cancel</a>
  </form>
</div>

<div class="registration_box_wrap"  style="display:none;"></div>
<div class="info_message" style="display:none;"></div>
<style type="text/css">
table thead tr th {
 background-color: #FFF;
 border-bottom-width: 1px;
 border-bottom-style: solid;
 border-bottom-color: #CCC;
 padding: 4px;
 color: #000;
 border-right-width: 1px;
 border-right-style: solid;
 border-right-color: #CCC;
 font-size: 12px;
}
table {
 background-color: #FFF;
 color: #333;
 float: left;
 position: absolute;
 top: 100px;
 width: 652px;
}
td a {
 color: #333;
 display: block;
 float: left;
 padding: 4px;
 text-decoration: none;
 font-size: 18px;
}
td {
 border-right-width: 1px;
 border-right-style: solid;
 border-right-color: #CCC;
 padding: 5px;
 border-bottom-width: 1px;
 border-bottom-style: solid;
 border-bottom-color: #CCC;
}
.tr-hover {
 background-color: #eeeeee;
}
.main {
 width: 700px;
 margin-top: 50px;
 margin-right: auto;
 margin-left: auto;
}
body {
 background-color: #efefef;
 font-family: Arial, Helvetica, sans-serif;
 margin: 0px;
 padding: 0px;
 height: 100%;
 width: 100%;
}
#button {
 padding: 5px;
 display: block;
 float: left;
 background-color: #ffffff;
 border: 1px solid #CCC;
 color: #666;
 text-decoration: none;
 -webkit-border-radius: 10px;
 -moz-border-radius: 10px;
 border-radius: 10px;
 margin-top: 3px;
 margin-right: 3px;
 margin-bottom: 3px;
}
.registration_box {
 background-color: #EEE;
 height: auto;
 width: 250px;
 margin-top: 75px;
 margin-right: auto;
 margin-left: auto;
 border: 5px solid #CCC;
 z-index: 999;
 -webkit-border-radius: 5px;
 -moz-border-radius: 5px;
 border-radius: 5px;
 filter:alpha(opacity=100);
 -moz-opacity:1;
 -khtml-opacity: 1;
 opacity: 1;
 position: relative;
 padding: 20px;
 color: #333;
 font-family: Arial, Helvetica, sans-serif;
}
.registration_box_wrap {
 z-index: 888;
 height: 100%;
 width: 100%;
 background-color: #333;
 position: absolute;
 filter:alpha(opacity=50);
 -moz-opacity:0.5;
 -khtml-opacity: 0.5;
 opacity: 0.5;
 top: 0px;
}
.edit_user {
 text-align: center;
 padding: 10px;
}
.info_message {
 text-align: center;
 margin: 10px;
 background-color: #EEE;
 font-family: Arial, Helvetica, sans-serif;
 padding: 10px;
 font-size: 18px;
 float: left;
 position: absolute;
 left: 5px;
 top: 5px;
}
.registration_error {
 font-size: 14px;
 padding: 5px;
 border: thin solid #09F;
 margin: 5px;
 text-align: center;
}
</style>
</body>
</html>
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>
//register.php
<?php
include("dbcon.php");
$username = $_POST['username'];
$password = $_POST['password'];
$email    = $_POST['email'];
#Create a unique code which will be used to confirm user accounts.
$confirm_code = md5(rand(0,99999).rand(0,999999));
#Check if data is of required lenght.
if (strlen($username) < 3 || strlen($password) < 3 || strlen($email) < 3)
{
 die("All Fields Must Be At Least 3 Characters");
}
if (!preg_match('/^[a-zA-Z0-9&\'\.\-_\+]+\@[a-zA-Z0-9.-]+\.+[a-zA-Z]{2,6}$/', $email)) { 
 die("Email Address Not Vaild.");
}
#Check if username or email is already in use.
$password = md5($password);
$sqlc="SELECT * FROM users WHERE username = '$username' OR email = '$email'";
if ($rsdc=mysqli_query($conn,$sqlc)){
  $total=mysqli_num_rows($rsdc); 
  if ($total >= '1') {
   die("Username Or Email Already In Use"); 
  } 
}
$sql = "INSERT INTO users (username,password,email,confirm_code,reg_date)
VALUES ('$username', '$password', '$email', '$confirm_code', now())";
if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
//manage_functions.php
<?php
include("dbcon.php");
if ($_POST['action'] == 'delete_user') {
  $id = $_POST['id'];
  $sql = "DELETE FROM users WHERE id=$id";
 if ($conn->query($sql) === TRUE) {
  echo "Record deleted successfully";
 } else {
  echo "Error deleting record: " . $conn->error;
 } 
}else if ($_POST['action'] == 'edit_user') {
 $id = $_POST['id'];
   $sql = "SELECT * FROM users WHERE id = $id";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_array($result,MYSQLI_ASSOC);
 
?><script>
  $(document).ready(function(){
   $("#edit_user_button").click(function(){
     var str = $('#edit_user_form').serialize();
    $.ajax({
     type: "POST",
     url: "manage_functions.php",
     data: str,
     success: function (msg) { 
      $('.info_message').html(msg).fadeIn().delay(3000).fadeOut();
      $('.edit_user').hide(500);
     }
    });
    return false; 
   });
  });
  </script>
   <form id="edit_user_form" name="edit_user_form" method="post" action="">
  Uname: 
  <input name="username" type="text" id="username" value="<?php echo $row["username"]; ?>" /> 
  Email: 
  <input name="email" type="text" id="email" value="<?php echo $row["email"]; ?>" />
  <input name="id" type="hidden" id="id" value="<?php echo $row["id"]; ?>">
  <input name="action" type="hidden" id="id" value="save_user_info">
  <input type="button" name="button" id="edit_user_button" value="Edit User" />
   </form>
<?php
}else if ($_POST['action'] == 'save_user_info') {
   $id =   $_POST['id'];
   $username = $_POST['username'];
   $email =  $_POST['email'];
   $sql = "UPDATE users SET username = '$username', email= '$email' WHERE id = '$id' ";
  if ($conn->query($sql) === TRUE) {
   echo "User Successfully Edited";
  } else {
   echo "Error updating record: " . $conn->error;
  }
}
?>   

Saturday, July 14, 2018

Javascript Disable button Terms and Conditions

Javascript Disable button Terms and Conditions

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript Disable button Terms and Conditions</title>
<script language=javascript>
function apply()
{
 document.frm.sub.disabled=true;
 if(document.frm.chk.checked==true)
 {
   document.frm.sub.disabled=false;
 }
 if(document.frm.chk.checked==false)
 {
   document.frm.sub.enabled=false;
 }
}
</script>
</head>
<body>
<form name="frm">
<table style="border:solid green 1px">
<tr><td align=center>I agree Terms and Conditions <input type="checkbox" name="chk" onClick="apply()"></td></tr>
<tr><td align=center><input type="button" name="sub" value="submit" disabled></td></tr>
</table>
</form>
</body>
</html>

Saturday, July 7, 2018

jQuery - Popup

jQuery - Popup



 
<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Popup modal</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var popupStatus = 0;
//loading popup with jQuery magic!
function loadPopup(){
 //loads popup only if it is disabled
 if(popupStatus==0){
  $("#backgroundPopup").css({
   "opacity": "0.7"
  });
  $("#backgroundPopup").fadeIn("slow");
  $("#popupContact").fadeIn("slow");
  popupStatus = 1;
 }
}

//centering popup
function centerPopup(){
 //request data for centering
 var windowWidth = document.documentElement.clientWidth;
 var windowHeight = document.documentElement.clientHeight;
 var popupHeight = $("#popupContact").height();
 var popupWidth = $("#popupContact").width();
 //centering
 $("#popupContact").css({
  "position": "absolute",
  "top": windowHeight/2-popupHeight/2,
  "left": windowWidth/2-popupWidth/2
 });
}

//disabling popup with jQuery magic!
function disablePopup(){
 //disables popup only if it is enabled
 if(popupStatus==1){
  $("#backgroundPopup").fadeOut("slow");
  $("#popupContact").fadeOut("slow");
  popupStatus = 0;
 }
}

//CONTROLLING EVENTS IN jQuery
$(document).ready(function(){
 //LOADING POPUP
 //Click the button event!
 $("#button").click(function(){
  //centering with css
  centerPopup();
  //load popup
  loadPopup();
 });
  //CLOSING POPUP
 //Click the x event!
 $("#popupContactClose").click(function(){
  disablePopup();
 });
  //Click out event!
 $("#backgroundPopup").click(function(){
  disablePopup();
 });
  //Press Escape event!
 $(document).keypress(function(e){
  if(e.keyCode==27 && popupStatus==1){
   disablePopup();
  }
 });
});
</script>
</head>
<body>
<p><h1 align="center">jQuery Popup Modal</h1></p>
<div id="button"><input type="submit" value="PopUp!" /></div>

 <div id="popupContact">
  <a id="popupContactClose"><img src="../img/delete00.png"></a>
  <h1>Title!</h1>
  <p>Pellentesque viverra vulputate enim. Aliquam erat volutpat. Pellentesque tristique ante ut risus. Quisque dictum. Integer nisl </p>
  <p>risus, sagittis convallis, rutrum id, elementum congue, nibh. Suspendisse dictum porta lectus. Donec placerat odio vel elit. Nullam ante </p>
  <p>orci, pellentesque eget, tempus quis, ultrices in, est. Curabitur sit amet nulla.</p>
 </div>
 <div id="backgroundPopup"></div>
<style>
body{
 background:#fff none repeat scroll 0%;
 line-height:1;
 font-size: 12px;
 font-family:arial,sans-serif;
 margin:0pt;
 height:100%;
}
a{
 cursor: pointer;
 text-decoration:none;
}
#button{
 text-align:center;
 margin:100px;
}
#backgroundPopup{
 display:none;
 position:fixed;
 height:100%;
 width:100%;
 top:0;
 left:0;
 background:#000000;
 border:1px solid #cecece;
 z-index:1;
}
#popupContact{
 display:none;
 position:fixed;
 height:300px;
 width:400px;
 background:#FFFFFF;
 border:2px solid #cecece;
 z-index:2;
 padding:12px;
 font-size:13px;
}
#popupContact h1{
 text-align:left;
 color:#6FA5FD;
 font-size:22px;
 font-weight:700;
 border-bottom:1px dotted #D3D3D3;
 padding-bottom:2px;
 margin-bottom:20px;
}
#popupContactClose{
 font-size:14px;
 line-height:14px;
 right:6px;
 top:4px;
 position:absolute;
 color:#6fa5fd;
 font-weight:700;
 display:block;
}
</style>
</body>
</html>

Friday, July 6, 2018

Dyanamic Drop down combo box using Ajax Get jquery

Dyanamic Drop down combo box using Ajax Get jquery ajax php in array






<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dyanamic Drop down combo box using Ajax Get jquery in array</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css'>
<script type="text/javascript">
 jQuery(document).ready(function(){    
  jQuery("select[name='country']").change(function(){   
   var optionValue = jQuery("select[name='country']").val();  
   jQuery.ajax({
    type: "GET",
    url: "data.php",
    data: "country="+optionValue+"&status=1",
    beforeSend: function(){ jQuery("#ajaxLoader").show(); },
    complete: function(){ jQuery("#ajaxLoader").hide(); },
    success: function(response){
     jQuery("#cityAjax").html(response);
     jQuery("#cityAjax").show();
    }
   });    
  });
 });
</script>
</head>
<body> 
<h2>Dyanamic Drop down combo box using Ajax Get jquery ajax php in array</h2>
<h1>Countries:</h1>
<div class="box" style="position: absolute;top: 50%;left: 50%;">
<select name="country">
 <option value="">Please Select</option>
 <option value="1">Nepal</option>
 <option value="2">India</option>
 <option value="3">China</option>
 <option value="4">USA</option>
 <option value="5">UK</option>
 <option value="6">Philippines</option>
</select>
</div>
<div id="ajaxLoader" style="display:none"><img src="../img/loader.gif" alt="loading...">Loading...</div>
<div id="cityAjax" style="display:none"></div>
<style>
body {
  margin: 0;font-family: Arial;
  padding: 0;
  background-color: #004882;
}
h1 { 
  position: absolute;
  top: 35%; color:#fff;
  left:41%;
}
h2 { 
  color:#fff;padding:10px;text-align:center;
}
.box {
  transform: translate(-50%, -50%);
}
.box select {
  background-color: #0563af;
  color: white;
  padding: 12px;
  width: 250px;
  border: none;
  font-size: 20px;
  box-shadow: 0 5px 25px rgba(0, 0, 0, 0.2);
  -webkit-appearance: button;
  appearance: button;
  outline: none;
}
.box::before {
  content: "\f13a";
  font-family: FontAwesome;
  position: absolute;
  top: 0;
  right: 0;
  width: 20%;
  height: 100%;
  text-align: center;
  font-size: 28px;
  line-height: 45px;
  color: rgba(255, 255, 255, 0.5);
  background-color: rgba(255, 255, 255, 0.1);
  pointer-events: none;
}
.box:hover::before {
  color: rgba(255, 255, 255, 0.6);
  background-color: rgba(255, 255, 255, 0.2);
}
.box select option {
  padding: 30px;
}
#ajaxLoader { 
  position: absolute;
  top: 25%; color:#fff;
  left:41%;
}
.city { 
  position: absolute;
  top: 55%; color:#fff;
  left:41%;
}
</style>
</body>
</html>
//data.php
<?php
$country = $_GET['country'];
if(!$country) {
 return false;
}
$cities = array(
   1 => array('Kathmandu','Bhaktapur','Patan','Pokhara','Lumbini'),
   2 => array('Delhi','Mumbai','Kolkata','Bangalore','Hyderabad','Pune','Chennai','Jaipur','Goa'),
   3 => array('Beijing','Chengdu','Lhasa','Macau','Shanghai'),
   4 => array('Los Angeles','New York','Dallas','Boston','Seattle','Washington','Las Vegas'),
   5 => array('Birmingham','Bradford','Cambridge','Derby','Lincoln','Liverpool','Manchester'),
   6 => array('Olongapo City','Angeles City','Manila City','Davao City','Cebu City','Makati City','Pasay City')
  );
$currentCities = $cities[$country];
?>
<h1 class="city">City:</h1>
<div class="box" style="position: absolute;top: 70%;left: 50%;">
<select name="city">
 <option value="">Please Select</option>
  <?php
 foreach($currentCities as $city) {
  ?>
  <option value="<?php echo $city; ?>"><?php echo $city; ?></option>
  <?php 
 }
 ?>
</select> 
</div>

Thursday, July 5, 2018

Table Edit using jquery ajax php

Table Edit using jquery ajax php





<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table Edit using jquery ajax php mysqli</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<style>
body
{
font-family:Arial, Helvetica, sans-serif;
font-size:16px;
}
.head
{
background-color:#333;
color:#FFFFFF
}
.edit_tr:hover
{
background:url(img/edit.png) right no-repeat #80C8E5;
cursor:pointer;
}
.editbox
{
display:none
}
.editbox
{
font-size:16px;
width:270px;
background-color:#ffffcc;
border:solid 1px #000;
padding:4px;
}
td
{
padding:10px;
}
th
{
font-weight:bold;
text-align:left;
padding:4px;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
 $(".edit_tr").click(function() {
   var ID=$(this).attr('id');
   $("#first_"+ID).hide();
   $("#first_input_"+ID).show();
  }).change(function(){
   var ID=$(this).attr('id');
   var first=$("#first_input_"+ID).val();
   var dataString = 'id='+ ID +'&name='+first;
   $("#first_"+ID).html('<img src="img/loader.gif" />');
   if(first.length>0){
     $.ajax({
   type: "POST",
   url: "ajax.php",
   data: dataString,
   cache: false,
   success: function(html)
   {
    $("#first_"+ID).html(first);
   }
     });
   }else{
     alert('Enter something.');
   }
  });
  
  $(".editbox").mouseup(function() {
   return false
  });
   $(document).mouseup(function() {
   $(".editbox").hide();
   $(".text").show();
  });
});
</script>
</head>
<body>
<div style="margin:0 auto; width:350px; padding:10px; background-color:#fff;">
<table width="100%" border="0">
 <tr class="head">
 <th>PHP Frameworks</th>
 </tr>
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
 $i=1;
 $sql = $conn->query("SELECT * from topphpframework");
 while($row = $sql->fetch_assoc()) {
  $id=$row['id'];
  $name=$row['name'];
  if($i%2) {
?>
  <tr id="<?php echo $id; ?>" class="edit_tr">
  <?php } else { ?>
  <tr id="<?php echo $id; ?>" bgcolor="#f2f2f2" class="edit_tr">
  <?php } ?>
   <td width="50%" class="edit_td">
   <span id="first_<?php echo $id; ?>" class="text"><?php echo $name; ?></span>
   <input type="text" name="name" value="<?php echo $name; ?>" class="editbox" id="first_input_<?php echo $id; ?>" />
   </td>
  </tr>
 <?php 
  $i++;
 } ?>
</table>
</div>
</body>
</html>
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
if($_POST['id'])
{
 $id=mysql_escape_String($_POST['id']);
 $name=mysql_escape_String($_POST['name']);
 $sql = "UPDATE topphpframework SET name = '$name' WHERE id = '$id' ";
 if ($conn->query($sql) === TRUE) {
  echo "Record updated successfully";
 } else {
  echo "Error updating record: " . $conn->error;
 }
}
?>

Check Availability username with jquery-ajax, php mysql

Check Availability username with jquery-ajax, php mysql





<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Check Availability username with jquery-ajax, php mysql</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<style type="text/css">
body
{
font-family:Arial, Helvetica, sans-serif
}
#status
{
font-size:11px;
margin-left:10px;
}
.green
{
background-color:#CEFFCE;
}
.red
{
background-color:#FFD9D9;
}
input
{
font-size:16px;
width:190px;
height:25px;
border:solid 1px #333333;
padding:4px;
}
</style>
<SCRIPT type="text/javascript">
$(document).ready(function()
{
 $("#username").change(function()
 {
  var username = $("#username").val(); 
  var msgbox = $("#status");
  if(username.length > 3) {
   $("#status").html('<img src="img/loader.gif" align="absmiddle"> <b>Checking...</b>');
   $.ajax({
   type: "POST",
   url: "check.php",
   data: "username="+ username,
   success: function(msg){ 
    if(msg == 'OK')
    { 
      $("#username").removeClass("red");
      $("#username").addClass("green");
     msgbox.html('<img src="img/yes.png" align="absmiddle"> <font color="Green"> Available </font>  ');
    }
    else
    {
       $("#username").removeClass("green");
     $("#username").addClass("red");
     msgbox.html(msg);
    }
   }
   });
  }else{
   $("#username").addClass("red");
   $("#status").html('<font color="#cc0000">Enter valid User Name</font>');
  }
  return false;
 });
});
</SCRIPT>
</head>
<body>
<div>
<input type="text" name="username" id="username" /><span id="status"></span>
</div>
</body>
</html>
//check.php
<?php
$host = "localhost";
$username_ = "root";
$password = "";
$databasename = "testingdb";
$connect = mysql_connect($host, $username_, $password) or die("Opps some thing went wrong");
mysql_select_db($databasename, $connect) or die("Opps some thing went wrong");
if(isSet($_POST['username']))
{
 $username = $_POST['username'];
 $username = mysql_real_escape_string($username);
 $sql_check = mysql_query("SELECT * FROM users WHERE username='$username'") or die('Invalid query: ' . mysql_error());;
 if(mysql_num_rows($sql_check))
 {
  echo '<font color="#cc0000"><STRONG>'.$username.'</STRONG> is already in use.</font>';
 }
 else
 {
  echo 'OK';
 }
}
?>

Sunday, July 1, 2018

Create Contact Form (CSS, JQuery & AJAX)

Create Contact Form (CSS, JQuery & AJAX)

Demonstration how to create a css form contact form and jquery ajax









<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Contact Form (CSS, JQuery & AJAX)</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript">                                     
$(document).ready(function(){
 $("form").submit(function(){ 
  var str = $("form").serialize();
  $.ajax({
  type: "POST",
  url: "contacts.php",
  data: str,
  success: function(msg){ 
    if(msg == 'OK')
    {
     $("#note").html('<div class="notification_ok">Your message has been sent. Thank you!</div>');
     $("#fields").hide();
    }else{
     $("#note").html(msg);
    }
   }
   });
  return false;
 });
});
</script>
</head>
<body>
<div id="main">
<h2>Contact Form (JQuery & AJAX)</h2>
<div id="note"></div>
<form action="">  
   <fieldset><legend>Contact form</legend>
    <p>
     <label for="name">Name</label>
     <input type="text" name="name" size="30" />
    </p>
 <p>
     <label for="email">Email</label>
     <input type="text" name="email" size="30" />
    </p>
    <label for="subject">Subject</label>
     <input type="text" name="subject" size="30" />
    </p>             
    <p>
     <label for="message">Message</label>
     <textarea name="message" rows="10" cols="30"></textarea>
    </p>       
    <p class="submit">
     <button type="submit" name="submit">Send Message</button>
    </p>    
 </fieldset>
</form> 
</div>
<style>
body{
 background:#fbf9ee;
    font:80% Trebuchet MS, Arial, Helvetica, Sans-Serif;
 color:#333;
}
.notification_ok
{
border: 1px #567397 solid;
height: auto;padding:10px;
width: 90%
padding: 8px;
background: #f5f9fd;
text-align: center;
-moz-border-radius: 5px;
}
.notification_error
{
border: 1px solid #A25965;
height: auto;padding:10px;
width: 90%;
padding: 4px;
background: #F8F0F1;
text-align: left;
-moz-border-radius: 5px;
}
#main{
 float:left;
 display:inline;
 width:610px;
 margin-left:2px;
 padding-bottom:1em;
 }                
 form{
  margin:1.5em 0;
  padding-top:.5em;
  }
 fieldset{
  margin:0;
  padding:0;
  border:none;
  }  
 legend{
  display:none;
  }  
 label{
  float:left;
  width:120px;
  }
 input, textarea{
  width:250px;
  border:1px solid #dbd3b6;
  padding:5px;
  }  
 textarea{
  height:120px;
  overflow:auto;
  }     
 form p{
  clear:both; 
  margin:0;
  padding:8px 0;
  }
 button{
  border:none;
  padding:5px 15px;
  margin:0;
  float:left;
  background:#2c728a;
  color:#fff;
  font-weight:bold;
  font-size:15px;
  cursor:pointer;
  margin-left:120px;
  }         
</style>
</body>
</html>
<?php
//contacts.php
function ValidateEmail($email)
{
 $regex = "([a-z0-9_\.\-]+)". # name
 "@". # at
 "([a-z0-9\.\-]+){2,255}". # domain & possibly subdomains
 "\.". # period
 "([a-z]+){2,10}"; # domain extension 
 $eregi = eregi_replace($regex, '', $email);
 return empty($eregi) ? true : false;
}
$post = (!empty($_POST)) ? true : false;
if($post)
{
 $name = stripslashes($_POST['name']);
 $email = trim($_POST['email']);
 $subject = stripslashes($_POST['subject']);
  $message = htmlspecialchars($_POST['message']);
  $error = '';
  // Check name
  if(!$name)
  {
   $error .= 'Please enter your name.<br />';
  }
   // Check email
  if(!$email)
  {
   $error .= 'Please enter an e-mail address.<br />';
  }
   if($email && !ValidateEmail($email))
  {
   $error .= 'Please enter a valid e-mail address.<br />';
  }
   // Check message (length)
  if(!$message || strlen($message) < 15)
  {
   $error .= "Please enter your message. It should have at least 15 characters.<br />";
  }
   if(!$error){
    echo 'OK';
  } else{
   echo '<div class="notification_error">'.$error.'</div>';
  }
} 
?>

Friday, June 29, 2018

Create Contact Us Form Validate fields using javascript

http://farm6.static.flickr.com/5078/5884241163_8224f896c4_z.jpg
Create Contact Us Form Validate fields using javascript











<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Contact Us Form Validate fields using javascript</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
<style>
#main{
float:left;
display:inline;
width:470px;
margin-left:55px;
}
form{
 margin:1em 0;
 }
fieldset{
 border:none;
 margin:0;
 background:#f1f1f1;
 border:5px solid #e7e7e7;
 padding:1em 15px; 
 } 
legend{
 display:none;
 } 
label{
 float:left;
 clear:both;
 width:120px;
 margin-right:10px;
 margin-top:5px;
 text-align:right;
 }
input, textarea{
 width:250px;
 border:1px solid #ccc;
 padding:5px;
 margin:5px 0;
 } 
textarea{
 height:80px;
 overflow:auto;
 }    
form p{
 clear:both;
 margin:0;
 }
form h3{
 margin:1em 0 .5em 0;
 font-size:25px;
 }          
.submit{
 text-align:right; 
 }
span.error{
 display:block;
 color:#a50000;
 font-weight:bold;
 margin-left:130px;
 }
</style>
<script>
this.form = function(){
 this.validate = function(name, email, message){
  $("span.error").remove();
  var valid = true;
  //name
  if(name == "") {
   error($("#name"),"Please tell us your name.")
   valid = false;
  };
  //email
  if(!checkEmail(email)) {
   error($("#email"),"We need a valid email address.")
   valid = false;
  }; 
  //messgae
  if(message == "") {
   error($("#message"),"Please write a message.")
   valid = false;
  };   
  return valid;
 };
 this.checkEmail = function(str){
  var regEx = /^[^@]+@[^@]+.[a-z]{2,}$/;
  return (str.search(regEx) != -1);
 };
 this.error = function(obj,text){
 var parent = $(obj).parent();
 parent.append("<span class=\"error\">"+ text +"</span>");
 $("span.error",parent).hide().show("fast");
 };
 $("#contactForm button").click(function(){              
 var name = $("#name").val();
 var email = $("#email").val();  
 var message = $("#message").val();    
 if(validate(name, email, message)) return true;
 return false;
 });
};
this.init = function() {
 form();
};
$(document).ready(function(){
 init();
});
</script>
<div id="main">
 <h2>Contact us</h2>
 <p>Nunc volutpat nisi nec leo. Fusce accumsan, mi ac posuere rhoncus,
 arcu orci tristique leo, vitae consequat.</p>
 <form id="contactForm" action="send.php" method="post">
 <fieldset><legend>Contact form</legend>
   <p>
    <label for="name">Name</label>
    <input type="text" name="name" id="name" size="30" />
   </p>
   <p>
    <label for="email">Email</label>
    <input type="text" name="email" id="email" size="30" />
   </p>            
   <p>
    <label for="message">Message</label>
    <textarea name="message" id="message" rows="10" cols="30"></textarea>
   </p>  
  <p class="submit">
   <button type="submit">Send</button>
  </p>
 </fieldset>  
 </form>
</div> 
</body>
</html>
//sent.php
<p><h1>Email Succesfully sent</h1></p>

Monday, June 18, 2018

Django - URL Mapping

Django - URL Mapping 

Django has his own way for URL mapping and it's done by editing your project url.py file (myproject/url.py). The url.py file looks like −
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
   #Examples
   #url(r'^$', 'myproject.view.home', name = 'home'),
   #url(r'^blog/', include('blog.urls')),

   url(r'^admin', include(admin.site.urls)),
)

When a user makes a request for a page on your web app, Django controller takes over to look for the corresponding view via the url.py file, and then return the HTML response or a 404 not found error, if not found. In url.py, the most important thing is the "urlpatterns" tuple. It’s where you define the mapping between URLs and views. A mapping is a tuple in URL patterns like −

from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
   #Examples
   #url(r'^$', 'myproject.view.home', name = 'home'),
   #url(r'^blog/', include('blog.urls')),

   url(r'^admin', include(admin.site.urls)),
   url(r'^hello/', 'myapp.views.hello', name = 'hello'),
)

Sending Parameters to Views

how to send parameters to views. A classic sample is the article example (you want to access an article via "/articles/article_id").

"myapp/view.py"

from django.shortcuts import render
from django.http import HttpResponse

def hello(request):
   return render(request, "hello.html", {})

def viewArticle(request, articleId):
   text = "Displaying article Number : %s"%articleId
   return HttpResponse(text)

We want to map it in myapp/url.py so we can access it via "/myapp/article/articleId", we need the following in "myapp/url.py" −

from django.conf.urls import patterns, include, url

urlpatterns = patterns('myapp.views',
   url(r'^hello/', 'hello', name = 'hello'),
   url(r'^morning/', 'morning', name = 'morning'),
   url(r'^article/(\d+)/', 'viewArticle', name = 'article'),)

http://127.0.0.1:8000/myapp/article/42/

output : Displaying article number : 42

Suppose we want the list of articles of a month of a year, let's add a viewArticles view. Our view.py becomes −

from django.shortcuts import render
from django.http import HttpResponse

def hello(request):
   return render(request, "hello.html", {})

def viewArticle(request, articleId):
   text = "Displaying article Number : %s"%articleId
   return HttpResponse(text)

def viewArticle(request, month, year):
   text = "Displaying articles of : %s/%s"%(year, month)
   return HttpResponse(text)

The corresponding url.py file will look like −

 
from django.conf.urls import patterns, include, url

urlpatterns = patterns('myapp.views',
   url(r'^hello/', 'hello', name = 'hello'),
   url(r'^morning/', 'morning', name = 'morning'),
   url(r'^article/(\d+)/', 'viewArticle', name = 'article'),
   url(r'^articles/(\d{2})/(\d{4})', 'viewArticles', name = 'articles'),)

http://127.0.0.1:8000/myapp/articles/12/2016/

Displaying articles of : 2016/12

To avoid that, it is possible to link a URL parameter to the view parameter. For that, our url.py will become −

 
from django.conf.urls import patterns, include, url

urlpatterns = patterns('myapp.views',
   url(r'^hello/', 'hello', name = 'hello'),
   url(r'^morning/', 'morning', name = 'morning'),
   url(r'^article/(\d+)/', 'viewArticle', name = 'article'),
   url(r'^articles/(?P\d{2})/(?P\d{4})', 'viewArticles', name = 'articles'),)

Friday, June 8, 2018

Simple PHP MySQLi Login Form

Simple PHP MySQLi Login Form
//login.php
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=ISO-8859-1'>
<title>Simple PHP MySQLi Login Form</title>
</head>
<body>
 <form method='post' action='validate_login.php' >
  <table border='1' >
   <tr>
    <td><label for='username'>User Name</label></td>
    <td><input type='text' name='username' id='username'></td>
   </tr>
   <tr>
    <td><label for='users_pass'>Password</label></td>
    <td><input name='users_pass' type='password' id='users_pass'></input></td>
   </tr>
   <tr>
    <td><input type='submit' value='Submit'/>
    <td><input type='reset' value='Reset'/>
   </tr>
  </table>
 </form>
</body>
</html>
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
$username = $_POST['username'];
$pass = $_POST['users_pass'];
$sqlc="SELECT * FROM users WHERE username = '$username' OR password = '$pass'";
if ($rsdc=mysqli_query($conn,$sqlc)){
  $total=mysqli_num_rows($rsdc); 
  if ($total == '1') {
   echo'<h1>You are a validated user.</h1>';
  }else{
 echo'<h1>Sorry, your credentials are not valid, Please try again.</h1>'; 
  } 
}
?>

Sunday, June 3, 2018

Dynamic Loading of ComboBox using jQuery and Ajax in PHP

Dynamic Loading of ComboBox using jQuery and Ajax in PHP

Download

 
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Loading of ComboBox using jQuery and Ajax PHP and Mysqli</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
 $('#loader').hide();
 $('#show_heading').hide();
 $('#search_category_id').change(function(){
    $('#show_sub_categories').fadeOut();
    $('#loader').show();
    $.post("get_child_categories.php", {
     parent_id: $('#search_category_id').val(),
    }, function(response){ 
     setTimeout("finishAjax('show_sub_categories', '"+escape(response)+"')", 400);
    });
    return false;
  });
}); 
function finishAjax(id, response){ 
  $('#loader').hide();
  $('#show_heading').show();
  $('#'+id).html(unescape(response));
  $('#'+id).fadeIn();
}
</script>
 
<style>
.both h4{ font-family:Arial, Helvetica, sans-serif; margin:0px; font-size:14px;}
#search_category_id{ padding:3px; width:200px;}
#sub_category_id{ padding:3px; width:200px;}
.both{ float:left; margin:0 15px 0 0; padding:0px;}
</style>
</head>
<body>
<?php include('dbcon.php');?>
<div style="padding-left:30px;">
<form action="#" name="form" id="form" method="post" onsubmit="return alert_id();" enctype="multipart/form-data">
 <div class="both">
  <h4>Select Category</h4>
  <select name="search_category"  id="search_category_id">
  <option value="" selected="selected"></option>
  <?php
  $sql="SELECT * from ajax_category";
  if ($result=mysqli_query($conn,$sql))
  {
   while ($row=mysqli_fetch_row($result)) {
  $id =  $row[0];
  $category =  $row[2];
  echo "<option value='$id'>$category</option>";
   }
   mysqli_free_result($result);
  }
  mysqli_close($conn);
  ?>
  </select>  
 </div>
  <div class="both">
  <h4 id="show_heading">Select Sub Category</h4>
  <div id="show_sub_categories" align="center">
   <img src="img/loader.gif" style="margin-top:8px; float:left" id="loader" alt="" />
  </div>
  </div>
</form>
</div>
</body>
</html>
//get_child_categories.php
<?php
include('dbcon.php');
if($_REQUEST)
{
 $id  = $_REQUEST['parent_id'];
 $query="SELECT * from ajax_categories2 where pid = ".$id;
 if ($result=mysqli_query($conn,$query)){
?>
 <select name="sub_category"  id="sub_category_id">
 <option value="" selected="selected"></option>
 <?php
 while ($row=mysqli_fetch_row($result)) { ?>
  <option value="<?php echo $row[2];?>  ID=<?php echo $row[0];?>"><?php echo $row[2];?></option>
 <?php } ?>
 </select> 
 <?php }
}
?>
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Delete confirmation Records jquery ajax php

Delete confirmation Records jquery ajax php

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Delete confirmation Records jquery ajax</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".delbutton").click(function(){
 //Save the link in a variable called element
 var element = $(this);
 //Find the id of the link that was clicked
 var del_id = element.attr("id");
 //Built a url to send
 var info = 'id=' + del_id;
 if(confirm("Sure you want to delete this records? There is NO undo!")) {
    $.ajax({
     type: "GET",
     url: "deleterec.php",
     data: info,
     success: function(data){ 
     alert(data);
     }
  });
    $(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
    .animate({ opacity: "hide" }, "slow");
  }
 return false;
});
});
</script>
</head>
<body>
<table id="box-table-a" summary="Employee Pay Sheet">
 <thead>
  <tr>
   <th scope="col" width="60">Photo</th>
   <th scope="col">Employee</th>
   <th scope="col">Bonus</th>
   <th scope="col" width="40">Action</th>
  </tr>
 </thead>
 <tbody>
<?php 
include("dbcon.php");
$query = $conn->query("SELECT * FROM updates order by msg_id desc");
while ($result = $query ->fetch_object()) {
 $fullname=stripslashes($result->fullname); 
?>
  <tr class="record">
   <td><img src="img/<?php echo $result->photo; ?>" width="50" height="50"/></td>
   <td><?php echo $fullname; ?></td>
   <td>$50</td>
   <td align="center"><a href="#" id="<?php echo $result->msg_id; ?>" class="delbutton"><img src="img/delete.png" style="background:#FFFFFF;width:15px;"/></a></td>
  </tr>
<?php } ?>  
 </tbody>
</table>
<style>
#box-table-a {
    font-family: lucida sans unicode,lucida grande,Sans-Serif;
    font-size: 12px;
    width: 480px;
    text-align: left;
    border-collapse: collapse;
    margin: 20px;
}
.tr, tr {
    border-bottom: 1px solid #ddd;
}
#box-table-a th {
    font-size: 13px;
    font-weight: 400;
    background: #b9c9fe;
    border-top: 4px solid #aabcfe;
    border-bottom: 1px solid #fff;
    color: #039;
    padding: 8px;
}
#box-table-a td {
    background: #e8edff;
    border-bottom: 1px solid #fff;
    color: #669;
    border-top: 1px solid transparent;
    padding: 8px;
}
#box-table-a tr:hover td{background:#d0dafd;color:#339}
</style> 
</body>
</html>
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>
//deleterec.php
<?php
include("dbcon.php");
if($_GET['id'])
{
 $id=$_GET['id'];
 $sql = "delete from updates where msg_id='$id'";
 if ($conn->query($sql) === TRUE) {
  echo "Record deleted successfully";
 } else {
  echo "Error deleting record: " . $conn->error;
 }
}
?>

Saturday, June 2, 2018

Jquery Animated menu hover

Jquery Animated menu hover

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Jquery Animated menu hover</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 $(".menu2 a").append("<em></em>");
 $(".menu2 a").hover(function() {
 $(this).find("em").animate({opacity: "show", top: "-75"}, "slow");
 var hoverText = $(this).attr("title");
 $(this).find("em").text(hoverText);
 }, function() {
  $(this).find("em").animate({opacity: "hide", top: "-85"}, "fast");
 });
});
</script>
</head>
<body>
<ul class="menu2">
 <li>
  <a href="http://tutorial101.blogspot.com/" title="Go to homepage">Home</a>  
 </li>
 <li>
  <a href="http://tutorial101.blogspot.com/" title="Find out who I am">About</a>
 </li>
 <li>
  <a href="http://tutorial101.blogspot.com/feeds/posts/default" title="Subscribe RSS feeds">Subscribe RSS</a>
 </li>
</ul>
<style type="text/css">
body {
 margin: 10px auto;
 width: 570px;
 font: 80%/120% Arial, Helvetica, sans-serif;
}
.menu2 {
 margin: 100px 0 0;
 padding: 0;
 list-style: none;
}
.menu2 li {
 padding: 0;
 margin: 0 2px;
 float: left;
 position: relative;
 text-align: center;
}
.menu2 a {
 padding: 14px 10px;
 display: block;
 color: #000000;
 width: 144px;
 text-decoration: none;
 font-weight: bold;
 background: url(img/button00.gif) no-repeat center center;
}
.menu2 li em {
 font-weight: normal;
 background: url(img/hover000.png) no-repeat;
 width: 180px;
 height: 45px;
 position: absolute;
 top: -85px;
 left: -15px;
 text-align: center;
 padding: 20px 12px 10px;
 font-style: normal;
 z-index: 2;
 display: none;
}
</style>
</body>
</html>

Download images

Friday, June 1, 2018

password meter using Javascript

password meter using Javascript



 
<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Password meter using javascript</title>
<script>
function passwordStrength(password)
{ 
var desc = new Array();
desc[0] = "Very Weak";
desc[1] = "Weak";
desc[2] = "Better";
desc[3] = "Medium";
desc[4] = "Strong";
desc[5] = "Strongest";
var score = 0;
//if password bigger than 6 give 1 point
if (password.length > 6) score++;
//if password has both lower and uppercase characters give 1 point
if ( ( password.match(/[a-z]/) ) && ( password.match(/[A-Z]/) ) ) score++;
//if password has at least one number give 1 point
if (password.match(/\d+/)) score++;
//if password has at least one special caracther give 1 point
if ( password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/) ) score++;
//if password bigger than 12 give another 1 point
if (password.length > 12) score++;
document.getElementById("passwordDescription").innerHTML = desc[score]; 
document.getElementById("passwordStrength").className = "strength" + score;
}
</script>
</head>
<body>
<form method="post">
<h1>Password strength meter</h1>
<label for="pass">Password</label>
<input type="password" name="pass" id="pass" onkeyup="passwordStrength(this.value)" />
<label for="passwordStrength">Password strength</label>
<div id="passwordDescription">Password not entered</div>
<div id="passwordStrength" class="strength0"></div>
</form>
<style>
#passwordStrength
{
height:10px;
display:block;
float:left;
}
.strength0
{
width:250px;
background:#cccccc;
}
.strength1
{
width:50px;
background:#ff0000;
}
.strength2
{
width:100px;
background:#ff5f5f;
}
.strength3
{
width:150px;
background:#56e500;
}
.strength4
{
background:#4dcd00;
width:200px;
}
.strength5
{
background:#399800;
width:250px;
}
</style>
</body>
</html>

Tuesday, May 29, 2018

Python IF and Else Condition Example code

Python IF and Else Condition Example code
 
#!/usr/bin/python
var = 100
if ( var  == 100 ) : print "Value of expression is 100"
print "Good bye!"

if 2 + 2 == 4:
 print "2 and 2 is 4"
 print "Arithmetic works."
else:
 print "2 and 2 is not 4"
 print "Big Brother wins."
 #--------------------------------------------------------------
num = 15
if num < 10:
 print "number is less than 10"
elif num > 10:
 print "number is greater than 10"
else:
 print "number is equal to 10" 
 #-------------------------------------------------------------- 
if 1 < 2:
 print "1 is less than 2"
elif 3 < 4:
 print "3 is less than 4"
else:
 print "Who moved my cheese?" 
 #-------------------------------------------------------------- 
want_cake = "yes"
have_cake = "no"
if want_cake == "yes":
  print "We want cake..."
  if have_cake =="no":
      print "But we don't have any cake"
elif have_cake == "yes":
 print "And it's our lucky day"
else:
 print "The cake is a lie."
#------------------------------------------------------------
phrase = "it marks the spot"
for letter in phrase:
 if letter == "X":
  break
else:
 print("There was no 'X' in the phrase")
#---------------------------------------------------------------
tries = 0
while tries < 3:
 password = input("Password: ")
 if password == "I<3Bieber":
  break
 else:
  tries = tries + 1
else:
 print("Suspicious activity. The authorities have been alerted.")
#---------------------------------------------------------------
if age > 18:
    print "adult person"

for i in range(5):
    print i 
#---------------------------------------------------------------
age = 17
if age > 18:
   print "Driving licence issued"
else:
   print "Driving licence not permitted"
#---------------------------------------------------------------
name = "Luke"
if name == "Jack":
   print "Hello Jack!"
elif name == "John":
   print "Hello John!"
elif name == "Luke":
   print "Hello Luke!" # Hello Luke!
else:
   print "Hello there!"   
#---------------------------------------------------------------
grades = ["A", "B", "C", "D", "E", "F"]
grade = "L"
if grade not in grades:
   print "unknown grade" # unknown grade
#---------------------------------------------------------------
sex = "M"
age = 26
if age < 55 and sex == "M":
   print "a young male" # a young male
#---------------------------------------------------------------
name = "Jack"
if ( name == "Robert" or name == "Frank" or name == "Jack" 
      or name == "George" or name == "Luke"):
   print "This is a male"   
#---------------------------------------------------------------
x = 10
y = 0
if (y != 0 and x/y < 100):
   print "a small value"   
#---------------------------------------------------------------
x,y =10,40
if(x < y):
   st= "x is less than y"
else:
   st= "x is greater than y"
print (st) 
#---------------------------------------------------------------
total = 500
#country = "US"
country = "AU"
if country == "US":
    if total <= 50:
        print("Shipping Cost is  $50")
elif total <= 100:
        print("Shipping Cost is $25")
elif total <= 150:
     print("Shipping Costs $5")
else:
        print("FREE")
if country == "AU": 
   if total <= 50:
     print("Shipping Cost is  $100")
else:
     print("FREE")
#---------------------------------------------------------------
a = 100
b = 100
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")
#---------------------------------------------------------------
a = 200
b = 33
c = 500
if a > b and c > a:
  print("Both conditions are True") 
#---------------------------------------------------------------
a = 6
b = 5
 
# Basic comparisons
if a < b:
    print("a is less than b")
 
if a > b:
    print("a is greater than b")
 
print("Done")

Related Post