Important Notes

Following are the some important coding regarding notes that will help you in website developing.

Headings:
  • How to check error in PDO (Sql query)
  • How to set default value in datepicker
  • How to populate google address
  • SET datetime using js
  • Select Onchange function for show and hide
  • Click on checkbox and if its checked show Div otherwise hide Div
  • Set Currency Format (on blur event)
  • Set Phone formatting: (555) 555-5555 (On keyup event)
  • Post form data including file upload using Ajax
  • Function for POST data using Ajax

Important notes


How to check error in PDO (Sql query): 

$wcquery->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );

print_r($wcquery->errorInfo());

How to set default value in datepicker:

Note: Date format should be checked because its not accept all date format

Using Js:

$("input[type=date]").datepicker(

    "setDate", "<?php echo date('Y-m-d')"
);

Date format:

if(!empty($result['invoice_date']) && $result['invoice_date'] != "0000-00-00") {
              $invoice_date = date("n/j/Y", strtotime($result['invoice_date']));
 }

<input type="text" id="upinvoice_date" class="form-control" value="<?php echo $invoice_date; ?>'">

Here are some examples of date format and result output

F j, Y g:i a - November 6, 2010 12:50 am
F j, Y - November 6, 2010
F, Y - November, 2010
g:i a - 12:50 am
g:i:s a - 12:50:48 am
l, F jS, Y - Saturday, November 6th, 2010
M j, Y @ G:i - Nov 6, 2010 @ 0:50
Y/m/d \a\t g:i A - 2010/11/06 at 12:50 AM
Y/m/d \a\t g:ia - 2010/11/06 at 12:50am
Y/m/d g:i:s A - 2010/11/06 12:50:48 AM
Y/m/d - 2010/11/06

date("n/j/Y", strtotime($datevalue));

How to populate google address:

HTML CODE:

<div class="form-group">
    <label class="control-label col-sm-4" for="prop_address"> Property Address:</label>
<input id="autocomplete" name="prop_address" size="30" placeholder="Enter your address" onFocus="geolocate()" type="text"></input>
  </div>
<input type="hidden" name="latitude" id="latitude"></input>
<input type="hidden" name="longitude" id="longitude"></input>
<input type="hidden" name="street_number" id="street_number"></input>
    <input type="hidden" name="route" id="route"></input>
<input type="hidden" name="prop_county" size="30" id="administrative_area_level_2"></input>

  <div class="form-group">
    <label class="control-label col-sm-4" for="prop_city">City:</label>
<input type="text" name="prop_city" size="30" id="locality"/>
  </div>

  <div class="form-group">
    <label class="control-label col-sm-4" for="prop_state">State: </label>
    <input type="text" name="prop_state" size="30" id="administrative_area_level_1"></input>
  </div>
  <div class="form-group">
    <label class="control-label col-sm-4" for="prop_zip">ZIP:</label>
    <input type="text" name="prop_zip" size="30" id="postal_code"></input>

  </div>

js code:

<script>
 var placeSearch, autocomplete, autocomplete_mail;
      var componentForm = {
street_number: 'short_name',
        route: 'long_name',
        locality: 'long_name',
        administrative_area_level_1: 'short_name',
administrative_area_level_2: 'short_name',
        postal_code: 'short_name'
      };

      function initAutocomplete() {
        autocomplete = new google.maps.places.Autocomplete(
            /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
            {types: ['geocode']});
        autocomplete.addListener('place_changed', fillInAddress);

autocomplete_mail = new google.maps.places.Autocomplete(
            /** @type {!HTMLInputElement} */(document.getElementById('autocomplete_mail')),
            {types: ['geocode']});
        autocomplete_mail.addListener('place_changed', fillInAddress_mail);
      }

      function fillInAddress() {
        // Get the place details from the autocomplete object.
        var place = autocomplete.getPlace();

        for (var component in componentForm) {
          document.getElementById(component).value = '';
          document.getElementById(component).removeAttribute('readonly');
        }

        // Get each component of the address from the place details
        // and fill the corresponding field on the form.
        for (var i = 0; i < place.address_components.length; i++) {
          var addressType = place.address_components[i].types[0];
          if (componentForm[addressType]) {
            var val = place.address_components[i][componentForm[addressType]];
            document.getElementById(addressType).value = val;
          }
        }
  var st_value = document.getElementById('street_number').value+' '+document.getElementById('route').value;
   document.getElementById('autocomplete').value = st_value;
   document.getElementById('latitude').value = place.geometry.location.lat();
         document.getElementById('longitude').value = place.geometry.location.lng();

      }

      // Bias the autocomplete object to the user's geographical location,
      // as supplied by the browser's 'navigator.geolocation' object.
      function geolocate() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var geolocation = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };
            var circle = new google.maps.Circle({
              center: geolocation,
              radius: position.coords.accuracy
            });
            autocomplete.setBounds(circle.getBounds());
          });
        }
      }

    </script>

    <script src="https://maps.googleapis.com/maps/api/js?key=Addkeyhere&libraries=places&callback=initAutocomplete"
        async defer></script>

SET datetime using js <input type="datetime-local" name="manual_added_datetime" id="manual_added_datetime"> var now = new Date(); var utcString = now.toISOString().substring(0,19); var year = now.getFullYear(); var month = now.getMonth() + 1; var day = now.getDate(); var hour = now.getHours(); var minute = now.getMinutes(); var second = now.getSeconds(); var localDatetime = year + "-" + (month < 10 ? "0" + month.toString() : month) + "-" + (day < 10 ? "0" + day.toString() : day) + "T" + (hour < 10 ? "0" + hour.toString() : hour) + ":" + (minute < 10 ? "0" + minute.toString() : minute) + utcString.substring(16,19); var datetimeField = document.getElementById("manual_added_datetime"); datetimeField.value = localDatetime;

Select Onchange function for show and hide: $('#primary_contact').on('change', function() { if(this.value == "other") { $("#primaryname").show(); }else{ $("#primaryname").hide(); } }); Click on checkbox and if its checked show Div otherwise hide Div: $("#twoInsured").click(function () { if ($(this).is(":checked")) { $("#divSecondInsured").show(); } else { $("#divSecondInsured").hide(); } }); Curency Format: document.getElementById("dwelling_coverage").onblur =function (){ this.value = parseFloat(this.value.replace(/,/g, "")) .toFixed(2) .toString() .replace(/\B(?=(\d{3})+(?!\d))/g, ","); if(this.value == 'NaN') { this.value = ''; } }
// Phone formatting: (555) 555-5555
$('input[type="tel"]').on("keyup paste", function(event) { // Don't run for backspace key entry, otherwise it bugs out if(event.which != 8){ // Remove invalid chars from the input var input = this.value.replace(/[^0-9\(\)\s\-]/g, ""); var inputlen = input.length; // Get just the numbers in the input var numbers = this.value.replace(/\D/g,''); var numberslen = numbers.length; // Value to store the masked input var newval = ""; // Loop through the existing numbers and apply the mask for(var i=0;i<numberslen;i++){ if(i==0) newval="("+numbers[i]; else if(i==2) newval+=numbers[i]+") "; else if(i==6) newval+="-"+numbers[i]; else newval+=numbers[i]; } // Re-add the non-digit characters to the end of the input that the user entered and that match the mask. if(inputlen>=1&&numberslen==0&&input[0]=="(") newval="("; else if(inputlen>=5&&numberslen==3&&input[4]==")") newval+=""; else if(inputlen>=6&&numberslen==3&&input[5]==" ") newval+=""; else if(inputlen>=10&&numberslen==6&&input[9]=="-") newval+="-"; $(this).val(newval.substring(0,14)); } }); Post form data including file upload using Ajax: <script> function uploaddoc() { var bar = $('#bar'); var updaterIDD = $("#updaterIDD").val(); var uname = $("#username").val(); var pcuserid = $("#docclientid").val(); var doctype = $("#doctype").val(); var andy_estimate_amt = $("#andy_estimate_amt").val(); var fd = new FormData(); var file_data = $("#clientdoc")[0].files; // for multiple files if(file_data.length > 0) { file =file_data[0]; fd.append("clientcontract", file); } fd.append("userid",pcuserid); fd.append("doctype",doctype); fd.append("updaterId",updaterIDD); fd.append("updatername",uname); fd.append("andyestimateamt",andy_estimate_amt); $.ajax({ url: 'ajax/docs_upload.php', type: 'POST', data: fd, cache: false, processData: false, // Don't process the files contentType: false, // Set content type to false as jQuery will tell the server its a query string request xhr : function () { var jqXHR = null; if ( window.ActiveXObject ) { jqXHR = new window.ActiveXObject( "Microsoft.XMLHTTP" ); } else { jqXHR = new window.XMLHttpRequest(); } //Upload progress jqXHR.upload.addEventListener( "progress", function ( evt ) { if ( evt.lengthComputable ) { var percentComplete = Math.round( (evt.loaded * 100) / evt.total ); var percentVal = percentComplete + '%'; bar.width(percentVal); bar.html(percentVal); } }, false ); return jqXHR; }, success: function(data, textStatus, jqXHR) { if(typeof data.error === 'undefined') { alert(data); $("#upload_docs_modal").modal("hide"); location.reload(true); } else { // Handle errors here console.log('ERRORS: ' + data.error); } }, error: function(jqXHR, textStatus, errorThrown) { // Handle errors here console.log('ERRORS: ' + textStatus); // STOP LOADING SPINNER } }); } </script> Function for POST data using Ajax: <script> function updateinfo() { // Add record if($("#twoInsured").prop('checked') == true){ var twoInsured = $('#twoInsured:checked').val(); }else{ var twoInsured = '0'; } $.post("ajax/updatecontactinfo.php", { uuid: $("#ad_uid").val(), fname: $("#fname").val(), lname: $("#lname").val(), twoInsured: twoInsured, }, function (data, status) { if(data != "Success") { alert(data); } else { $("#update_contact_info_modal").modal("hide"); location.reload(true); } }); } </script>

Post a Comment

0 Comments