Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Monday, 23 November 2015

Stripe Payment Gateway Integrate Using PHP

There are lots of payment gateway available in the web market like PayPal, iTransact, Card Gate Plus, SagePay, ANZ eGate and many more. Today, we are going to introduce one of the most powerful payment gateway for Web and Mobile payment. Yes, we are talking about Stripe Payment Gateway.
Integration of Stripe payment gateway using PHP is very easy. Just follow few steps and it will be ready.

Stripe take care the processing and keeping client’s card data so no information of essence would be stored on our server and you would not have to comply with all the rules that come with storing credit/debit cards. 


Step 1: Create an account on Stripe https://dashboard.stripe.com/register

Step 2: Login your account and go to Account setting for API Keys.

 

 

Step 3: Download the source code and replace the secret key in payment.php:
<?php
try {  
    require_once('Stripe/lib/Stripe.php');
    Stripe::setApiKey("XXXX_YOUR_SECRET_KEY"); //Replace with your Secret Key  
    $charge = Stripe_Charge::create(array(
                "amount" => 2100,
                "currency" => "usd",
                "card" => $_POST['stripeToken'],
                "description" => "Demo Transaction"
            ));
    //send the file, this line will be reached if no error was thrown above
    echo "<h1>Your payment has been completed.</h1>";
    //you can send the file to this email:
    echo $_POST['stripeEmail'];
}

Step 4: Edit index.php file and replace with your Publishable Key

<script src="https://checkout.stripe.com/checkout.js"
    class="stripe-button"
    data-key="XXX_YOUR_PUBLISHER_KEY" //Replace with your Publishable key
    data-image="http://www.stepblogging.com/wp-content/uploads/2014/12/logo1.png"
    data-name="StepBlogging.com"
    data-description="Demo Transaction ($21.00)"
    data-amount="2100" />
</script>

The test version does not entail any actual funds. However for testing you can use below mentioned detail:
Testing Card Number - 4242424242424242
CVV Number - 1234 
Card Expiry Date - Use any future date

If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries.

Google Map API Integrate Using PHP

To display geographic information using Google Map is a very important and demanding feature of website. To integrate Google Map is a difficult task for PHP beginners. In this tutorial we are going to explain how to integrate Google Map API using PHP and display the location on Google Map.

 

 A simple HTML form to capture user address detail:

<html>
<head>
    <meta http-equiv="Content-Type"content="text/html; charset=UTF-8">
    <title>Google Map API  Integrate Using PHP </title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
</head>
<body>
<div class='web'>
    <h1>How To Load Data On Page Scroll Using JQuery</h1> <br />
    <div class='inner'>
        <form class="mapinfo" method="POST" action="index.php">
            <label>Address</label>
            <input type="text" id="address" name="address" />
            </br>
            <label>city</label>
            <input type="text" id="city" name="city" />
            </br>
            <label>state</label>
            <input type="text" id="state" name="state" />
            </br>
            <label>country</label>
            <input type="text" id="country" name="country" />
            </br>
            <label>zip</label>
            <input type="text" id="zip" name="zip" />
            </br>
            <input type="submit" id="submit" name="submit" />
        </form>
    </div>
</div>
</body>
</html>

PHP Code to call google map api and fetch the detail:
<?php
if(isset($_POST['submit'])){
    $address = urlencode($_POST['address']);
    $city = urlencode($_POST['city']);
    $state = urlencode($_POST['state']);
    $country   = urlencode($_POST['country']);
    $zip = $_POST['zip'];
    $resultGeoCode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$address.',+'.$city.',+'.$state.',+'.$country.'&sensor=false');
 
    $output= json_decode($resultGeoCode);
    if($output->status == 'OK'){
        $latitude = $output->results[0]->geometry->location->lat; //Returns Latitude
        $longitude = $output->results[0]->geometry->location->lng; // Returns Longitude
        $location = $output->results[0]->formatted_address;
    }
}
?>

Javascript code to generate map after getting the response from google map api:
<script type="text/javascript">
$(document).ready(function () {
function initialize() {
 
// Define the latitude and longitude positions
var latitude = parseFloat("<?php echo $latitude; ?>"); // Latitude get from above variable
var longitude = parseFloat("<?php echo $longitude; ?>"); // Longitude from same
var latlngPos = new google.maps.LatLng(latitude, longitude);
 
// Set up options for the Google map
var myOptions = {
zoom: 13,
center: latlngPos,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControlOptions: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
}
};
// Define the map
map = new google.maps.Map(document.getElementById("display_map"), myOptions);
 
addMarker(latlngPos, 'Default Marker', map);
  
  google.maps.event.addListener(map, 'dragstart', function(event) {
  //infowindow.open(map,marker);
      addMarker(event.latlngPos, 'Click Generated Marker', map);
  
   var lat, lng, address;
                    
  });
 
  
}
  function addMarker(latlng,title,map) {
    var marker = new google.maps.Marker({
            position: latlng,
            map: map,
            title: title,
icon:'marker.png',
            draggable:true,
animation: google.maps.Animation.DROP
    });
 
    google.maps.event.addListener(marker,'drag',function(event) {
        document.getElementById('lat').value = event.latLng.lat();
        document.getElementById('lng').value= event.latLng.lng();
    });
 
    google.maps.event.addListener(marker,'dragend',function(event) {
        document.getElementById('lat').value = event.latLng.lat();
        document.getElementById('lng').value = event.latLng.lng();
alert(marker.getPosition());
    });
   google.maps.event.addListener(map, 'zoom_changed', function () {
      document.getElementById('zoom').value =map.getZoom();
    });
}
google.maps.event.addDomListener(window, 'load', initialize);
});
</script>

If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries.

Friday, 20 November 2015

Multistep Registration Form Using PHP

Sometimes we required to capture lots of user details during registration. Due to this we got long forms on our website. So the best solution is to break into smaller logical section and convert it into a multi step form. This type of mult step form always improves usability on our site comparing very long form. Now we are going to explain how to convert very long form into multi-step signup form using PHP, MySQLi / PDO and jQuery.

 

NOTE: password_verify() required PHP version >=5.5. So use another hashing if your server don’t have PHP version 5.5 or greater.
You can use another password encryption and decryption method if you have PHP version < 5.5.

Database SQL Script:


CREATE TABLE `users` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NULL DEFAULT NULL,
`password` VARCHAR(72) NULL DEFAULT NULL,
`email` VARCHAR(100) NULL DEFAULT NULL,
`gender` VARCHAR(6) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;

Database Connection: (db_connection.php)
<?php
    define('_HOST_NAME', 'localhost');
    define('_DATABASE_USER_NAME', 'root');
    define('_DATABASE_PASSWORD', '');
    define('_DATABASE_NAME', 'demo');
 
    $dbConnection = new mysqli(_HOST_NAME, _DATABASE_USER_NAME, _DATABASE_PASSWORD,
 _DATABASE_NAME);
    if ($dbConnection->connect_error) {
        trigger_error('Connection Failed: '  . 
$dbConnection->connect_error, E_USER_ERROR);
     }

index.php
<?php
    include 'db_connection.php'; 
    if(isset($_POST['finish'])){
      $name = '"'.$dbConnection->real_escape_string($_POST['name']).'"';
     $email = '"'.$dbConnection->real_escape_string($_POST['email']).'"';
     $password = '"'.password_hash($dbConnection->real_escape_string($_POST['password'])
, PASSWORD_DEFAULT).'"';
        $gender = '"'.$dbConnection->real_escape_string($_POST['gender']).'"';
  
        $sqlInsertUser = $dbConnection->query("INSERT INTO users (name, password, email,
 gender) VALUES($name, $password, $email, $gender)");
 
        if($sqlInsertUser === false){
        trigger_error('Error: ' . $dbConnection->error, E_USER_ERROR);
        }else{
            echo 'Last inserted record is : ' .$dbConnection->insert_id ; 
        }
    }
?>
<html>
<head>
<title>Multi step registration form PHP, JQuery, MySQLi</title>

<style>
body{font-family:tahoma;font-size:12px;}
#signup-step{margin:auto;padding:0;width:53%}
#signup-step li{list-style:none; float:left;padding:5px 10px;
border-top:#004C9C 1px solid;border-left:#004C9C 1px solid;
border-right:#004C9C 1px solid;border-radius:5px 5px 0 0;}
.active{color:#FFF;}
#signup-step li.active{background-color:#004C9C;}
#signup-form{clear:both;border:1px #004C9C solid;padding:20px;width:50%;margin:auto;}
.demoInputBox{padding: 10px;border: #CDCDCD 1px solid;border-radius: 4px;
background-color: #FFF;width: 50%;}
.signup-error{color:#FF0000; padding-left:15px;}
.message {color: #00FF00;font-weight: bold;width: 100%;padding: 10;}
.btnAction{padding: 5px 10px;background-color: #F00;border: 0;color: #FFF;cursor: 
pointer; margin-top:15px;}
label{line-height:35px;}
</style>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>

function validate() {
    var output = true;
    $(".signup-error").html('');
    if($("#personal-field").css('display') != 'none') {
        if(!($("#name").val())) {
            output = false;
            $("#name-error").html("Name required!");
        }
        if(!($("#email").val())) {
            output = false;
            $("#email-error").html("Email required!");
        }
        /** Remove below Comment for email validation **/ 
        /*if(!$("#email").val().match(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/)) {
            $("#email-error").html("Invalid Email!");
            output = false;
        }*/
    }

    if($("#password-field").css('display') != 'none') {
        if(!($("#user-password").val())) {
            output = false;
            $("#password-error").html("Password required!");
        } 
        if(!($("#confirm-password").val())) {
            output = false;
            $("#confirm-password-error").html("Confirm password required!");
        } 
        if($("#user-password").val() != $("#confirm-password").val()) {
            output = false;
            $("#confirm-password-error").html("Password not matched!");
        } 
    }
    return output;
}

$(document).ready(function() {
    $("#next").click(function(){
        var output = validate();
        if(output) {
            var current = $(".active");
            var next = $(".active").next("li");
                if(next.length>0) {
                    $("#"+current.attr("id")+"-field").hide();
                    $("#"+next.attr("id")+"-field").show();
                    $("#back").show();
                    $("#finish").hide();
                    $(".active").removeClass("active");
                    next.addClass("active");
                    if($(".active").attr("id") == $("li").last().attr("id")) {
                        $("#next").hide();
                        $("#finish").show();    
                    }
                }
            }
        });
    $("#back").click(function(){ 
        var current = $(".active");
        var prev = $(".active").prev("li");
        if(prev.length>0) {
            $("#"+current.attr("id")+"-field").hide();
            $("#"+prev.attr("id")+"-field").show();
            $("#next").show();
            $("#finish").hide();
            $(".active").removeClass("active");
            prev.addClass("active");
            if($(".active").attr("id") == $("li").first().attr("id")) {
                $("#back").hide();   
            }
        }
    });
});
</script>
</head>
<body>
<ul id="signup-step">
    <li id="personal" class="active">Personal Detail</li>
    <li id="password">Password</li>
    <li id="general">General</li>
</ul>
<form name="frmRegistration" id="signup-form" method="post">
    <div id="personal-field">
        <label>Name</label><span id="name-error" class="signup-error"></span>
        <div><input type="text" name="name" id="name" class="demoInputBox"/></div>
        <label>Email</label><span id="email-error" class="signup-error"></span>
        <div><input type="text" name="email" id="email" class="demoInputBox" /></div>
    </div>
        <div id="password-field" style="display:none;">
            <label>Enter Password</label><span id="password-error" class="signup-error">
</span>
            <div><input type="password" name="password" id="user-password" 
class="demoInputBox" /></div>
            <label>Re-enter Password</label><span id="confirm-password-error" 
class="signup-error"></span>
            <div><input type="password" name="confirm-password" id="confirm-password" 
class="demoInputBox" /></div>
        </div>
        <div id="general-field" style="display:none;">
            <label>Gender</label>
            <div>
                <select name="gender" id="gender" class="demoInputBox">
                    <option value="female">Female</option>
                    <option value="male">Male</option>
                </select>
            </div>
        </div>
    <div>
        <input class="btnAction" type="button" name="back" id="back" value="Back"
 style="display:none;">
        <input class="btnAction" type="button" name="next" id="next" value="Next" >
        <input class="btnAction" type="submit" name="finish" id="finish" value="Finish" 
style="display:none;">
    </div>
</form>
</body>
</html>


If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries.

Friday, 21 August 2015

Create / Read / Erase Cookie using Javascript

These are the three javascript function.

  1.     createCookie: Using this function you can create cookie 

  2.     readCookie: This function is used to read cookie. 

  3.     eraseCookie: Use this function to erase any existing cookie.


    <style type="text/css">
    function createCookie(name, value, days) {
        var expires;

        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toGMTString();
        } else {
            expires = "";
        }
        document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
    }

    function readCookie(name) {
        var nameEQ = escape(name) + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) === ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) return unescape(c.substring(nameEQ.length, c.length));
        }
        return null;
    }

    function eraseCookie(name) {
        createCookie(name, "", -1);
    }
    </script>

    If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries.

     

Thursday, 23 July 2015

Confirm box on click anchor link to delete record

HTML  Code


<a href="javascript:void(0);" onclick="delete(<?php echo $row->id;?>);">Delete</a>
 
Javascript Code

<script type="text/javascript">
    var url="<?php echo base_url();?>";
    function delete(id){
       var r=confirm("Do you want to delete this?")
        if (r==true)
          window.location = url+"user/deleteuser/"+id;
        else
          return false;
        } 
</script>
 

Sunday, 5 July 2015

Sum up columns of a table Javascript

I have a simple table set up in which a user can insert values into the boxes and onkeydown it will sum up the column.


HTML: Code

    <table>
    <tr>
    <td><input type="text" onblur="calTotal(this, 'tot')" /></td>
    <td><input type="text" onblur="calTotal(this, 'tot1')" /></td>
    </tr>
    <tr>   
    <td><input type="text" onblur="calTotal(this, 'tot')" /></td>
    <td><input type="text" onblur="calTotal(this, 'tot1')" /></td>
    </tr>
    <tr>   
    <td><input type="text" onblur="calTotal(this, 'tot')" /></td>
    <td><input type="text" onblur="calTotal(this, 'tot1')" /></td>      
    </tr>
    <tr>   
    <td><input type="text" id="tot" /></td>
    <td><input id="tot1" type="text" /></td>
    </tr>  
    </table>


javascript: Code

    <script type="text/javascript">
    function calTotal(txtBox, totBox)
    {
        var totVal;
        try
        {
        totVal = document.getElementById(totBox).value;
        if(totVal!= null && totVal!='')
         {
           document.getElementById(totBox).value= eval(parseInt(document.getElementById(totBox).value) + parseInt(txtBox.value));  
         }
         else
         {
            document.getElementById(totBox).value= txtBox.value;          
         }
        }
        catch(e)
        {}
    }
    </script>