Friday, November 25, 2016

Internal Messaging System Using PHP & Javascript

///////////////////////////////////////////////////////////////////////////////////////////////////
//// index.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<h2 align="center"  style="color:#CC33FF"> Login Verification IMS</h2>
<form id="myform" action="#" method="post" onSubmit="return checkvalidate()">
<table align="center" style="color:#FF99FF">
    <tr>
      <td><strong>Email</strong></td>
 <td><input type="text" id="useremail" name="useremail" maxlength="17" /></td>
 <td><span style="color:#FF0000" id="usernameerr"></span></td>
   </tr>
 
   <tr>
      <td><strong>Password</strong></td>
 <td><input type="password" id="userpassword" name="userpassword" maxlength="8" /></td>
 <td><span style="color:#FF0000" id="userpassworderr"></span></td>
   </tr>
 
      <tr>
   
 <td><input type="hidden" name="action" value="trans" /></td>
 <td colspan="2"><img src="img/sub.png" height="25" width="80" id="sub" name="sub" onclick="javascript:doSubmit()"/></td>

   </tr>
</table>
</form>

<?php
include("db.php");
$obj=new DB;
session_start();
if(isset($_REQUEST['logout'])){
   unset($_SESSION['username']);
   unset($_SESSION['userid']);
   header("Location:index.php");
 
}




if(isset($_REQUEST['action'])){
   $useremail=$_REQUEST['useremail'];
   $userpassword=$_REQUEST['userpassword'];
   $sql="select * from userlogin where useremail='$useremail' and password='$userpassword'";
   $results=$obj->getTable($sql);
   echo'<pre>';
   $emailid=$results[0]['useremail'];
   $name=strstr($emailid,"@",true);
   ucfirst($name);
    $_SESSION['username']=$name;
$_SESSION['userid']=$results[0]['id'];
    header("Location:dashboard.php");

 


}
?>

<script>
function doSubmit(){
alert("hi");
var form=document.forms[0];
   if(form.onsubmit){
     var flag=form.onsubmit.call(form);
     if(flag==true){
       form.submit();
     }
   }
}



function checkvalidate(){
var userpass=document.getElementById("userpassword").value;
var useremail=document.getElementById("useremail").value;


var passerr=document.getElementById("userpassworderr");
var emailerr=document.getElementById("usernameerr");



var validation =true;
var emailvalida=false;

//email validation
for(var i=0; i<useremail.length; i++){
if(useremail.charAt(i)=="@"){
 emailvalida=true;
}



}

if(emailvalida==false || useremail==""||useremail.length<8){   //if anyone is true
emailerr.innerHTML="<font color=red size=2>Enter Proper Email</font>";
validation =false
}





//name validation
if(userpass==""||userpass.length<4){   //if anyone is true
passerr.innerHTML="<font color=red size=2>Enter Proper Name</font>";
validation =false;
}



alert(validation);

return validation;
//return false;
}
</script>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End index.php
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
//// inbox.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
$leftTop="Muna Inbox";
include("afterloginheader.php");




include("db.php");
$obj=new DB;
//$sql="select * from userlogin where useremail='$useremail' and password='$userpassword'";
   //$results=$obj->getTable($sql);
?>

           <form action="#" method="post">
          <table border="1" width="65%" align="center" style="background-color:#FFCCCC">
            <tr>
 <th><strong><input type="checkbox" id="selectAll" onclick="chkall()"/></strong></th>
 <th><strong>Froom</strong></th>
 <th><strong>Subject</strong></th>
 <th><strong>Date</strong></th>
 <th><strong>Action</strong></th>
          </tr>

 <?php $sql="select * from email_tbl where `To`=".$_SESSION['userid']."";
        $results=$obj->GetTable($sql);
        foreach($results as $result){

?>
        <tr>
    <td>
  <input type="checkbox" id="checkbox[]" name="checkbox[]" value="<?php  echo $result['id'];?>" />
  </td>
    <td>
  <?php  echo $result['From'];?>
</td>

    <td>
  <?php  echo $result['Subject'];?>
</td>

    <td>
  <?php  echo $result['Date'];?>
</td>
<td>
 <img src="img/del1.jpg" height="25" width="80" align="left" onclick=del(<?php  echo $result['id'];?>)/>
</td>
</tr>


<?php
       }
?>

      <tr>
    <td><input type="submit" value="Delete Sel" id="sub" name="sub" /></td>
</tr>
</table>
</form>

<div align="center" style="display:block">
<form action="#" method="post">
<table>
 <tr>
   <td>
  User List
</td>
<td>
<select id="userlist">
<?php $sql="select * from userlogin";
        $results=$obj->GetTable($sql);
        foreach($results as $result){?>

<option value="<?php echo $result['useremail'] ?>"><?php echo $result['useremail'] ?></option>
<?php }?>
</select>
</td>
 </tr>
    <tr>
    <td>Subject</td><td><input type="text" id="subj" name="subj" placeholder="Enter Subject here"/></td>
  </tr>
   <tr>
    <td>Message</td><td><textarea id="msg" name="msg" rows="4" cols="50" placeholder="Enter Content here"></textarea> </td>
  </tr>

  <tr>
    <td><input type="hidden" value="trans" name="action" /></td>
<td><img src="img/send2.jpg" width="80" height="25" align="left" onclick="submitform()"/>
 <img src="img/save.jpg" width="80" height="25" align="left" onclick="saveEmail()"/></td>
  </tr>

</table>
</form>
</div>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
 //setInterval("saveEmail()",30000);
function saveEmail(){
 var id=document.getElementById("userlist").value;
 var subject=document.getElementById("subj").value;
 var msg=document.getElementById("msg").value;
  $.ajax({
  type:"POST",
  url:"savemsg.php",
  data:{"id":id,"subject":subject,"msg":msg},
  success:function(data){
  alert(data);
   $("#display").html(data);
  }

});
}

 
  function submitform() {
  var form = document.forms[0];

  if (form.onsubmit) {
    var result = form.onsubmit.call(form);
  }

  if (result !== false) {
    form.submit();
  }
}
</script>

<?php
  if(isset($_REQUEST['action'])){
    echo "comming here";
  }
?>

   </tr>
</table>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End inbox.php
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
//// savemsg.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
//{"id":id,"subject":subject,"msg":msg},
session_start();
/*$id=$_REQUEST['id'];
$msg=$_REQUEST['msg'];
$subject=$_REQUEST['subject'];*/
$id=$_REQUEST['id']=2;
$msg=$_REQUEST['msg']="doooo how are you today plz call any time you are free want to talk imo to you";
$subject="call me";
$_SESSION['userid']=1;


include("db.php");
$obj=new DB;
//$sql="select * from category";
//$cats=$obj->getTable($sql);
echo $inssql="insert into email_tbl set `To`='".$id."',`From`=".$_SESSION['userid'].", Subject='".$subject."' ,Content='".$msg."',Date=Now(),published='0'";
echo $results=$obj->insertdelSql($inssql);
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End savemsg.php
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
//// sent.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
$leftTop="Muna Sent List";
include("afterloginheader.php");




include("db.php");
$obj=new DB;
//$sql="select * from userlogin where useremail='$useremail' and password='$userpassword'";
   //$results=$obj->getTable($sql);
?>

           <form action="#" method="post">
          <table border="1" width="65%" align="center" style="background-color:#FFCCCC">
            <tr>
 <th><strong><input type="checkbox" id="selectAll" onclick="chkall()"/></strong></th>
 <th><strong>To</strong></th>
 <th><strong>Subject</strong></th>
 <th><strong>Date</strong></th>
 <th><strong>Action</strong></th>
          </tr>

 <?php $sql="select * from email_tbl where `From`=".$_SESSION['userid']."";
        $results=$obj->GetTable($sql);
        foreach($results as $result){

?>
        <tr>
    <td>
  <input type="checkbox" id="checkbox[]" name="checkbox[]" value="<?php  echo $result['id'];?>" />
  </td>
    <td>
  <?php  echo $result['To'];?>
</td>

    <td>
  <?php  echo $result['Subject'];?>
</td>

    <td>
  <?php  echo $result['Date'];?>
</td>
<td>
 <img src="img/del1.jpg" height="25" width="80" align="left" onclick=del(<?php  echo $result['id'];?>)/>
</td>
</tr>


<?php
       }
?>





   </tr>
</table>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End sent.php
///////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////
//// draft.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
$leftTop="Muna Draft List";
include("afterloginheader.php");




include("db.php");
$obj=new DB;
//$sql="select * from userlogin where useremail='$useremail' and password='$userpassword'";
   //$results=$obj->getTable($sql);
?>

           <form action="#" method="post">
          <table border="1" width="65%" align="center" style="background-color:#FFCCCC">
            <tr>
 <th><strong><input type="checkbox" id="selectAll" onclick="chkall()"/></strong></th>
 <th><strong>To</strong></th>
 <th><strong>Subject</strong></th>
 <th><strong>Date</strong></th>
 <th><strong>Action</strong></th>
          </tr>

 <?php  $sql="select * from email_tbl where `From`=".$_SESSION['userid']." and published='0'";
        $results=$obj->GetTable($sql);
        foreach($results as $result){

?>
        <tr>
    <td>
  <input type="checkbox" id="checkbox[]" name="checkbox[]" value="<?php  echo $result['id'];?>" />
  </td>
    <td>
  <?php  echo $result['To'];?>
</td>

    <td>
  <?php  echo $result['Subject'];?>
</td>

    <td>
  <?php  echo $result['Date'];?>
</td>
<td>
 <img src="img/del1.jpg" height="25" width="80" align="left" onclick=del(<?php  echo $result['id'];?>)/>
</td>
</tr>


<?php
       }
?>





   </tr>
</table>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End draft.php
///////////////////////////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////////////////////////
//// trash.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
$leftTop="Muna Sent List";
include("afterloginheader.php");




include("db.php");
$obj=new DB;
//$sql="select * from userlogin where useremail='$useremail' and password='$userpassword'";
   //$results=$obj->getTable($sql);
?>

           <form action="#" method="post">
          <table border="1" width="65%" align="center" style="background-color:#FFCCCC">
            <tr>
 <th><strong><input type="checkbox" id="selectAll" onclick="chkall()"/></strong></th>
 <th><strong>From</strong></th>
 <th><strong>Subject</strong></th>
 <th><strong>Date</strong></th>
 <th><strong>Action</strong></th>
          </tr>

 <?php  $sql="select * from email_tbl where `To`=".$_SESSION['userid']." and status='delete'";
        $results=$obj->GetTable($sql);
        foreach($results as $result){

?>
        <tr>
    <td>
  <input type="checkbox" id="checkbox[]" name="checkbox[]" value="<?php  echo $result['id'];?>" />
  </td>
    <td>
  <?php  echo $result['From'];?>
</td>

    <td>
  <?php  echo $result['Subject'];?>
</td>

    <td>
  <?php  echo $result['Date'];?>
</td>
<td>
 <img src="img/del1.jpg" height="25" width="80" align="left" onclick=del(<?php  echo $result['id'];?>)/>
</td>
</tr>


<?php
       }
?>





   </tr>
</table>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End trash.php
///////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////
//// db.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
class DB{
   private $dbhost="localhost";
   private $dbuser="root";
   private $dbpass="";
   private $dbname="email";



//The mysql_query function in php returns TRUE on success and FALSE on failure.

 public function insertdelSql($sql){
  $result=mysql_query($sql,$this->getCon());
return $result;
 }

public function hc($sql,$ch){
  $result=mysql_query($sql,$this->getCon());
while($res=mysql_fetch_assoc($result)){
if($res['name']==$ch){
 $resarr[]=array('name'=>$res['name'],'y'=>$res['amount'],'sliced'=>"true",'selected'=>"true");
 }

else{
 $resarr[]=array('name'=>$res['name'],'y'=>$res['amount']);
}
}
//$res=json_encode($resarr, JSON_NUMERIC_CHECK);
return $resarr;
}





 public function getTable($sql){
  $result=mysql_query($sql,$this->getCon());
while($row=mysql_fetch_array($result)){
 $resarr[]=$row;
}
return $resarr;
 }



  public function getCon(){
  $con=mysql_connect($this->dbhost,$this->dbuser,$this->dbpass);
  mysql_select_db($this->dbname,$con)or
  die(mysql_error("can't connect db"));
  return $con;
 }


}//class end

///////////////////////////////////////////////////////////////////////////////////////////////////
//// End db.php
///////////////////////////////////////////////////////////////////////////////////////////////////






YQL to Populate Country,State and Distrct/County Drop down Based on Selection in parents Drop down!

<html>
  <head><title>YQL and RSS: Yahoo! Top News Stories</title>
  <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
  <script src="http://yui.yahooapis.com/3.10.3/build/yui/yui-min.js"></script>
  <script type='text/javascript'>
    /*function top_stories(o){
      var items = o.query.results.item;
      var output = '';
      var no_items=items.length;
      for(var i=0;i<no_items;i++){
        var title = items[i].title;
        var link = items[i].link;
        var desc = items[i].description;
        output += "<h3><a href='" + link + "'>"+title+"</a></h3>" + desc + "<hr/>";
      }*/
      // Place news stories in div tag
 function top_stories(o){   //json output get stored in o
      var items = o.query.results.place; //json array get saved in items
      var output = '';
 var no_items=items.length;  //size of items like no. of countries
      for(var i=0;i<no_items;i++){
 output=output+"<option value=\""+items[i].woeid+ "\">";
 output=output+items[i].name+"</option>";
 }
      document.getElementById('countri').innerHTML = output;  //innerHTML everything between opening and closing element
    }
function updatestate()
{
e=document.getElementById('countri').value;
//http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.states%20where%20place%3D%2223424819%22&format=json&diagnostics=true&callback=cbfunc
qe="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.states%20where%20place%3D"+e+"&format=json&diagnostics=true";
$.ajax( {
    url: qe,
  type: 'POST',
  //data: {"num1":number1,"num2":number2},
    success: function(response) {
obj=response.query.results.place;
var output = '';
  var l=obj.length;
      for(var i=0;i<l;i++){
output=output+"<option value=\""+ obj[i].woeid +"\">";
output=output+obj[i].name;
output=output+'</option>';
}
document.getElementById('state').innerHTML=output;
document.getElementById('county').innerHTML='';
document.getElementById('district').innerHTML='';
}
    });
}

function updatecounty()
{
e=document.getElementById('state').value;
//http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.states%20where%20place%3D%2223424819%22&format=json&diagnostics=true&callback=cbfunc
qe="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.counties%20where%20place%3D"+e+"&format=json&diagnostics=true";
$.ajax( {
    url: qe,
  type: 'POST',
  //data: {"num1":number1,"num2":number2},
    success: function(response) {
obj=response.query.results.place;
var output = '';
  var l=obj.length;
      for(var i=0;i<l;i++){
output=output+"<option value=\""+ obj[i].woeid +"\">";
output=output+obj[i].name;
output=output+'</option>';
}
//alert(output);
document.getElementById('county').innerHTML=output;
document.getElementById('district').innerHTML='';
}
    });
}

function updatedistrict()
{
e=document.getElementById('county').value;
//http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.states%20where%20place%3D%2223424819%22&format=json&diagnostics=true&callback=cbfunc
qe="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.districts%20where%20place%3D"+e+"&format=json&diagnostics=true";
console.log(qe);
$.ajax( {
    url: qe,
  type: 'POST',
  //data: {"num1":number1,"num2":number2},
    success: function(response) {    
                       if(response)
{
obj=response.query.results;
if(obj!=null)
{
obj=obj.place;
var output = '';
  var l=obj.length;
      for(var i=0;i<l;i++){
output=output+"<option value=\""+ obj[i].woeid +"\">";
output=output+obj[i].name;
output=output+'</option>';
}
//alert(output);
document.getElementById('district').innerHTML=output;
}
}
}
    });
}
    </script>
  </head>
  <body>
    <!-- Div tag for stories results -->
    <select id="countri" name="countri" onChange="updatestate()">

</select>
<select id="state" name="state" onChange="updatecounty()"></select>
<select id="county" name="county" onChange="updatedistrict()"> </select>
<select id="district" name="district"></select>
    <!-- The YQL statment will be assigned to src. -->
    <script src='http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.countries&format=json&diagnostics=true&callback=top_stories'></script>
  </body>
</html>

Wednesday, November 23, 2016

Yahoo Top News Stories using YQL and yahoo API

///////////////////////////////////////////////////////////////////////////////////////////////////
//// index.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?xml version="1.0" encoding="UTF-8"?>
<table xmlns="http://query.yahooapis.com/v1/schema/table.xsd" https="true">
    <meta>
        <author>Paul Donnelly</author>
        <documentationURL>http://developer.netflix.com/docs/REST_API_Reference#0_52696</documentationURL>
    </meta>
      <bindings>
        <select itemPath="" produces="XML" >
          <urls>
            <url>http://api-public.netflix.com/catalog/titles/</url>
          </urls>
         <paging model="offset">
           <start id="start_index" default="0" />
           <pagesize id="max_results" max="100" />
           <total default="20" />
         </paging>
          <inputs>
                <key id="term" type="xs:string" paramType="query" required="true" />
                <key id="ck" type="xs:string" paramType="variable" required="true" />
                <key id="cs" type="xs:string" paramType="variable" required="true" />
          </inputs>
          <execute><![CDATA[
// Include the OAuth libraries from oauth.net
y.include("http://oauth.googlecode.com/svn/code/javascript/oauth.js");
y.include("http://oauth.googlecode.com/svn/code/javascript/sha1.js");

// Collect all the parameters
var encodedurl = request.url;
var accessor = { consumerSecret: cs, tokenSecret: ""};
var message = { action: encodedurl, method: "GET", parameters: [["oauth_consumer_key",ck],["oauth_version","1.0"]]};
OAuth.setTimestampAndNonce(message);

// Sign the request
OAuth.SignatureMethod.sign(message, accessor);

try {
   // get the content from service along with the OAuth header, and return the result back out
   response.object = request.contentType('application/xml').header("Authorization", OAuth.getAuthorizationHeader("netflix.com", message.parameters)).get().response;
} catch(err) {
   response.object = {'result':'failure', 'error': err};
}
          ]]></execute>
        </select>
      </bindings>
</table>

<html>
  <head><title>YQL and RSS: Yahoo Top News Stories</title>      <style type='text/css'>
      #results{ width: 40%; margin-left: 30%; border: 1px solid gray; padding: 5px; height: 200px; overflow: auto; }
    </style>
    <script type='text/javascript'>
      function top_stories(o){
        var items = o.query.results.item;
        var output = '';
        var no_items=items.length;
        for(var i=0;i<no_items;i++){
          var title = items[i].title;
          var link = items[i].link;
          var desc = items[i].description;
          output += "<h3><a href='" + link + "'>"+title+"</a></h3>" + desc + "<hr/>";    
        }
        document.getElementById('results').innerHTML = output;
      }
    </script>
  </head>
  <body>
    <div id='results'></div>
    <script src='http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20rss%20where%20url%3D%22http%3A%2F%2Frss.news.yahoo.com%2Frss%2Ftopstories%22&format=json&diagnostics=false&callback=top_stories'></script>
  </body>
</html>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End index.php
///////////////////////////////////////////////////////////////////////////////////////////////////





Tuesday, November 22, 2016

Getting Full detail of any particular location using Geocoding in PHP


///////////////////////////////////////////////////////////////////////////////////////////////////
//// index.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<form  method="post" action="geoclass.php">
<h2 align="center" style="vertical-align:middle">Geocode This Address</h2>
<table align="center" style="vertical-align:middle">
<tr>
<td>Appt No:</td><td><input type="text" id="appt" name="appt"></td></tr>
<td>Street Address:</td><td><input type="text" id="street" name="street"></td></tr>
<td>City:</td><td><input type="text" id="city" name="city"></td></tr>
<td>State:</td><td><input type="text" id="state" name="state"></td></tr>
<td>Zip Code:</td><td><input type="text" id="zip" name="zip"></td></tr>
<td>Country:</td><td><input type="text" id="country" name="country"></td></tr>
<td></td><td><input type="submit" id="sub" name="sub" value="Enter The Address Here!!!"></td>
</tr>
</table>
</form>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End index.php
///////////////////////////////////////////////////////////////////////////////////////////////////



///////////////////////////////////////////////////////////////////////////////////////////////////
//// geoclass.php //using curl
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php

class geocoder{
   static private $url="http://maps.google.com/maps/api/geocode/xml?sensor=true&address=";
   static public function getLocation($address){
       $url=self::$url.urlencode($address);
$ch=curl_init($url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$data1=curl_exec($ch);
curl_close($ch);
$data2=simplexml_load_string($data1);
$data2->asXML("result.xml");
$arr=array();
if($data2->status=='OK'){

$arr[]=(string)$data2->result->geometry->location->lat;
$arr[]=(string)$data2->result->geometry->location->lng;
return $arr;
}
   }


}//end class
if(!isset($_REQUEST['sub'])){
$appt=$_REQUEST['appt'];
$street=$_REQUEST['street'];
$city=$_REQUEST['city'];
$state=$_REQUEST['state'];
$zip=$_REQUEST['zip'];
$country=$_REQUEST['country'];
$myaddress=$appt." ".$street." ".$city." ".$state." ".$zip." ".$country;
$address=urlencode($myaddress);
$loc = geocoder::getLocation($address);
}
else{
$address=urlencode("1600 Amphitheatre Parkway, Mountain View, CA");
//$address=urlencode($myaddress);
$loc = geocoder::getLocation($address);
}
?>

<script src="http://maps.googleapis.com/maps/api/js?key=API_KEY"></script>
<script>


var myLatlng = new google.maps.LatLng('<?php echo $loc[0]; ?>','<?php echo $loc[1]; ?>');


function initialize()
{
var mymapProp = {
  center: myLatlng,
  zoom:5,
  mapTypeId: google.maps.MapTypeId.ROADMAP
  };

var map = new google.maps.Map(document.getElementById("displayarea"),mymapProp);

var image = 'images/myimage.png';
image.height = 5;
image.width = 5;
var marker = new google.maps.Marker({
  position: myLatlng,
   map: map,
   icon: image,
   title:'Click for zooming muna map'
  });

marker.setMap(map);
google.maps.event.addListener(marker,'click',function() {
  map.setZoom(12);//// Zoom to 9 when clicking on marker
  map.setCenter(marker.getPosition());
  });
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<div  align="center" id="displayarea" style="width:500px;height:380px;" ></div>


///////////////////////////////////////////////////////////////////////////////////////////////////
//// End geoclass.php
///////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////
//// geoclass.php //using file_get_contents
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php

class geocoder{
    static private $url = "http://maps.google.com/maps/api/geocode/xml?sensor=false&address=";
    static public function getLocation($address){
        $url = self::$url.urlencode($address);
$resp_json =file_get_contents($url);
   $data=simplexml_load_string($resp_json);
$data->asXML("googleres.xml");
$arr=array();
if($data->status=='OK'){
$arr[]=(string)$data->result->geometry->location->lat;
$arr[]=(string)$data->result->geometry->location->lng;
return $arr;
}



$resp = json_decode($resp_json, true);
if($resp['status']=='OK'){
            return $resp['results'][0]['geometry']['location'];
        }else{
            return false;
        }  
    }
}
if(isset($_REQUEST['sub'])){
$appt=$_REQUEST['appt'];
$street=$_REQUEST['street'];
$city=$_REQUEST['city'];
$state=$_REQUEST['state'];
$zip=$_REQUEST['zip'];
$country=$_REQUEST['country'];
$myaddress=$appt." ".$street." ".$city." ".$state." ".$zip." ".$country;
$address=urlencode($myaddress);
$loc = geocoder::getLocation($address);
}
else{
$address=urlencode("1600 Amphitheatre Parkway, Mountain View, CA");
$address=urlencode($myaddress);
$loc = geocoder::getLocation($address);
}
?>

<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDfdjaFVpr7tz2oA-FQ0_e4WJM8zN9StCI"></script>
<script>


var myLatlng = new google.maps.LatLng('<?php echo $loc[0]; ?>','<?php echo $loc[1]; ?>');


function initialize()
{
var mymapProp = {
  center: myLatlng,
  zoom:5,
  mapTypeId: google.maps.MapTypeId.ROADMAP
  };

var map = new google.maps.Map(document.getElementById("displayarea"),mymapProp);

var image = 'images/myimage.png';
image.height = 5;
image.width = 5;
var marker = new google.maps.Marker({
  position: myLatlng,
   map: map,
   icon: image,
   title:'Click for zooming muna map'
  });

marker.setMap(map);
google.maps.event.addListener(marker,'click',function() {
  map.setZoom(12);//// Zoom to 9 when clicking on marker
  map.setCenter(marker.getPosition());
  });
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<div  align="center" id="displayarea" style="width:500px;height:380px;" ></div>


///////////////////////////////////////////////////////////////////////////////////////////////////
//// End geoclass.php
///////////////////////////////////////////////////////////////////////////////////////////////////







///////////////////////////////////////////////////////////////////////////////////////////////////
//// result.xml
///////////////////////////////////////////////////////////////////////////////////////////////////
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
 <status>OK</status>
 <result>
  <type>street_address</type>
  <formatted_address>1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA</formatted_address>
  <address_component>
   <long_name>1600</long_name>
   <short_name>1600</short_name>
   <type>street_number</type>
  </address_component>
  <address_component>
   <long_name>Amphitheatre Parkway</long_name>
   <short_name>Amphitheatre Pkwy</short_name>
   <type>route</type>
  </address_component>
  <address_component>
   <long_name>Mountain View</long_name>
   <short_name>Mountain View</short_name>
   <type>locality</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Santa Clara County</long_name>
   <short_name>Santa Clara County</short_name>
   <type>administrative_area_level_2</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>California</long_name>
   <short_name>CA</short_name>
   <type>administrative_area_level_1</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>United States</long_name>
   <short_name>US</short_name>
   <type>country</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>94043</long_name>
   <short_name>94043</short_name>
   <type>postal_code</type>
  </address_component>
  <geometry>
   <location>
    <lat>37.4223664</lat>
    <lng>-122.0844060</lng>
   </location>
   <location_type>ROOFTOP</location_type>
   <viewport>
    <southwest>
     <lat>37.4210174</lat>
     <lng>-122.0857550</lng>
    </southwest>
    <northeast>
     <lat>37.4237154</lat>
     <lng>-122.0830570</lng>
    </northeast>
   </viewport>
  </geometry>
  <partial_match>true</partial_match>
  <place_id>ChIJ2eUgeAK6j4ARbn5u_wAGqWA</place_id>
 </result>
</GeocodeResponse>

///////////////////////////////////////////////////////////////////////////////////////////////////
//// End result.php
///////////////////////////////////////////////////////////////////////////////////////////////////


Thursday, November 10, 2016

Dynamic modification of text using Ajax

///////////////////////////////////////////////////////////////////////////////////////////////////
//// index.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
include("connect.php");
$query=mysql_query("select * from `student`");
?>
<html>
<head>
<script src="jquery-1.10.1.js"></script>
<script language="javascript">
function g(e,f)
{
if(f=='delete.php') { confirmation=confirm('You want to delete your own account???'); if(confirmation==false) return; }
document.getElementById('mydatatobesent').value=e;
document.getElementById('myform').action=f;
document.getElementById('myform').submit();
}

function h(v1,v2)
{
v3=v1+v2;
n=document.getElementById(v3).innerHTML;
c=document.createElement("input");
c.setAttribute("type","text");
c.setAttribute("value",n);
c.setAttribute("id",v3);
mm="vv("+v1+",'"+v2+"')";
c.setAttribute("onBlur",mm);
document.getElementById(v3).parentNode.replaceChild(c,document.getElementById(v3));
}
function vv(v1,v2)
{
v3=v1+v2;
n=document.getElementById(v3).value;
$.ajax( {
    url: 'change.php',
  type: 'POST',
  data: {"id":v1,"field":v2,"textentry":n},
    success: function(datareturned) {
console.log(datareturned);
}
    });
c=document.createElement("div");
c.innerHTML=n;
c.setAttribute("id",v3);
mm="h("+v1+",'"+v2+"')";
c.setAttribute("onClick",mm);
//c.setAttribute("onClick","h(v1,v2)");
document.getElementById(v3).parentNode.replaceChild(c,document.getElementById(v3));
}
</script>
</head>
<body bgcolor="#00FF00">
<table border="3" bgcolor="#CCFFFF" style="position:absolute; top:20%">
<tr bgcolor="#CCFF00">
<th>NAME</th>
<th>AGE</th>
<th>PHONE</th>
<th>ADDRESS</th>
<th>DELETE</th>
</tr>
<form  id="myform" method="post">
    <input type="hidden" name="id" id="mydatatobesent" value="gg"/>
</form>
<?php
while($row=mysql_fetch_array($query))
{
$r=$row['id'];
?>
<tr>
<script language="javascript">
</script>
<td>
<div onClick="h(<?php echo $r; ?>,'NAME')" id="<?php echo $r."NAME"; ?>">
<?php
echo $row['NAME'];
?>
</div>
</td>
<td>
<div onClick="h(<?php echo $r; ?>,'AGE')"  id="<?php echo $r."AGE"; ?>">
<?php
echo $row['AGE'];
?>
</div>
</td>
<td>
<div onClick="h(<?php echo $r; ?>,'PHONE')"  id="<?php echo $r."PHONE"; ?>">
<?php
echo $row['PHONE'];
?>
</div>
</td>
<td>
<div onClick="h(<?php echo $r; ?>,'ADDRESS')" id="<?php echo $r."ADDRESS"; ?>">
<?php
echo $row['ADDRESS'];
?>
</div>
</td>
<td>
<?php
echo "<button  onclick=\"g($r,'delete.php')\" <strong>DELETE</strong> </button> ";;
//return confirm('You want to delete your own account???');
?>

</td>
</tr>
<?php
}
?>
</table>
</body>
</html>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End index.php
///////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////
//// change.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
include("connect.php");
$id=$_POST['id'];
$field=$_POST['field'];
$textentry=$_POST['textentry'];
//echo "update student set $field = $textentry where id='$id'";
mysql_query("update `student` set `$field` = '$textentry' where `id`='$id'") or die(mysql_error());
?>

///////////////////////////////////////////////////////////////////////////////////////////////////
//// End change.php
///////////////////////////////////////////////////////////////////////////////////////////////////

Take a csv file as input argument and print it in table form using PHP ,JavaScript language and JSON

///////////////////////////////////////////////////////////////////////////////////////////////////
//// index.html
///////////////////////////////////////////////////////////////////////////////////////////////////
<html>
<head>
<script type="text/javascript" src="detail.js"></script>
<script type="text/javascript">

  document.write("<table>");
  ajax( {
    url: 'fetchData.php',
  type: 'POST',
dataType: "json",
  data: {"fileName":"details.csv"},
    success: function(response) {
response=response.data;
document.write("<table border=\"2\">");
Object.keys(response[0]).forEach(function(key) {
     
document.write("<th bgcolor=\"red\">"+key+"</th>");
    });


for (var i = 0, len = response.length; i < len; i++) {
document.write("<tr bgcolor=\"yellow\">");
             Object.keys(response[i]).forEach(function(key) {
     
document.write("<td>"+response[i][key]+"</td>");
    });
document.write("</tr>");
        }
document.write("</table>");

},
    error: function( response ) { alert( response ); }
   } );
   document.write("</table>");
</script>
</head>
<body>
</body>
</html>

///////////////////////////////////////////////////////////////////////////////////////////////////
//// End index.html
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
//// fetchData.php
///////////////////////////////////////////////////////////////////////////////////////////////////

<?php
$isRequest = true;
if( !$isRequest ) {
if( count( $argv ) == 1 ) {

echo "Enter a csv file name ";

$in = fopen( "php://stdin", "r" );
$fileName = trim( fgets( $in ) );

} else {
$fileName = trim( $argv[1] );
}
} else {
$fileName = ( isset( $_REQUEST['fileName'] ) ? $_REQUEST['fileName'] : "deviceList2.csv" );
}

if( !$isRequest ) echo "Reading CSV from  $fileName.\n";

$fp = fopen( $fileName, "r" );

$addNewLine = false;

$fields = false;

$json = "{ ";
if( !$fp ) {
$json .= "\"status\": 0, \"statusString\": \"Could not open specified file.\" } ";
echo $json;
die;
}

$json .= " \"data\": [";

if( $addNewLine ) $json .= "\n";

$total = 0;

while( $line = fgets( $fp ) ) {

$rowValues = preg_split( "*,*", trim( $line ) );

if( !$fields ) {
$fields = $rowValues;
} else {

$json .= " { ";
if( $addNewLine ) $json .= "\n";

for( $i = 0; $i < count( $fields ); $i++ ) {

$field = $fields[ $i ];
$value = $rowValues[ $i ];

$json .= "   \"$field\": \"$value\", ";
if( $addNewLine ) $json .= "\n";

}

$json = substr( $json, 0, -2 );
if( $addNewLine ) $json .= "\n";
$json .= " }, ";

$total++;

}

}

$json = substr( $json, 0, -2 );
$json .= " ], ";
$json = substr( $json, 0, -2 );
$json .= " }";
if( $addNewLine ) $json .= "\n";
echo $json;
?>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End fetchData.php
///////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////
//// detail.js
///////////////////////////////////////////////////////////////////////////////////////////////////
function buildAjaxArrayObject( par, obj ) {

var dataSt= '';

for( var what in obj ) {

if( typeof( obj[ what ] ) == 'array' || typeof( obj[ what ] ) == 'object' ) {
dataSt += buildAjaxArrayObject( par + '[' + what + ']', obj[ what ] );
} else {
dataSt += par + '[' + what + ']=' + obj[ what ] + '&'
}

}

return dataSt;

}

function ajax( data ) {

if( data.async == undefined ) {
data.async = true;
}

if( data.beforeSend ) {
data.beforeSend( data );
}

var dataString = '';
if( data.data ) {
for( var what in data.data ) {
if( typeof( data.data[ what ] ) == 'array' || typeof( data.data[ what ] ) == 'object' ) {
dataString += buildAjaxArrayObject( what, data.data[ what ] );
} else {
dataString += what + '=' + data.data[what] + '&';
}
}
}
dataString = dataString.substr( 0, dataString.length - 1 );

var xmlHttp;
try {
xmlHttp = new XMLHttpRequest();
} catch( e ) {
return;
}

var responseFunction = function() {
if( xmlHttp.readyState == 4 ) {

var reponse = '';
if( xmlHttp.responseText ) {
if( xmlHttp.getResponseHeader( 'Content-Type' ) == 'text/xml' ) {
response = xmlHttp.responseXML;
} else {
if( window.JSON && window.JSON.parse ) {
response = window.JSON.parse( xmlHttp.responseText );
} else {
response = (new Function("return " + xmlHttp.responseText))();
}
}
}
if( xmlHttp.status == 200 ) {
if( data.success ) {
data.success( response );
}
} else {
if( data.error ) {
data.error( response );
}
}
if( data.complete ) {
data.complete.call( response );
}

}

}

xmlHttp.open( 'POST', data.url, data.async );
xmlHttp.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded' );
if( data.async ) {
xmlHttp.onreadystatechange = responseFunction;
}
xmlHttp.send( dataString );
if( !data.async ) {
responseFunction.call();
}
return true;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
//// End detail.js
///////////////////////////////////////////////////////////////////////////////////////////////////


Tuesday, November 8, 2016

Getting Sunrise and Sunset Time of any Country using YQL(Yahoo API)


///////////////////////////////////////////////////////////////////////////////////////////////////
//// index.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
t=document.createElement("Table");
t.setAttribute("border","3");
$(document).ready(function(){
 $.ajax( {
     url: 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.states%20where%20place%3D23424848&format=json&diagnostics=true',
   type: 'POST',
async:false,
        success: function(response) {
pp=document.createElement("tr");
q1=document.createElement("th");
q1.innerHTML="STATENAME";
q2=document.createElement("th");
q2.innerHTML="SUNRISE";
q3=document.createElement("th");
q3.innerHTML="SUNSET";
pp.appendChild(q1);
pp.appendChild(q2);
pp.appendChild(q3);
t.appendChild(pp);
console.log(response);
v=response.query.results.place;
l=v.length;
for(i=0;i<l;i++)
{
statename=v[i].name;
placeid=v[i].woeid;
z=document.createElement("tr");
y=document.createElement("td");
y.innerHTML=statename;
z.appendChild(y);

console.log(statename);
rrr="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%3D"+placeid+"&format=json&diagnostics=true";
$.ajax( {
url: rrr,
async:false,
success: function(datareturned) {

console.log(datareturned);
sunrisetime=datareturned.query.results.channel.astronomy.sunrise;
y1=document.createElement("td");
y1.innerHTML=sunrisetime;
sunsettime=datareturned.query.results.channel.astronomy.sunset;
y2=document.createElement("td");
y2.innerHTML=sunsettime;
z.appendChild(y1);
z.appendChild(y2);
t.appendChild(z);
}
});
}

document.getElementsByTagName("body")[0].appendChild(t);}
    });
});

</script>
</head>
<body>
</body>
</html>



</html>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End index.php
///////////////////////////////////////////////////////////////////////////////////////////////////