Tuesday, November 15, 2016

PHP null compare to 0




When PHP gets null from MySQL NULL column and compare to 0
     $ChairRecomStep_arr = array(0,0.5,1,1.5,2);
        $AdditionStepOrder =  $AdditionStepOrder.'</select>';

            $ChairRecomStep =   '<select name="ChairRecomStep" class="ChairRecomStep"><option value="">Select</option>';
         foreach($ChairRecomStep_arr  as $row0){
                    $select=' ';
                    if($row['ChairRecomStep']== $row0) $select='selected';
            $ChairRecomStep =  $ChairRecomStep.'<option value="'.$row0.'" '.$select.'>'.
            $row0.'</option> ';

         }
        $ChairRecomStep =  $ChairRecomStep.'</select>';

In this code, null compare to 0 is true, the select dropdwon pickup 0 value instead of empty.
To make null compare to 0 is false, we should use = = =
   if($row['ChairRecomStep']=== $row0) 

Also when we use empty function in PHP, the 0 also treated as  empty. To avoid 0 treated as empty:
      if(empty($ChairRecomStep) && $ChairRecomStep!=0) $ChairRecomStep=null;
 

Friday, May 13, 2016

Use Bootstrap Glyphicon for icons in text, buttons, toolbars, navigation, or forms





We can use Bootstrap Glyphicon for icons in  text, buttons, toolbars, navigation, or forms :
as long as we have Bootstrap library

Example, comment icon


<span class='glyphicon glyphicon-comment'></span>

And more examples

<p>Envelope icon: <span class="glyphicon glyphicon-envelope"></span></p>
<p>Search icon: <span class="glyphicon glyphicon-search"></span></p>
<p>Print icon: <span class="glyphicon glyphicon-print"></span></p>
 
Reference:

Thursday, May 12, 2016

jQuery, prevent many click fireup





Use jQuery function die to prevent many clicks fire at the same time:
example
                $('#popup_9sp .modal-body .delete').die('click');    
                $('#popup_9sp .modal-body .delete').live('click', function(){
              
                        var id = $(this).parents('tr').attr('data-id');
                        var answer = confirm("Are you sure to delete this row?")
                        if(id>0 && answer){
                          
                              $('#tab1').find('.cid'+id).remove();
                        
                        }        
                        var postdata = {funct: 'DeleteCourse', id:id};
                        var url = '../_ajaxParts/preplanning/preplanning_summary.php';

                        if(id>0 && answer){
                            $.post(url, postdata, function(data) {
                                if(data=='fail')
                                    $("div#notice").html('Delete failed!');
                                else{    
                                    $("div#notice").html('Delete successfully.');
                                }
                                                                                
                                $("div#notice").css('display', 'block');
                                $("div#notice").fadeOut(15000);
                            });
                        }                      
                        if (answer)
                            $(this).parents('tr').css('display','none');
                    });
                  
      

            });

jQuery autocomplete scroll bar for dropdown menu




jQuery autocomplete scroll bar for dropdown menu
add following CSS style:
<style>
.ui-autocomplete { height: 300px; width: 200px; overflow-y: scroll; overflow-x: hidden;}
</style>

jquery - Parse JSON with jQuery Example





jquery - Parse JSON with jQuery Example

 $.parseJSON - Takes a well-formed JSON string and returns the resulting JavaScript value.
Example:
        $.post("../_ajaxParts/preplanning/preplanning.php", {
            funct: 'getPrePlanning',
            stakeholder_id:stakeholder_id,
            pad_id:pad_id,
             site:site,          
        }, function(data) {
             formattedJson= $.parseJSON(data);
             formatPrePlanningBox(formattedJson)
        });


 In preplanning.php, we use json_encode to convert to json format.
<?php
 if($_POST['funct'] == "getPrePlanning") {

    $preplanning = new  preplanning();
    $model =  new PreplanningSummaryModel();
    $pad_id =$_POST['pad_id'];
    $total_semester= $model->get_total_semester($pad_id);
    $coursepre_choice= $model->get_coursepre_choice($pad_id);  
    $data = $preplanning->getPrePlanning($_POST);
    $CoursePre = $preplanning->getCoursePre($_POST);
    $arrayForJSON = array("count" => count($data),  "coursepre_choice" => $coursepre_choice, "total_semester" => $total_semester,  "data" => $data, "CoursePre" => $CoursePre);
    echo json_encode($arrayForJSON);
}

?>

PHPExcel using excel template, increase PHP memory




PHPExcel using excel template:
               $file_path = $_SERVER['DOCUMENT_ROOT'].'/uploads/IAA/IAAtemplate.xlsx';
                $objReader = PHPExcel_IOFactory::createReader('Excel2007');

                $objPHPExcel = $objReader->load($file_path);

        ini_set('zlib.output_compression','Off');
         ob_end_clean();
            header("Pragma: public");
            header("Expires: 0");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Content-Type: application/force-download");
            header("Content-Type: application/octet-stream");

              header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8');
                $filename = $termFilter."-IAA-".$dept_abbrname."-".date("Ymd").".xlsx";
                header('Content-Disposition: attachment; filename= "'.$filename.'"');
            header("Content-Transfer-Encoding: binary");

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
                $objWriter->save('php://output');



This will  take more memory than using without template If you produce  a large
excel file, you may see error: "File not Found" or "Connection reset error".


To fix this: add
         set_time_limit(1000000);
         ini_set("max_input_time", 60000);
         ini_set("memory_limit",-1);

ini_set("memory_limit",-1); will remove PHP  memory limit and will fix memory problem

Tuesday, May 10, 2016

jquery bind paste to get paste content





Below is the code for  jquery bind  paste to get paste content
        $('.coursepre').bind('paste', function(e) {
                //remove placeholder to make sure placeholder not mess with paste text
                $(this).attr("placeholder", "");

              //using setTimeout to get paste text
                 setTimeout(function ()
                {

                   //use $(e.currentTarget) to replace $(this) in paste
                    curname= $(e.currentTarget).val();
                    parent = $(e.currentTarget).parent();   
                     preid =  $(e.currentTarget).attr('data-preid');
                    saveBasicPre(curname, parent, stakeholder_id,pad_id,preid);           
               },0);                   
        });


We can use also add paste in jQuery  on  function
                $('#popup_9sp').on("keydown.autocomplete, paste",".course",function(e){
                $(this).autocomplete({              
                        //    autoFocus: true,
                    source: "../_ajaxParts/preplanning/preplanning.php?funct=courselist",
                    minLength : 2,

                    select : function(event, ui) {

                        $(this).val(ui.item.label);
                        newname = ui.item.value;
                        newvalue = ui.item.label;
                        checked = false;
                        parent = $(this).parent();
                        type='select';
                        campus = parent.find('.campus').val();
                        id =  $(this).parent().parent().attr('data-id');  
                      

              
                          managerttr=1;
                              
                          
                        saveBasicInfo1(row0,type,newvalue, parent, campus, id,sid,term, newname, managerttr,pad_id);

                    },
                    open : function() {
                       // $("#instructorname").attr('data-sid', 0);
                    },

                    change : function() {   
                            curname = $(this).val();
                            parent = $(this).parent();
                            type='change'
                            campus = parent.find('.campus').val();
                            id =  $(this).parent().parent().attr('data-id');
                                                  
                             newname=$('#tab1').find('.cid'+id).html();
                              managerttr=1;
              
                            if(curname.trim()!= newname) {
                                saveBasicInfo1(row0,type,curname, parent, campus, id,sid,term,newname,managerttr,pad_id);
                                //$(this).val(newname);
                             }
                    }
                    }).focus(function(){
                    //    $(this).autocomplete('search');
                        oldname=$(this).val();
                    });
                });              
              
                $('#popup_9sp .modal-body select.ttr, input.comment').die('change');
                $('#popup_9sp .modal-body select.ttr, input.comment').live('change', function(){  
                     row0.find('.ttrpattern').html($(this).val());
                     row0.find('.ttrpattern').attr('data-ttr',$(this).val());
                     row0.parent().find('.term').attr('data-ttr',$(this).val());
                     $td=row0;
                    if($(this).val()=='SL' || $(this).val()=='L'){
                        $td.find('.SLdate').html('');
                        $td.removeClass('teachingCell');  
                        $td.removeClass('researchCell');          
                        $td.addClass('leaveCell');
                        $(this).parent().find('.SLdate').hide();   
                        $td.find('.cidlist').hide();                          
                    }else if($(this).val()=='Research'){
                        $td.removeClass('leaveCell');  
                        $td.removeClass('teachingCell');
                        $td.addClass('researchCell');  
                         $(this).parent().find('.SLdate').hide();                      
                        $td.find('.cidlist').hide();  
                    }else if($(this).val()=='Teaching'){
                        $td.removeClass('leaveCell');  
                        $td.removeClass('researchCell');              
                        $td.addClass('teachingCell');
                         $(this).parent().find('.SLdate').show();   
                        $td.find('.cidlist').show();                        
                      
                    }else{
                        $td.removeClass('teachingCell');  
                        $td.removeClass('researchCell');          
                        $td.removeClass('leaveCell');  
                        $td.find('.cidlist').hide();  
                         $(this).parent().find('.SLdate').hide();   
                    }
                     ttrnew =     $(this).val();              
                    $.post("../_ajaxParts/preplanning/preplanning_summary.php", {
                            funct: 'savettrRevisedTerm',
                            ttrRevised:ttrnew,
                            stakeholder_id:sid,
                            pad_id:pad_id,
                            term: term
                    }, function(data) {
                        if(data=='fail')
                            $("div#notice").html('Updated failed!');
                        else        
                            $("div#notice").html('Updated successfully.');
                        $("div#notice").fadeIn();      
                        $("div#notice").fadeOut(5000);  
                     

                    });                  
                });  
                            

Wednesday, March 9, 2016

jQuery, loop over all rows in a table



jQuery, loop over all rows in a table
For example, row is current row, I want to loop over all the rows in jQuery
                               row.parent().find("tr").each(function(index) {
                                 alert(index);
                                });

Saturday, March 5, 2016

Knockout JS Video tutorial - The Basic for beginner




Knockout JS Video tutorial - The Basic for beginner

Reference:
 http://www.knockmeout.net/
 http://learn.knockoutjs.com/#/?tutorial=intro
 http://knockoutjs.com/
 https://www.youtube.com/watch?v=a108oDs39Ss

Thursday, February 25, 2016

Use return instead of exit in Javascript





In PHP, we use exit function to exit a loop.  We should not use exit in Javascrip.
The following  statement in JS is wrong
        if(fromTUG_id==null || fromTUG_id==undefined ||fromTUG_id==0) {
         exit;
          }

We should use return instead:
        if(fromTUG_id==null || fromTUG_id==undefined ||fromTUG_id==0) {
         return;          

       }

PHP - Comparing String to Integer gives strange results




I have url
SITAview_pdf.php?&guide=wk
In PHP, I have
 $guide = $_GET['guide'];
When I tried to compare 0=='wk', the statement  is true!

From PHP manual:

String conversion to numbers
When a string is evaluated in a numeric context, the resulting value and type are determined as follows.
The string will be evaluated as a float if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will be evaluated as an integer.
The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

We can  use triple equals instead of a double equals. This ensures that what you are comparing is a string that contains the digit zero only, and prevents any type conversion.
such as 0==='wk'
For simplify code, I used
SITAview_pdf.php?&guide=3
to fix the problem

Saturday, February 13, 2016

Allow popup windows in Firefox



A lot of applications, you need to popup a pdf file when you click a link. In Firefox, the default is  block pop-up windows. To allow popup in Firefox

 1) Click open menu button at right corner of Firefox
2) In the popup menu, click content at right menu
3) Uncheck block pop-up  windows

Wednesday, February 3, 2016

Difference between dot and space in CSS



What is difference between
#tab1 a { text-decoration: underline; }
and
#tab.a { text-decoration: underline; }

#tab1 a { text-decoration: underline; }
<div id='tab1'><a>test</a><a>test1</a></div>
put all  underline for link under id tab1

#tab.a { text-decoration: underline; }
<a id='tab1'>test</a>
 Select link with id tab1 as underline

To remove underline
#tab.a { text-decoration: none; }

Thursday, January 21, 2016

jQuery remove data attribute and add data attribute



Suppose we have data attribute id, value 76
<tr class="worksheet" data-id="76"></tr>
To remove data attribute id in  jQuery
         $('.worksheet').removeData("id");
To add data attribute id in  jQuery
       $('.worksheet').attr("data-id",""); 
  Get value:
   $('.worksheet').data("id");
 Set value
   $('.worksheet').data("id",""); 
  For some reason set value not working well, I use remove data attribute and add data attribute instead.

Tuesday, January 19, 2016

disabled input in jQuery serializeArray();




If an input has attribute disabled, it will not be included in   jQuery serializeArray();
To make it included in jQuery serializeArray(),  we first make it enabled and disabled again
 Example
                var disabled_attr =$('#instructorname').attr("disabled");
                if(disabled_attr=='disabled') $('#instructorname').removeAttr("disabled");
                var postData = $("form").serializeArray();
                if(disabled_attr=='disabled')  $("#instructorname").prop("disabled", true);

To get serializeArray into post bvalue
         dataObj = {};
         for (i=0; i<len; i++) {
           dataObj[postData[i].name] = postData[i].value;
         }

Add more value, some of them from url get
                postData.push({
                        name: "funct",
                        value: "saveGuidelineInfo"
                }, {
                        name: "sid",
                        value: $.url.param('sid')
                },{
                        name: "term",
                        value: $.url.param('term')
                },{
                        name: "instr_section",
                        value: $.url.param('instr_section')
                },{
                        name: "cid",
                        value: $.url.param('cid')
                },{
                        name: "pad_id",
                        value: $.url.param('pad_id')
                }
                );

Final post data
              $.post("../_ajaxParts/TA/SITAContractView.php", postData, function(data) {
                        formatJson(data, 'div#notice', null);
                           });

Monday, January 11, 2016

$(document).on('click', check which class is clicked for multiple classes




For example, jquery, click:
 $(document).on('click',  '.sendmail00, .sendmailq',function(){
I want to check which class is clicked? .sendmail00 or .sendmailq?
We can check its parent to contain this class or not.
Examples, suppose both of classes have parents td,
    $(document).on('click',  '.sendmail00, .sendmailq',function(){
                     var $td = $(this).parents('td');

      if($td.find('.sendmailq').html()==null ||$td.find('.sendmailq').html()==undefined)  
        alert('Not contain class  .sendmailq');
      else
        alert('Contain class  .sendmailq');
 });

click on box, but not a link in the box, jquery



I have link inside a box
<div class='term'><a href='#'' class='link'>My Link</a></div>
I have click on class term. When I click the link, I want the class 'term' not trigger a click.
used:
              if (event.target.nodeName == 'A') 
Example:
            $('.term').on('click',  function(event){
              if (event.target.nodeName == 'A') return true;

          } 
 Another method:
 e.stopPropagation();
Example 
$('.term a').click( function(e) {
    e.stopPropagation();
});
Reference:
http://stackoverflow.com/questions/3838758/select-the-div-but-not-the-link-inside-it-jquery-question 

Saturday, January 9, 2016

$(document).ready(function() {}); and $(function() {});



What does "$(function(data){"  mean  in jQuery?
It is the same as $(document).ready(function () {
  • $(document).ready(function() {});
  • $(function() {});
The two statements are actually the exact same. So the second call is just a shortcut for the first.

Wednesday, January 6, 2016

php, escape quotes in html input value



In form
 <input type="text" name="firstname" value="<?php echo $_POST['firstname']; ?>" />
You may find if  

$_POST['firstname']=O'test may not work.
We need to use  htmlspecialchars or  htmlentities()

But we need to use  ENT_QUOTES to esacpe single, i.e.
 htmlspecialchars($_POST['firstname'],ENT_QUOTES) 

More about htmlspecialchars:
  • '&' (ampersand) becomes '&amp;'
  • '"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.
  • "'" (single quote) becomes '&#039;' (or &apos;) only when ENT_QUOTES is set.
  • '<' (less than) becomes '&lt;'
  • '>' (greater than) becomes '&gt;'