Thursday, August 24, 2017

Bind Some Event to Element and trigger that function when click the element

Scenario:

Suppose if we used same click event function in various web pages. if you want do some logic some page button for that need to register the event

for buttons


Register events to button:

 $(document).ready(function(){
        $('.apply-filter').bind('beforeClick',function(event) {           
            if ($(this).data("value")=="10") {
                return true;
            }
            else return false;
        });
    });

Trigger the Registered function inside click event:

- creat event object using $.Event() metod and then trigger event by trigger(); method
- check the event prevented or not using event.isDefaultPrevented() based on that we can handle click event
- Button creations

 <div class="col-md-12" style="clear:both;">
            Button1 <button class="apply-filter" data-value="5">Five</button>
        </div>
        <div class="col-md-12">
            Button2 <button class="apply-filter" data-value="10">Ten</button>
        </div>
         <div class="col-md-12">
            Button2 <button class="apply-filter" data-value="15">Fifteen</button>
</div>

Sunday, August 6, 2017

Find Charts from web page and convert chart to Png using jquery

Find highcharts which are loaded in the page and then convert chart into png using  jquery

Charts are loaded through the ajax

See the example code:

create four php files for rendering charts one by one those file names are page1.php, page2.php, page3.php and page4.php

page1.php
---------

<?php
sleep(12);
$id = $_GET['key'];
?>
<div id="container<?php echo $id; ?>" style="">           
        </div>

 <script type="text/javascript">
      var chart =   Highcharts.chart('container<?php echo $id; ?>', {
    chart: {
        type: 'bar'
    },
    title: {
        text: 'Stacked bar chart'
    },
    xAxis: {
        categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
    },
    yAxis: {
        min: 0,
        title: {
            text: 'Total fruit consumption'
        }
    },
    legend: {
        reversed: true
    },
    plotOptions: {
        series: {
            stacking: 'normal'
        }
    },
    series: [{
        name: 'John',
        data: [5, 3, 4, 7, 2]
    }, {
        name: 'Jane',
        data: [2, 2, 3, 2, 1]
    }, {
        name: 'Joe',
        data: [3, 4, 4, 2, 5]
    }]
});     
 </script>

page2.php
---------

<?php
$id = $_GET['key'];
?>
<div id="container<?php echo $id; ?>" >           
        </div>
<script type="text/javascript">
Highcharts.chart('container<?php echo $id; ?>', {

    chart: {
        type: 'column'
    },

    title: {
        text: 'Total fruit consumtion, grouped by gender'
    },

    xAxis: {
        categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
    },

    yAxis: {
        allowDecimals: false,
        min: 0,
        title: {
            text: 'Number of fruits'
        }
    },

    tooltip: {
        formatter: function () {
            return '<b>' + this.x + '</b><br/>' +
                this.series.name + ': ' + this.y + '<br/>' +
                'Total: ' + this.point.stackTotal;
        }
    },

    plotOptions: {
        column: {
            stacking: 'normal'
        }
    },

    series: [{
        name: 'John',
        data: [5, 3, 4, 7, 2],
        stack: 'male'
    }, {
        name: 'Joe',
        data: [3, 4, 4, 2, 5],
        stack: 'male'
    }, {
        name: 'Jane',
        data: [2, 5, 6, 2, 1],
        stack: 'female'
    }, {
        name: 'Janet',
        data: [3, 0, 4, 4, 3],
        stack: 'female'}]
    });      
 </script>

page3.php
---------
<?php
$id = $_GET['key'];
?>
<div id="container<?php echo $id; ?>">           
</div>

 <script type="text/javascript"> 
$(document).ready(function () {
    // Build the chart
    Highcharts.chart('container<?php echo $id; ?>', {
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie'
        },
        title: {
            text: 'Browser market shares January, 2015 to May, 2015'
        },
        tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: false
                },
                showInLegend: true
            }
        },
        series: [{
            name: 'Brands',
            colorByPoint: true,
            data: [{
                name: 'Microsoft Internet Explorer',
                y: 56.33
            }, {
                name: 'Chrome',
                y: 24.03,
                sliced: true,
                selected: true
            }, {
                name: 'Firefox',
                y: 10.38
            }, {
                name: 'Safari',
                y: 4.77
            }, {
                name: 'Opera',
                y: 0.91
            }, {
                name: 'Proprietary or Undetectable',
                y: 0.2
            }]
        }]
    });
});     
</script>

page4.php
---------
<?php
$id = $_GET['key'];
?>
<div id="container<?php echo $id; ?>" >    
        </div>
 <script type="text/javascript">
      var chart =   Highcharts.chart('container<?php echo $id; ?>', {
    chart: {
        type: 'bar'
    },
    title: {
        text: 'Stacked bar chart'
    },
    xAxis: {
        categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
    },
    yAxis: {
        min: 0,
        title: {
            text: 'Total fruit consumption'
        }
    },
    legend: {
        reversed: true
    },
    plotOptions: {
        series: {
            stacking: 'normal'
        }
    },
    series: [{
        name: 'John',
        data: [5, 3, 4, 7, 2]
    }, {
        name: 'Jane',
        data: [2, 2, 3, 2, 1]
    }, {
        name: 'Joe',
        data: [3, 4, 4, 2, 5]
    }]
});     
</script>

Now Create Index.html.

First Load the necessary libraries of JQuery and highcharts

 <head>
        <script src="https://code.highcharts.com/highcharts.js"></script>
        <script src="https://code.highcharts.com/modules/exporting.js"></script>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
 </head>


and charts through the ajax using loop:

var ajax = [1,2,3,4,1,2,3,4,1,2,3,4];
        for(var k in ajax){ // loop
            //console.log();
// create div container for load charts dynamically and append it to body tag
            html = '<div id="cont'+k+'"style="min-height:400px;min-width:800px;border-width: 2px; border-style: solid; border-color: red; "></div>';
            $("body").append(html);
// scope function handling multiple ajax
         (function(key,ajax){
            // passing ajax to chart php files        
            $.ajax({
                method: 'get',
                url:'page'+ajax+'.php?key='+key+'&rand='+Math.random(),
                success: function(data) {
                   // load ajax response
                   $("#cont"+key).html(data);
// image conversion method
                   charttoimage(key);
                }
            });            
          
    })(k,ajax[k]);            
              
} });

Next charttoimage method explantion:

1) We can get highcharts objects using Highcharts.charts
2) We can get svg string from objects getSvg() method(highcharts native method)
3) we can convert svg into image using canvas element and canvas drawimage method
4) Create Image Object and render into highchart render element
5) Canvas to png binary using canvas toDataUrl methods
6) Image onload event load image.

code below:

var chartToImgArr = [];
    function charttoimage(key){
        // loop highchart     
        for(chart in Highcharts.charts){
            //check and skipe already converted
            if($.inArray(chart,chartToImgArr)>-1){ continue;  }             
            chartToImgArr.push(chart);
            // get chart obeject
            chart = Highcharts.charts[chart];
           // get SVG String
            var svg = chart.getSVG({
                exporting: {
                    sourceWidth: chart.chartWidth,
                    sourceHeight: chart.chartHeight
                }
           });
       // create canvas
            var canvas = document.createElement('canvas');
            canvas.width = chart.chartWidth;
            canvas.height = chart.chartHeight;
            // create image           
            var image = new Image;
            image.onload = function() {
            // drawimage into canvas
            canvas.getContext('2d').drawImage(this, 0, 0);
            // convert into png
            var data = canvas.toDataURL("image/png");
            image.src = data;           
            }; 
            // set svg into image tag         
            image.src = 'data:image/svg+xml;base64,' + window.btoa(svg);
            $(chart.renderTo).html(image);           
        } 
    }

Index.html:

<html>
    <head>
        <script src="jquery-3.2.1.min.js"></script>
        <script src="highcharts.js"></script>
        <script src="exporting.js"></script>
        <script type="text/javascript">
$(document).ready(function(){
    var chartToImgArr = [];
    function charttoimage(key){      
        for(chart in Highcharts.charts){
            if($.inArray(chart,chartToImgArr)>-1){ continue;  }             
            chartToImgArr.push(chart);
            chart = Highcharts.charts[chart];
          
            var svg = chart.getSVG({
                exporting: {
                    sourceWidth: chart.chartWidth,
                    sourceHeight: chart.chartHeight
                }
           });
            var canvas = document.createElement('canvas');
            canvas.width = chart.chartWidth;
            canvas.height = chart.chartHeight;
                      
            var image = new Image;
            image.onload = function() {
            canvas.getContext('2d').drawImage(this, 0, 0);           
            var data = canvas.toDataURL("image/png");
            image.src = data;           
            };           
            image.src = 'data:image/svg+xml;base64,' + window.btoa(svg);
            $(chart.renderTo).html(image);           
        } 
    }

           var ajax = [1,2,3,4,1,2,3,4,1,2,3,4];
           for(var k in ajax){         
            html = '<div id="cont'+k+'"style="min-height:400px;min-width:800px;border-width: 2px; border-style: solid; border-color: red; "></div>';
            $("body").append(html);
            (function(key,ajax){
            kkey = parseInt(key)+1;           
            if(kkey>=4) { kkey = kkey%4; if(kkey==0) kkey = kkey+1; }
            console.log("chart==="+key);
            $.ajax({
                method: 'get',
                url:'page'+ajax+'.php?key='+key+'&rand='+Math.random(),
                success: function(data) {
                  
                   $("#cont"+key).html(data);
                   charttoimage(key);
                }
            });            
          
    })(k,ajax[k]);    
}
});
        </script>
    </head>
    <body>
       
    </body>
</html>

OutPut:

Saturday, January 9, 2016

Find Start Date and End date Week , Week Number using javascript

First download momentjs from the link and include this in your html page.

For example:

<head>
        <script src="jquery-1.12.0.min.js"></script>
        <script type="text/javascript" src="moment.js"></script>
    </head>


<body>
Start Date:<div id="startdate"></div>
End Date<div id="enddate"></div>
Week:<div id="weekno"></div>
</body>

<script type="text/javascript">
 date = '2015-10-01';
 start = moment(date,'YYYY-MM-DD').startOf('week');
 //alert(start.format('YYYY-MM-DD HH:mm:ss'));
 end = moment(date,'YYYY-MM-DD').endOf('week');
 //alert(end.format('YYYY-MM-DD HH:mm:ss'));
 week = moment(date,'YYYY-MM-DD').week();
 console.log(start);
 console.log(end);
 $("#startdate").html(start.format('YYYY-MM-DD HH:mm:ss'));
 $("#enddate").html(end.format('YYYY-MM-DD HH:mm:ss'));
 $("#weekno").html(week);
</script>

Monday, February 23, 2015

convert time to seconds in javascript (prototype method)


Example code for convert time to seconds.

String.prototype.toSEC = function () {
value = this;
formats = value.split(":");
s = 0; m = 0; h = 0; res = 0;
if(formats.length>2) s = formats[2];
if(formats.length>1) m = formats[1];
if(formats.length>0) h = formats[0];
res += (parseInt(h)*3600);
res += (parseInt(m)*60);
res += parseInt(s);
return res;
}
time = '11:45:00';
time.toSEC();

Sunday, September 7, 2014

Upload Multiple files using Yii CUploadedFile class



Following code help your to upload multiple files using Yii CUploadedFile Class.

Model settings:

In your model class add rules for file tag  validation. Then add a attribute to your file tag and name it as "files"

example:

class Gallery extends CActiveRecord
{
public $files;
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function tableName()
{
return 'gallery';
}

public function rules()
{
return array(
array('files', 'file', 'types'=>'jpg, gif, png'),
array('files,asset_id','safe','on'=>"editrights")
   
    );
}
}

In your Controller:

Create a object for your class model. Then render your upload view file with param of gallery object.

example:

// place this code inside your action
$model=new Gallery;

if(isset($_POST["Gallery"])) {

// form massive assignment
$model->attributes = $_POST["Gallery"];
// uploader dir
$dir = "uploads/gallery/";
// get the array of CUploadedFile objects per files //

$fileobjects = CUploadedFile::getInstances($model,'files');
/*
* without model object you place following code
* $filemodel = CUploadedFile::getInstances('Gallery[files]');
*/
foreach( $fileobjects as $file) {
    // generate file name
    $randno=rand(11111,99999);
    $filename=$randno.$file->name;
    $dirfile = $dir.$filename;
    // save file in your location ensure your files dir is writable //
    $file->saveAs($dirfile);
    // save your file name
    $save = new Gallery;
    $save->name = $filename;
    $save->type = $file->extensionName;
    $save->save(false);
    chmod($dirfile, 0777);
    // if you want resize the image user following code //
    //
    if(preg_match('/image/',$file->type)) {
        // use convert command for resize file before make sure you get installed imagegick tool //
        echo exec("convert ".$file." -scale 220 ".$dir."thumb_".$filename);   
    }
}
$this->render("upload",array("model",$model));

In your view page:

Add file code in your form.

echo CHtml::activeFileField($model,'files[]',array("id"=>"files","multiple"=>true,"style"=>"margin-top:5px;"));


For more CUploadedFile options see CUploadedFile class reference


Thursday, August 28, 2014

Model Object to result array in Yii


Yii CActiverecord methods findall, findAllByattributes always return object. if you want get the result as array. By you can get the dbcriteria use it in commanBuilder

$object = Message::model();
$object = $object ->getCommandBuilder()
               ->createFindCommand($object ->tableSchema, $object ->dbCriteria)
               ->queryAll();

print_r($object);


Monday, August 25, 2014

Steps to install vagrant on windows system


This will help you to work with Virtual machines.. and helps us to work with Git


A) VirtalBox Dwonlad and install

B) Vagrant Download and install

Restart the system

Goto command line prompt

Create the Folder in your system using mkdir

1.. Start the vagrant
vagrant init

This command will create the config files

2.. Coping the vagrant from server. this is installing the Ubuntu 

vagrant box add precise32   http://files.vagrantup.com/precise32.box

3.. Now change the following line in the config file
box to prcecise32 in vagrant config

4.. Now the time to boot the new Ubuntu

vagrant up

5. This command will helps to stop the ubuntu

vagrant suspend

6. This command will helps to reboot the ubuntu
vagrant reload
 
 

Bind Some Event to Element and trigger that function when click the element

Scenario: Suppose if we used same click event function in various web pages. if you want do some logic some page button for that need to re...