Friday, June 26, 2015

CSS. draw a line in a box




This is the style to draw a line in left side a box:
 1) Using box shadow:
 box-shadow: inset -10px 0 5px -5px hsla(0,100%,50%,0.5); 
2) Set a style in left side of the box:
       border-left-width: 5px;
        border-left-style: solid;
        border-left-color: #B27F4C;

MySQL NULL column during comparison




In MySQL table, I have column WorkPermit, 5 values, 'N', 'N', 'N', NULL, NULL

When we do MySQl statement  WorkPermit !=N, we expect to get 2, but result return nothing
as NULL not participate comparision in not equal.

So when we use != (not equal) in MySQL, we should add condition
( WorkPermit !=N or WorkPermit IS NULL)

Wednesday, June 24, 2015

json_encode data in php to javascript




I have a function in php
       function GetROFRpl($arr){
             $arr['coursename'] = preg_replace('/\s+/', '',   $arr['coursename']);
             $c = new Connection();
                   $sql0 = "SELECT * FROM rofr_parental_leave WHERE stakeholder_id =   {$this->sanitizeInput($arr['sid'])}
                    AND coursename = {$this->sanitizeInput($arr['coursename'])} ";
                     $result = $c->query($sql0);
                  
                      while($row = $c->getArray($result)){
                              $data[$row['id']] = $row;
                          }
                        return $data;     
                   
        }  
 
which is called by another function and data format to json_encode
   function GetROFRpl($arr){
                $model =  new TeachingContract();
                $data =  $model->GetROFRpl($arr);
                $arrayForJSON = array("count" => count($data), "data" => $data);
                echo json_encode( $arrayForJSON );
    }   

In javascript, I used JSON.parse to parse data to Javascript array
     $('.pl').on('click',  function(){
     
         var row=$(this).parents('tr');

         var sid=row.find('.sid').attr('data-sid');
         var coursename=row.find('.coursename').html();
            
         pldate= "Parental Leave:<table id='pl_table'><tbody>";

         var postdata = {funct: 'GetROFRpl', sid:sid,  coursename:coursename};
         var url = '../_ajaxParts/ROFR/SITAROFR_list.php';

         $.post(url, postdata, function(data) { 
                     var dataarray = JSON.parse(data);
                      var dataarray0 = dataarray['data'];
                     for(var key in dataarray0) {
   
                      var getrow = "<tr class='worksheet' data-id='"+dataarray0[key]['id']+"'><td class='delete' ><span class='btn glyphicon glyphicon-trash'></span></td><td>Start date: <input type='text' class='hasDatepicker pl_start_date' placeholder='yyyy-mm-dd'  name='pl_start_date' value='"+dataarray0[key]['startdate']+"'></td><td>End date: <input type='text'  class='hasDatepicker pl_end_date' placeholder='yyyy-mm-dd' name='pl_end_date' value='"+dataarray0[key]['enddate']+"'></td></tr>";
                      pldate = pldate +getrow;
   
                    }

  pldate0= "<tr class='template' data-id=''><td class='delete' ><span class='btn glyphicon glyphicon-trash'></span></td><td>Start date: <input type='text' class='hasDatepicker pl_start_date' placeholder='yyyy-mm-dd'  name='pl_start_date'></td><td>End date: <input type='text'  class='hasDatepicker pl_end_date' placeholder='yyyy-mm-dd' name='pl_end_date'></td></tr>";
    
             pldate = pldate +pldate0+ '</tbody></table><br /><div class="addRow btn btn-primary">Add Row</div>';    

    });

Sunday, June 21, 2015

Bootstrap Datepicker on change firing twice or three times




I used Bootstrap Datepicker
  $('.hasDatepicker').on('change', function(){
   }); 
 Bootstrap Datepicker fired three times. After I change it to
   $('.hasDatepicker').datepicker().on('change', function(){
   });
 Bootstrap Datepicker fired twice.

Solution 1
change
   $('#ROFRmail .modal-body .hasDatepicker').datepicker({ minDate: 0}).on('change', function(){
to
 $('#ROFRmail .modal-body').on('change', '.hasDatepicker', function(){

As when I add row, I did not have .hasDatepicker row.
Solution 2


Get global variable count and check if equal to 0 then execute Your function.
var count=0;
     $( "#Id" ).datepicker({ minDate: 0}).on('change',function (){
            if(count==0) 
           validity();//any function
           count=1;
         });
     validity(){ count=0;}
My code: use count=0 in .post to wait for ajax post post feedback to update id in div for next post
                      $('#ROFRmail .modal-body .hasDatepicker').datepicker({ minDate: 0}).on('change', function(){


                                      var row1=$(this).parents('tr');
                                      var pl_id =  row1.attr('data-id');
                                     var startdate = row1.find('.pl_start_date').val();

                                     var enddate = row1.find('.pl_end_date').val();
                                        $(this).attr('disabled','disabled');
 var postdata = {funct: 'UpdateROFRpl', pl_id:pl_id,sid:sid,  coursename:coursename, startdate:startdate,enddate:enddate};
                                                         var url = '../_ajaxParts/ROFR/SITAROFR_list.php';
                                                    if(count==0){
                                                         $.post(url, postdata, function(data) {
                                                            row1.attr('data-id',data);
                                                            count =0;
                                                            row1.find('.hasDatepicker').removeAttr('disabled');
                               });
                               }
                                 count=1;

                           });

Friday, June 19, 2015

A script on this page may be busy firefox jquery


In Firefox, when I loaded a page, it showed ""A script on this page may be busy, or it may have stopped responding. You can stop the script now, or you can continue to see if the script will complete." I need to click continue or stop. To fix this unresponsive  script:
1) In the address bar, type about:config and press Enter.
 about:config
2)  Click I'll be careful, I promise! to continue to the about:config page.
3)  search for the preference dom.max_script_run_time, and double-click on it. In the Enter integer value prompt,
change 10  to 40.
4) Press OK.

Wednesday, June 17, 2015

JavaScript, simple alert dialog callback




In java Script, when we create alert box and click OK, we hope some actions are performed.
The Modal dialog box, jquery dialog box and bootbox dialog box have similar features.
But the following codes are simplest:

for example, a table with a column with delete icon:
<tr class='template'><td class='delete' ><span class='btn glyphicon glyphicon-trash'></span></td></tr>
After clicking delete ico, this row is deleted after click ok in alert box:
 $('td.delete').on('click', function(){
                 var answer = confirm("Are you sure to delete this row?");
                if (answer)
                $(this).parents('tr').remove();
                                                         
   }); 

 

Tuesday, June 16, 2015

Pass data via attribute in JavaScript




 We create a data attribute sid (you can change to any name) and assign it value 3456
<tr><td class='sid' id='firstname' data-sid='3456'></td> </tr>
Below is the script to click this cell to display this value using jQuery:
     $('.sid').on('click',  function(){
                     var $tr = $(this).parents('tr');
                     var sid = $tr.find('#firstname').attr('data-sid');

                    alert(sid);
        });

Monday, June 15, 2015

JavaScript email validation




JavaScript regular email validation:
 function validateRegularEmail(email) {
  var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return regex.test(email);
}

JavaScript gmail validation:
 function validateGmail(email) {
    //Gmail required: %@gamil.com

    var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
    if (re.test(email)) {
        if (email.indexOf('@gmail.com', email.length - '@gmail.com'.length) !== -1) {
            return true;
        } else {
            bootbox.alert('Please enter Gmailaddress.');
        }
    } else {
        bootbox.alert('Please enter Gmail  address.');
    }
}


To use this function:
testmail ='test@htomail.com';
if(!validateRegularEmail(testmail)) alert('Wrong email adress');

JavaScript: add days to current date



Below is JavaScript: to add days to current date:
                      var someDate = new Date();
//11 days are added in current date
                     someDate.setDate(someDate.getDate() + 11);
                     var dateFormated = someDate.toDateString();
                     alert(dateFormated);

 The result will be like
Fri June 26 2015

Creating multiline strings in JavaScript


For a long strings, if you use return key in text editor for javascript, you may encounter an error for example:
var s1= 'test
 This is another line';

We can use \ in at the end of each line to create a multiline string  such as
var s1= 'test \
 This is another line';

We can also use string concatenation (better)
var s1= 'test'+
 'This is another line';

Rendering HTML tags inside textarea




In textarea
  var $mailform = $('<textarea id="textbody"><textarea>');
   $mailform.find('#textbody').html("Dear <br />, This is advised that...");
We found html tags br is not rendered.

To sovle this problem, we make a div editable
  var $mailform = $('<div id="textbody" class="editable"><div>');
   $mailform.find('#textbody').html("Dear <br />, This is advised that...");
   $('.editable').each(function(){
                 this.contentEditable = true;
    });

Now this div has same feature as textarea.

Sunday, June 14, 2015

Javascrpt dialog box using bootbox




Bootbox.js is a small JavaScript library which allows you to create programmatic dialog boxes using Bootstrap modals

Bootbox.js can be downloaded from:
http://bootboxjs.com/

Example of bootbox to creat cancel and OK dialog button
<script type='text/javascript' id='' src='bootstrap.min.js'></script>
<script type='text/javascript' id='' src='bootbox.min.js'></script>

      bootbox.dialog({
                                        message: "Are you sure you want to send out ROFR?",
                                        buttons: {
                                                cancel: {
                                                        label: "Cancel",
                                                        className: "btn-default btn-sm",
                                                        callback: function() {
                                                           // $('#mail').modal('show');
                                                        }
                                                },
                                                OK: {
                                                        label: "OK",
                                                        className: "btn-warning btn-sm",
                                                        callback: function() {
                                                            var postdata = {};
                                                            var url = ' ';
                                                                $.post(url, postdata, function(data) {
                                                   $("div#notice").html('mail is sent.');
                                       $("div#notice").css('display', 'block');
                                                           $("div#notice").fadeOut(5000);
                                                });

                                                        }
                                                },

                                        }
       });

Install, Start / Stop / Restart Postfix Mail Server in Linux




You can  install postfix mail server in Linux using yum:
sudo yum -y install postfix
Postfix mail config file
   /etc/postfix/main.cf

To Start / Stop / Restart Postfix Mail Server in Linux:
  sudo service postfix start
  sudo service postfix stop
  sudo service postfix restart

 
 
To cehck if postfix is tarted:
  sudo postfix status
You will get the following message it it is tarted:
 postfix/postfix-script: the Postfix mail system is running: PID: 2357

Linux mail command prompt help




mail is a simple  email client command line in Linux.
Type mail in shell
h
list all email with only headers,  this is also the way to go back main menu
z to next screen.
type number to read message
type h to return to main menu
? for help
list to list command
Mail Command               Description
-------------------------  --------------------------------------------
t [message list]           type message(s).
n                          goto and type next message.
e [message list]           edit message(s).
f [message list]           give head lines of messages.
d [message list]           delete message(s).
s [message list] <file>    append message(s) to file.
u [message list]           undelete message(s).
R [message list]           reply to message sender(s).
r [message list]           reply to message sender(s) and all recipients.
p [message list]           print message list.
pre [message list]         make messages go back to /var/mail.
m <recipient list>         mail to specific recipient(s).
q                          quit, saving unresolved messages in mbox.
x                          quit, do not remove system mailbox.
h                          print out active message headers.
!                          shell escape.
| [msglist] command        pipe message(s) to shell command.
pi [msglist] command       pipe message(s) to shell command.
cd [directory]             chdir to directory or home if none given
fi <file>                  switch to file (%=system inbox, %user=user's
                           system inbox).  + searches in your folder
                           directory for the file.
set variable[=value]       set Mail variable.

Wednesday, June 10, 2015

Parse JSON in JavaScript





In PHP, I used
        $message['success'] = "Personal Information Updated";
        echo json_encode($message);

to pass $message to Javascript .post
    $.post('stakeholderInfo.php', $(".box#stakeholderInfo div #editInfoForm").serialize(), function(jsonMessage) {       
                            obj = JSON.parse(jsonMessage);
                            alert(obj['success']);
                 
                });


 Here I used JSON.parse to  parse JSON in JavaScript, then display message   alert(obj['success']);

Friday, June 5, 2015

increase mysql query speed




If want to increase mysql query speed, you need to create a primary key for your table, and also add the columns you want to search as index.

Tuesday, June 2, 2015

PHPExcel keep leading 0s in number




In EXCEL columns from PHPExcel, I want to display number 2 as 0002.
After setting the cell value, 
For cell F1:
$objPHPExcel->getActiveSheet()->getStyle('F1')
->getNumberFormat()->setFormatCode('0000');
For cell F1 to F1000:
$objPHPExcel->getActiveSheet()->getStyle('F1:F1000')
->getNumberFormat()->setFormatCode('0000');
 
To get all columns align left
 
$objPHPExcel->getActiveSheet()->getDefaultStyle()
->getAlignment()
->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
 
For cell F1 to F1000 align left:
$objPHPExcel->getActiveSheet()->getStyle('F1:F1000')
 ->getAlignment()
 ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);