Sunday, February 26, 2017

javascript alert like div example

By using bootbox js library we can create a dialogue box like javascript alert. i have tried different types and then commented it. you can just uncomment it to see its effect. For more description and uses visit its page Bootbox Page Link

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Basic Bootstrap Template</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js" ></script>
    <script type="text/javascript">
    $('document').ready(function(){
    $('#alert').click(function(){
    //bootbox.alert("Your message here…");
    /*bootbox.alert("This is an alert with a callback!", function(){
    console.log('This was logged in the callback!');
    });*/
bootbox.alert({
   message: "This is an alert with a callback!",
   size: 'large', // small,large
   backdrop: true,
   callback: function () {
       console.log('This was logged in the callback!');
   }
});
/*bootbox.confirm("This is the default confirm!", function(result){
console.log('This was logged in the callback: ' + result);
});*/
/*bootbox.confirm({
   message: "This is an alert with a callback!",
   size: 'large', // small,large
   backdrop: true,
   callback: function (result) {
       console.log('This was logged in the callback! '+result);
   }
});*/
/*bootbox.confirm({
   message: "This is a confirm with custom button text and color! Do you like it?",
   buttons: {
       confirm: {
           label: 'Yes',
           className: 'btn-success'
       },
       cancel: {
           label: 'No',
           className: 'btn-danger'
       }
   },
   callback: function (result) {
       console.log('This was logged in the callback: ' + result);
   }
});*/
/*var dialog = bootbox.confirm({
   title: "Destroy planet?",
   message: "Do you want to activate the Deathstar now? This cannot be undone.",
   buttons: {
       cancel: {
           label: '<i class="fa fa-times"></i> Cancel'
       },
       confirm: {
           label: '<i class="fa fa-check"></i> Confirm'
       }
   },
   callback: function (result) {
       console.log('This was logged in the callback: ' + result);
   }
});
dialog.init(function(){
   setTimeout(function(){
       dialog.find('.bootbox-body').html('I was loaded after the dialog was shown!');
   }, 3000);
});*/

    });    
    });
   
    </script>
</head>
<body>
<button id="alert">For Alert</button>
<!-- <div class="alert alert-info fade in">
   <a href="#" class="close" data-dismiss="alert">&times;</a>
   <strong>Note!</strong> Please read the <a href="#" class="alert-link">comments</a> carefully.
</div>
<div class="alert alert-warning fade in">
   <a href="#" class="close" data-dismiss="alert">&times;</a>
   <strong>Warning!</strong> There was a problem with your network connection.
</div> -->
</body>
</html>

Tuesday, January 31, 2017

google recaptcha in cakephp

For google recaptcha at first register your site at this link: https://www.google.com/recaptcha/admin

Enter your site details. if you have to use on local machine then enter domain name and lable as 'localhost'.
In controller

    function recaptcha(){
    if(isset($_POST['submit'])){
        if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
            //your site secret key
            $secret = '6LfR2xMUAAAAAJ9EvvLrA5mQUqZ77owaFQ3RVvou';
            //get verify response data
            $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
            $responseData = json_decode($verifyResponse);
         
            $name = !empty($_POST['name'])?$_POST['name']:'';
            $email = !empty($_POST['email'])?$_POST['email']:'';
            $message = !empty($_POST['message'])?$_POST['message']:'';
            if($responseData->success){
                //contact form submission code
                $to = 'gautam8953@gmail.com';
                $subject = 'New contact form have been submitted';
                $htmlContent = "
                    <h1>Contact request details</h1>
                    <p><b>Name: </b>".$name."</p>
                    <p><b>Email: </b>".$email."</p>
                    <p><b>Message: </b>".$message."</p>
                ";
                // Always set content-type when sending HTML email
                $headers = "MIME-Version: 1.0" . "\r\n";
                $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
                // More headers
                $headers .= 'From:'.$name.' <'.$email.'>' . "\r\n";
                //send email

                @mail($to,$subject,$htmlContent,$headers);
             
                $succMsg = 'Your contact request have submitted successfully.';
                $name = '';
                $email = '';
                $message = '';
                $errMsg = '';
            }else{
                $errMsg = 'Robot verification failed, please try again.';
                $succMsg = '';
                $this->set('name',$name);
                $this->set('email',$email);
                $this->set('message',$message);
            }
        }else{
            $errMsg = 'Please click on the reCAPTCHA box.';
            $succMsg = '';
            $this->set('name',$name);
            $this->set('email',$email);
            $this->set('message',$message);
        }
    }else{
        $errMsg = '';
        $succMsg = '';
        $name = '';
        $email = '';
        $message = '';
    }
    $this->set('errMsg',$errMsg);
    $this->set('succMsg',$succMsg);
    }

in view recaptcha.ctp
<script src="https://www.google.com/recaptcha/api.js" async defer></script>

    <div class="registration">
<h2>Contact Form</h2>
        <?php if(!empty($errMsg)): ?><div class="errMsg"><?php echo $errMsg; ?></div><?php endif; ?>
        <?php if(!empty($succMsg)): ?><div class="succMsg"><?php echo $succMsg; ?></div><?php endif; ?>
<div class="form-info">
<form action="" method="POST">
<input type="text" class="text" value="<?php echo !empty($name)?$name:''; ?>" placeholder="Your full name" name="name" >
                <input type="text" class="text" value="<?php echo !empty($email)?$email:''; ?>" placeholder="Email adress" name="email" >
                <textarea type="text" placeholder="Message..." required="" name="message"><?php echo !empty($message)?$message:''; ?></textarea>
<div class="g-recaptcha" data-sitekey="6LfR2xMUAAAAABBy2TBrBKur0_L23TizUGR-M20s"></div>
<input type="submit" name="submit" value="SUBMIT">
</form>
</div>
<div class="clear"> </div>
</div>

Sunday, November 27, 2016

Multiple JQuery Autocomplete With Selector

Multiple jquery autocomplete : example of multiple jquery autocomplete and also when select any element or hover on list description of hovered element will show and when we select the element its value will shown in lebel.

<!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <title>Multiple JQuery Autocomplete with selector</title>
      <link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
      <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
      <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
      <!-- Javascript -->
      <script>
         $(function() {
            var projects = [
            {
               value: "java",
               label: "Java",
               desc: "write once run anywhere",
            },
            {
               value: "jquery-ui",
               label: "jQuery UI",
               desc: "the official user interface library for jQuery",
            },
            {
               value: "Bootstrap",
               label: "Twitter Bootstrap",
               desc: "popular front end frameworks ",
            }
         ];
            $("[id^=autocomplete_]").autocomplete({
               source: projects,
                focus: function( event, ui ) {
                    var idArr=$(this).attr('id').split('_');
                    $('#value_'+idArr[1]).text(ui.item.desc);
                        return false;
                },
                select: function( event, ui ) {
                    var idArr=$(this).attr('id').split('_');
                    $('#value_'+idArr[1]).text(ui.item.value);
                        return false;
                }

            });
         });
      </script>
   </head>
   <body>
      <!-- HTML -->
      <div class="ui-widget">
         <p>Type J OR b</p>
         <input id="autocomplete_1"><label id="value_1"></label><br>
         <input id="autocomplete_2"><label id="value_2"></label><br>
         <input id="autocomplete_3"><label id="value_3"></label><br>
         <input id="autocomplete_4"><label id="value_4"></label><br>
         <input id="autocomplete_5"><label id="value_5"></label><br
      </div>
   </body>
</html>

Monday, November 14, 2016

infinite load more data at page end

<!DOCTYPE html>
<html>
<head>
    <title>Loading</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <style type="text/css">
        .loadedcontent {min-height: 800px; }
    </style>
</head>
<body>
<input type="hidden" value="0" id="numCount"></input>
<div id="container">
    <div style="border:1px solid" class="loadedcontent">old div</div>
</div>

</body>
</html>
<script type="text/javascript">
var processing;

$(document).ready(function(){
    $(document).scroll(function(e){
        if (processing){
            return false;
        }

        if ($(window).scrollTop() >= ($(document).height() - $(window).height())*0.7){
            processing = true;
            var numCount=$("#numCount").val();
            numCount++;
            var data1='<div class="loadedcontent">new div'+numCount+'</div>';
            //var sortData = $('#productsearchid').serialize();
            //var sortData = {};
            //sortData['category_name'] = 'electronics';
            //$.ajax({
            //    url:"load_data.php",
            //    cache:false,
            //    type:'GET',
            //    data:sortData,
                //success:function(data){
                    $('#container').append(data1);
                    $("#numCount").val(numCount)
                    processing = false;
                //}
            //});
        }
    });
});
</script>

Saturday, November 5, 2016

call js function when user stop typing

Many times we need instant result of whatever the change has been made. For calculation we define some function and do calculation there or for search we do ajax call. But for result we we call our function /ajax on every keyup event then what happen if i have to search a name "gautam" then then function calls 6 times as each keyup but 5 call is a waste as i am searching for "gautam" not for each character as typed.

In short we should call our function or ajax request when user stop typing not on each and every key up. For it we may guess when user type halts for a second or two second then his typing is finished and we can do whatever the result he wants.

<!DOCTYPE html>
<html>
<head>
    <title>call js function when stop typing</title>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $('document').ready(function() {
        $('#in').keyup(function() {
            s = $('#in').val();
            setTimeout(function() {
                if($('#in').val() == s){ // Check value is last typed or not.
                    // call ajax or any function or whaterver you wnat
                    var v = $("#in").val();
                    $("#out").html(v);
                }
            }, 1000); // 1 sec delay to check.
        });
    });

    </script>
</head>
<body>
<input id="in" type="text"/>
<div id="out"></div>
</body>
</html>


<!DOCTYPE html>
<html>
<head>
    <title>call js function when stop typing</title>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    var typingTimer;                //timer identifier
    var doneTypingInterval = 1000;  //time in ms, 5 second for example

    //on keyup, start the countdown
    $('document').ready(function(){
        $('#in').keyup(function(){
            clearTimeout(typingTimer);
            if ($('#in').val) {
                typingTimer = setTimeout(function(){
                    //do stuff here e.g ajax call etc....
                    var v = $("#in").val();
                    $("#out").html(v);
                }, doneTypingInterval);
            }
        });      
    });

    </script>
</head>
<body>
<input id="in" type="text"/>
<div id="out"></div>
</body>
</html>

Monday, September 12, 2016

call any other element property function from another function

Call any other function defined with own argument from another function by reading the property.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
function checkFun(i,name,code){
if(document.getElementById('name_'+i).checked==true){
console.log('checked '+i+' '+name+' '+code);
} else {
console.log('not checked '+i+' '+name+' '+code);
}
}
function checkAll(ths){
var k=$(ths);
if(k.prop('checked')==true){
for(var i=1;i<=document.getElementsByName('ids[]').length;i++){
var t=$('#name_'+i);
var funArgList=t.attr('onClick');
var funArgListArr1=funArgList.replace(/[('",)]/g,'_');
funArgListArr1=funArgListArr1.replace(/_+/g, '_');
var funArgListArr2=funArgListArr1.split('_');
if(document.getElementById('name_'+funArgListArr2[1]).checked==false){
document.getElementById('name_'+funArgListArr2[1]).checked=true;
checkFun(funArgListArr2[1],funArgListArr2[2],funArgListArr2[3]);
} else {
continue;
}

}
} else {
for(var i=1;i<=document.getElementsByName('ids[]').length;i++){
document.getElementById('name_'+i).checked=false;
}
}

}
</script>
</head>
<body>
<table>
<tr>
<td><input onclick="checkAll(this)" id="name_0" type="checkbox" name="" value="" /></td>
<td id="name_0">Select All</td>
</tr>
<tr>
<td><input onclick="checkFun('1','name1 h','code1')" id="name_1" type="checkbox" name="ids[]" value="" /></td>
<td id="name_1">name1</td>
</tr>
<tr>
<td><input onclick="checkFun('2','name2','code2')" id="name_2" type="checkbox" name="ids[]" value="" /></td>
<td id="name_2">name2</td>
</tr>
<tr>
<td><input onclick="checkFun('3','name3','code3')" id="name_3" type="checkbox" name="ids[]" value="" /></td>
<td id="name_3">name3</td>
</tr>
<tr>
<td><input onclick="checkFun('4','name4','code4')" id="name_4" type="checkbox" name="ids[]" value="" /></td>
<td id="name_4">name4</td>
</tr>
<tr>
<td><input onclick="checkFun('5','name5','code5')" id="name_5" type="checkbox" name="ids[]" value="" /></td>
<td id="name_5">name5</td>
</tr>
<tr>
<td><input onclick="checkFun('6','name6','code6')" id="name_6" type="checkbox" name="ids[]" value="" /></td>
<td id="name_6">name6</td>
</tr>
<tr>
<td><input onclick="checkFun('7','name7','code7')" id="name_7" type="checkbox" name="ids[]" value="" /></td>
<td id="name_7">name7</td>
</tr>
</table>
</body>
</html>

Friday, September 2, 2016

Wordwrap in fpdf table cell

Adding word wrap feature while creating pdf file using fpdf table cell data .
Complete source ccode is at end.
<?php
require('mc_table.php');

class PDF extends FPDF
{
// Load data
function LoadData($file)
{
// Read file lines
$lines = file($file);
$data = array();
foreach($lines as $line)
$data[] = explode(';',trim($line));
return $data;
}

// Simple table
function BasicTable($header, $data)
{
// Header
foreach($header as $col)
$this->Cell(40,7,$col,1);
$this->Ln();
// Data
foreach($data as $row)
{
foreach($row as $col)
$this->Cell(40,6,$col,1);
$this->Ln();
}
}

// Better table
function ImprovedTable($header, $data)
{
// Column widths
$w = array(40, 35, 40, 45);
// Header
for($i=0;$i<count($header);$i++)
$this->Cell($w[$i],7,$header[$i],1,0,'C');
$this->Ln();
// Data
foreach($data as $row)
{
$this->Cell($w[0],6,$row[0],'LR');
$this->Cell($w[1],6,$row[1],'LR');
$this->Cell($w[2],6,number_format($row[2]),'LR',0,'R');
$this->Cell($w[3],6,number_format($row[3]),'LR',0,'R');
$this->Ln();
}
// Closing line
$this->Cell(array_sum($w),0,'','T');
}

// Colored table
function FancyTable($header, $data)
{
// Colors, line width and bold font
$this->SetFillColor(255,0,0);
$this->SetTextColor(255);
$this->SetDrawColor(128,0,0);
$this->SetLineWidth(.3);
$this->SetFont('','B');
// Header
$w = array(40, 35, 40, 45);
for($i=0;$i<count($header);$i++)
$this->Cell($w[$i],7,$header[$i],1,0,'C',true);
$this->Ln();
// Color and font restoration
$this->SetFillColor(224,235,255);
$this->SetTextColor(0);
$this->SetFont('');
// Data
$fill = false;
foreach($data as $row)
{
$this->Cell($w[0],6,$row[0],'LR',0,'L',$fill);
$this->Cell($w[1],6,$row[1],'LR',0,'L',$fill);
$this->Cell($w[2],6,number_format($row[2]),'LR',0,'R',$fill);
$this->Cell($w[3],6,number_format($row[3]),'LR',0,'R',$fill);
$this->Ln();
$fill = !$fill;
}
// Closing line
$this->Cell(array_sum($w),0,'','T');
}
}

function GenerateWord()
{
//Get a random word
$nb=rand(3,10);
$w='';
for($i=1;$i<=$nb;$i++)
$w.=chr(rand(ord('a'),ord('z')));
return $w;
}

function GenerateSentence()
{
//Get a random sentence
$nb=rand(1,10);
$s='';
for($i=1;$i<=$nb;$i++)
$s.=GenerateWord().' ';
return substr($s,0,-1);
}

$pdf=new PDF_MC_Table();
$pdf->AddPage();
$pdf->SetFont('Arial','',14);
//Table with 20 rows and 4 columns
$pdf->SetWidths(array(30,50,30,40));
srand(microtime()*1000000);
/*for($i=0;$i<20;$i++){
$pdf->Row(array(GenerateSentence(),GenerateSentence(),GenerateSentence(),GenerateSentence()));
}*/
$pdf1 = new PDF();
$data = $pdf1->LoadData('countries.txt');
//print_r($data);
$i=0;
foreach ($data as $key => $value) {
$pdf->Row(array($i++.' '.$value[0],$value[1],$value[2],$value[3]));
}
$pdf->Output();
?>

Source Code