Tuesday, October 29, 2013

Jquery Validate Dynamic Form

Scenario:

In a html page, there are button and a div (newFormDiv), when user click the button, it will call up an ajax function to write a new form (commentForm) in div newFormDiv. in the new form, user will input something in artPlaceName, the length must be bigger than 1.

index.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                     "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
   <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
   <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
   <script src="formajax.js"></script>
</head>
<body>
<div id="textarea">
This is a text area.
</div>
<div id="buttonarea">
<button>Create New Form</button>
</div>
<div id="newFormDiv">
This is new form area.
</div>
</body>
</html>

futureForm.php


<?php
echo '
  <form id="commentForm" method="get" action="">
      <input id="artPlaceName" name="artPlaceName" size="25" />
      <input type="submit"/>
  </form>
';


formajax.js


$(document).ready(function () {
        function createNewForm() {
        $.ajax({
            url: 'futureForm.php',
            success: function (data) { // crude simulation of ajax load
                $('#newFormDiv').html(data);
            },
            complete: function () {
                $('#commentForm').validate({ // initialize the plugin
                    rules:{
                        artPlaceName:
                            {
                                required: true,
                                minlength: 2
                            }

                    },
        messages:{
            artPlaceName:
                        {
                            required: "<li>Please enter a name.</li>",
                            minlength: "<li>Your name is not long enough.</li>"
                        }
                    }
                });
            }
        });
    };

    $('button').click(function () {
        createNewForm();
    });

});

Thursday, October 3, 2013

AWK to extract IP address, Mac Address and Netmask

Scenario:
Use ifconfi and awk/gawk to extract network information.

For Linux:
Usage: ifconfig | awk -f linuxNICParser.awk

linuxNICParser.awk

BEGIN {
  FS = "\n"
}
{
      # nics[1,1]:nicName, [1,2]:macAddress, [1,3]:ipAddress, [1,4]:netMask
      newNicLine = "[A-Za-z].*encap.*"
      ipLine = ".*inet.*"
      zeroLine = $0
      isFirstSection = 1
      nicCount = 0
      newSec = match(zeroLine, newNicLine)
      if (newSec) {
        split (zeroLine, variableArray, " ")
        nicName = variableArray[1]
      # ignore loop nic
        if ( ! match(nicName, "lo*") ) {
          nicCount = nicCount + 1
          nics[nicCount,1] = nicName
          nics[nicCount,2] = variableArray[5]
        } else
          isFirstSection = 10
      }
      while (( getline variableLine ) &gt; 0)
      {
        newSec = match(variableLine, newNicLine)
      if (newSec) {
        isFirstSection == 0
        split (variableLine, variableArray, " ")
        nicName = variableArray[1]
      # ignore loop nic
        if ( ! match(nicName, "lo*") ) {
          nicCount = nicCount + 1
          nics[nicCount,1] = nicName
          nics[nicCount,2] = variableArray[5]
        } else
          isFirstSection = 10
      }

      #ignore loop device
        if (isFirstSection == 10)
          continue

      # Get ip/net mask
      if (match(variableLine, ipLine)) {
        split (variableLine, variableArray, ":")
        split (variableArray[2], tmpArray, " ")
        nics[nicCount,3] = tmpArray[1]
        nics[nicCount,4] = variableArray[4]
      }
      }
}

END {
  for (i = 1; i &lt;= nicCount; i++) {
    print width
    for (j =1; j&lt;=4; j++) {
      print nics[i,j]
    }
  }
}

For Solaris:

Usage: ifconfig -a|gawk -f solarisNICParser.awk

solarisNICParser.awk

BEGIN {                                  
  FS = "\n"                              
}                                        
{                                        
      # nics[1,1]:nicName, [1,2]:macAddress, [1,3]:ipAddress, [1,4]:netMask
      newNicLine = "[A-Za-z].*flags.*"                                    
      ipLine = "inet*"                                                    
      macLine = "ether*"                                                  
      zeroLine = $0                                                       
      isFirstSection = 1                                                  
      nicCount = 0                                                        
      newSec = match(zeroLine, newNicLine)                                
      if (newSec) {                                                       
        split (zeroLine, variableArray, ":")                              
        nicName = variableArray[1]                                        
      # ignore loop nic                                                   
        if ( ! match(nicName, "lo*") ) {                                  
          nicCount = nicCount + 1                                         
          nics[nicCount,1] = nicName
        } else
          isFirstSection = 10
      }
      while (( getline variableLine ) > 0)
      {
        newSec = match(variableLine, newNicLine)
      if (newSec) {
        isFirstSection = 0
        split (variableLine, variableArray, " ")
        nicName = variableArray[1]
      # ignore loop nic
        if ( ! match(nicName, "lo*") ) {
          nicCount = nicCount + 1
          nics[nicCount,1] = nicName
        }
      }
      #ignore loop device
        if (isFirstSection == 10)
          continue

      # Get ip/net mask
      if (match(variableLine, ipLine)) {
        split (variableLine, variableArray, " ")
        nics[nicCount,3] = variableArray[2]
        nics[nicCount,4] = variableArray[6]
      }

      # Get mac address
      if (match(variableLine, macLine)) {
        split (variableLine, variableArray, " ")
        nics[nicCount,2] = variableArray[2]
      }
      }
}

END {
  for (i = 1; i <= nicCount; i++) {
    for (j =1; j<=4; j++) {
      print nics[i,j]
    }
  }
}

Mark Google Map with the addresses from Mysql database with PHP, jQuery, ajax and Google Map API 3.

Scenario: Mark Google Map with the addresses from Mysql database with PHP, jQuery, and ajax.

Files: map.html, gsearch.php
Database: test
Table: office

map.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Children Service Field Workers</title>
    <script type="text/javascript" src="//maps.google.com/maps/api/js?sensor=false"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <script type="text/javascript">

var infowindow, map;

function initialize() {
  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(43.8561002, -79.33701880000001),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  markLocations(map);
}

function addMarkers(latLng,map) {
  var marker = new google.maps.Marker({
            position: latLng,
            map: map
          });

          google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map, this);
          });

}
function markLocations(map) {
   var geocoder = new google.maps.Geocoder();
    //url = 'gsearch.php?q=' + $('#search').val();
    url = 'gsearch.php';
    $.getJSON(url, function(data) {
    jQuery.each(data, function(key,value) {
    geocoder.geocode( { 'address': value}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      latlng=results[0].geometry.location;
      addMarkers(latlng,map);
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
          });
    });
  };

google.maps.event.addDomListener(window, 'load', initialize);

</script>
  </head>
  <body style="font-family: Arial; border: 0 none;">
    <div id="map-canvas" style="width: 500px; height: 400px"></div>
  </body>
</html>

gsearch.php
<?php
include_once ('database_connection.php');

mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");

//$query = "select office_name,postcode from office where office_name like '%$q%' or postcode like '%$q%'";
$query = "select address,city,province,country from office";

$result = mysql_query($query);

$num=mysql_numrows($result);


mysql_close();
$response = array();

$addressitems = array("address","city","province","country");

if($result){
      while($row = mysql_fetch_array($result,MYSQLI_ASSOC)){
        $address=$row['address'];
        $city=$row['city'];
        $province=$row['province'];
        $country=$row['country'];
        $combine="";
        foreach ($addressitems as $item) {
        $temp = ${$item};
        if ($temp!="") {
          if ($combine==""){
             $combine = ${$item};
          } else {
             $combine .= ", $temp";
          }
         }
        }
        #echo $combine;
        //array_push($response,array('label'=>$row['office_name'],'value'=>$row['office_name']));
        array_push($response,$combine);
      }
    echo(json_encode($response));
    }else {
        echo 'No Results for :"'.$_POST['q'].'"';
    }

?>

MySQL SQL Script
office.sql

CREATE TABLE IF NOT EXISTS `office` (
`office_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'Event ID',
`office_name` varchar(64) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Event Name',
`country` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Province',
`province` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Province',
`city` varchar(30) COLLATE utf8_unicode_ci NOT NULL COMMENT 'City',
`address` varchar(88) COLLATE utf8_unicode_ci NOT NULL COMMENT 'address',
`postcode` char(10) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Postcode',
`gpslatitude` char(15) COLLATE utf8_unicode_ci NOT NULL COMMENT 'GPS Latitude',
`gpslongitude` char(15) COLLATE utf8_unicode_ci NOT NULL COMMENT 'GPS Longitude',
`catagory` varchar(16) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Catagory ID',
`start_date` date DEFAULT NULL COMMENT 'Starting Date',
`close_date` date DEFAULT NULL COMMENT 'Ending Date',
`Schedule` text COLLATE utf8_unicode_ci NOT NULL COMMENT 'Schedule',
`admission` char(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT 'Admission',
`Contact` char(50) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Contact',
`Phone` varchar(20) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Phone',
`Fax` char(20) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Fax',
`Email` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Email',
`Website` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'website',
`image1` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Image1',
`Image2` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Image2',
`Description` text COLLATE utf8_unicode_ci NOT NULL COMMENT 'Description',
`tags` text COLLATE utf8_unicode_ci NOT NULL COMMENT 'tags',
`Searchable` tinyint NOT NULL DEFAULT '1' COMMENT 'Searchable',
`Submitter` varchar(80) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Submitter',
PRIMARY KEY (`office_id`),
KEY `Event_Name` (`office_name`),
FULLTEXT KEY `Description` (`Description`)
);

Data file
To load the data file into the table, the file must be have 755 permission, and its parent folder must have 755 permission too. So I would suggest to put it in /tmp if you are using Unix/Linux.

Mysql> load data infile '/tmp/office.txt' into table office fields terminated by ',';

office.txt
, Downtown Toronto, Canada, Ontario, Toronto, 5 John st., M5V 5C6,,,Head Quarter,,,6am-6pm,N/A,Phy Cris, 416-333-8888,,aaa@bloger.ca,www.bloger.ca,,,Internet Marketing,IM,1,
, Downtown New York, USA, NY, New York, 8 Wall st., 10888,,,NA HQ,,,6am-6pm,N/A,Sam US, 646-333-8888,,bbb@bloger.ca,www.bloger.ca,,,Internet Marketing,IM,1,