Tuesday, 31 March 2015

Script for YES _NO _CONFIRMATION_ IN_ JAVASCRIPT with PHP:


(1)FIRST WRITE javascript CODE in <head> section </head> :
<html>
 <head>

<script type="text/javascript">
function doDelete(id){
if(confirm("Do you want to delete the record?")){
$.ajax({
url:'delete.php',
type:'post',
data:'id='+id,
success:function(msg){
alert(msg);
window.location.href='pagination2.php';
}
});
}
}
</script>

</head>

<!---Second  use  following line where you want to call doDelete() method in <body> section </body>--->
<body>
<?php

   include("connect.php");
 
    $per_page = 8;

    $pages_query = mysql_query("SELECT COUNT('id') FROM  notes order by coursename,semester ASC");

    $pages = ceil(mysql_result($pages_query, 0) / $per_page);

   
    $page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
    $start = ($page - 1) * $per_page;
   
    $query = mysql_query("SELECT *  FROM notes LIMIT $start, $per_page");

while($row = mysql_fetch_assoc($query))


{

echo "record one";

?>



<a class="click-more" href="#" onClick="doDelete('<?php echo $row['id']; ?>');">read more</a>


<?php




$prev = $page - 1;
    $next = $page + 1;
   
    if(!($page<=1)){
        echo "<a href='pagination1.php?page=$prev'><button>Prev</button></a> ";
    }

    if($pages>=1 && $page<=$pages){
   
        for($x=1;$x<=$pages;$x++){
            echo ($x == $page) ? '<strong><a href="?page='.$x.'"><button>'.$x.'</button></a></strong> ' : '<a href="?page='.$x.'"><button>'.$x.'</button></a> ';
       
        }
   
    }
   
    if(!($page>=$pages)){
        echo "<a href='pagination1.php?page=$next'><button>Next>></button></a>";
    }
   
   
?>

</body>
</html>


(2)write code for delete.php file:

<?php


$id=$_POST['id'];

include("connect.php");


$sql="delete from notes where id='$id'";

mysql_query($sql) or die(mysql_error());


echo "Record deleted successfully";

echo '<br></br>';

echo '<a href="pagination1.php"><button>back to previous page</button></a>';


?>



Sunday, 29 March 2015

Java_code_for_Calculator using Java Applet

(1)first write code for "cal.java" file:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*
<applet code="Cal" width=300 height=300>
</applet>
*/

public class cal extends Applet implements ActionListener
{
String msg=" ";
int v1,v2,result;
TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,EQ;
char OP;
public void init()
{
Color k=new Color(120,89,90);
setBackground(k);
t1=new TextField(10);
GridLayout gl=new GridLayout(4,5);
setLayout(gl);
for(int i=0;i<10;i++)
{
b[i]=new Button(""+i);
}
add=new Button("add");
sub=new Button("sub");
mul=new Button("mul");
div=new Button("div");
mod=new Button("mod");
clear=new Button("clear");
EQ=new Button("EQ");
t1.addActionListener(this);
add(t1);
for(int i=0;i<10;i++)
{
add(b[i]);
}
add(add);
add(sub);
add(mul);
add(div);
add(mod);
add(clear);
add(EQ);
for(int i=0;i<10;i++)
{
b[i].addActionListener(this);
}
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
char ch=str.charAt(0);
if ( Character.isDigit(ch))
t1.setText(t1.getText()+str);
else
if(str.equals("add"))
{
v1=Integer.parseInt(t1.getText());
OP='+';
t1.setText("");
}
else if(str.equals("sub"))
{
v1=Integer.parseInt(t1.getText());
OP='-';
t1.setText("");
}
else if(str.equals("mul"))
{
v1=Integer.parseInt(t1.getText());
OP='*';
t1.setText("");
}
else if(str.equals("div"))
{
v1=Integer.parseInt(t1.getText());
OP='/';
t1.setText("");
}
else if(str.equals("mod"))
{
v1=Integer.parseInt(t1.getText());
OP='%';
t1.setText("");
}
if(str.equals("EQ"))
{
v2=Integer.parseInt(t1.getText());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
t1.setText(""+result);
}
if(str.equals("clear"))
{
t1.setText("");
}
}
}


(2)write code for  "cal.html "  file:

<html>
 <p> This file launches the 'A' applet: A.class! </p>
 <applet code="Cal.class" height=200 width=320>
 No Java?!
 </applet>
 </html>


(3)Now see following how to run  java file

Go to dirve wehre you have save your  cal.java file
for example  E:/  drive..

E:> set path="C:\Program Files\Java\jdk1.8.0_40\bin"
E:> javac  cal.java     (to compile your java file  & then you will get "cal.class"  file)
E:>appletviewer  cal.html

here appletviewer is used for  running  java applet..

Saturday, 28 March 2015

SMS Service(Api) Integration to website

(1)first go to website   & click on sign up  & register  there.

http://sms.ssdindia.com/


(2)they will send you your password through sms ..
(3)user your username & password & make login:

(4)then go to left hand side under IMPORTANT LINKS
CLICK ON   developer Tools(Api):

(5)then you will be redirected to  following links:

"http://sms.ssdindia.com/apidoc/"


(6)under that click on  "Text Sms"

(7)then fill given below form get Authetication key & Sample code for integrating Sms Api to your website ..






(8)then  use following sample code for testing:



<?php

//Your authentication key
$authKey = "YourAuthKey";

//Multiple mobiles numbers separated by comma
$mobileNumber = "9999999";

//Sender ID,While using route4 sender id should be 6 characters long.
$senderId = "102234";

//Your message to send, Add URL encoding here.
$message = urlencode("Test message");

//Define route 
$route = "default";
//Prepare you post parameters
$postData = array(
    'authkey' => $authKey,
    'mobiles' => $mobileNumber,
    'message' => $message,
    'sender' => $senderId,
    'route' => $route
);

//API URL
$url="http://sms.ssdindia.com/sendhttp.php";

// init the resource
$ch = curl_init();
curl_setopt_array($ch, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $postData
    //,CURLOPT_FOLLOWLOCATION => true
));


//Ignore SSL certificate verification
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);


//get response
$output = curl_exec($ch);

//Print error if any
if(curl_errno($ch))
{
    echo 'error:' . curl_error($ch);
}

curl_close($ch);

echo $output;
?>
Note: finally you will get sms which is given  & message=urlencode("testmessage");

Javascript _ for _Captcha

<html>
<head>
<title>Captcha</title>
   
    <script type="text/javascript">

   //Created / Generates the captcha function  
    function DrawCaptcha()
    {
        var a = Math.ceil(Math.random() * 10)+ '';
        var b = Math.ceil(Math.random() * 10)+ '';      
        var c = Math.ceil(Math.random() * 10)+ '';
        var d = Math.ceil(Math.random() * 10)+ '';
        var e = Math.ceil(Math.random() * 10)+ '';
        var f = Math.ceil(Math.random() * 10)+ '';
        var g = Math.ceil(Math.random() * 10)+ '';
        var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' '+ f + ' ' + g;
        document.getElementById("txtCaptcha").value = code
    }

    // Validate the Entered input aganist the generated security code function  
    function ValidCaptcha(){
        var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
        var str2 = removeSpaces(document.getElementById('txtInput').value);
        if (str1 == str2) return true;      
        return false;
       
    }

    // Remove the spaces from the entered and generated code
    function removeSpaces(string)
    {
        return string.split(' ').join('');
    }
   

    </script>
   
   
   
</head>
<body onload="DrawCaptcha();">
<table>
<tr>
    <td>
        Welcome To Captcha<br />
    </td>
</tr>
<tr>
    <td>
        <input type="text" id="txtCaptcha"
            style="background-image:url(1.jpg); text-align:center; border:none;
            font-weight:bold; font-family:Modern" />
        <input type="button" id="btnrefresh" value="Refresh" onclick="DrawCaptcha();" />
    </td>
</tr>
<tr>
    <td>
        <input type="text" id="txtInput"/>  
    </td>
</tr>
<tr>
    <td>
        <input id="Button1" type="button" value="Check" onclick="alert(ValidCaptcha());"/>
    </td>
</tr>
</table>
</body>
</html>

PHP_Script_ for _Captcha

(1)First write code for  "captcha.php"   file:

<?php
// Create our image
$image = imagecreatetruecolor(100, 30);

// Assign a background colour. I have set it to white but background is going to be transparent anyway
$background = imagecolorallocate($image, 0,0,0);

// Make background transparent by setting the colour we are going to use as transparent
imagecolortransparent($image, $background);

// Fill it in with the background colour. This is required to make the background transparent
imagefilledrectangle($image, 0, 0, 199, 49, $background);

// function to generate captcha characters
function captchaChars($hash)
{
  //  Generate a 32 character string by getting the MD5 hash of the servers name with the hash added to the end.
  //  Adding the servers name means outside sources cannot just work out the characters from the hash
  $captchastr = md5($_SERVER['SERVER_NAME'] . $hash);
  return strtoupper($captchastr); // Make all our characters uppercase for clarity in the image
}

// Lets get the characters to show in the image or say 'error' if no hash submitted
$str = (!empty($_GET['hash'])) ? captchaChars($_GET['hash']) : 'ERROR';

// Assign a colour for the text and lines. I've chosen a shade of grey
$our_colour = imagecolorallocate($image, 140,140,140);

// Lets add three random background lines
for ($i = mt_rand(5, 8); $i <= 29; $i += 10)
{
  imageline($image, mt_rand(0, 100), $i + mt_rand(-5, 5), mt_rand(0, 100), $i + mt_rand(-5, 5), $our_colour);
}

// Set a random horizontal starting position
$x_pos = mt_rand(10, 20);

// Lets loop through our string adding one character at a time in a randomish position
// We start with the first character and then use every seventh character just for added randomness
for($i = 0; $i <= 28; $i += 7)
{
  imagestring($image, 5, $x_pos, mt_rand(0, 12), $str[$i], $our_colour); // add a character from our string
  $x_pos += mt_rand(10, 18);  // Move the horizontal position by a random amount
}

// Add some wavy distortion to the image
$wave = rand(3,5);
$wave_width = rand(8,15);
for ($i = 0; $i < 200; $i += 2)
{
  imagecopy($image, $image, $i - 2, sin($i / $wave_width) * $wave, $i, 0, 2, 40);
}

// Send the gif header. We use a gif because of IE6's poor support for PNG transparency
header('Content-type: image/gif');
// Dump the image
imagegif($image);

?>



(2)Second write code for   "captchaform.php"  file:


<?php
$hash = substr(md5(mt_rand(1, 1000)), 10, 20); // Just generate a random hash to use
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <title></title>
  <script type="text/javascript">
  function reloadCaptcha(imageName)
  {
    var randomnumber=Math.floor(Math.random()*1001); // generate a random number to add to image url to prevent caching
    document.images[imageName].src = document.images[imageName].src + '&amp;rand=' + randomnumber; // change image src to the same url but with the random number on the end
  }
  </script>
  </head>
  <body>
<img src="captcha.php?hash=<?php echo $hash; ?>" alt="captcha" name="captchaImage"><br>
<a href="#" onclick="reloadCaptcha('captchaImage'); return false;">refresh image</a>
<form action="captchaform.php" method="post">
<input type="text" name="captchacode"><br>
<input type="submit" value="Submit Code" name="submit">
<input type="hidden" value="<?php echo $hash; ?>" name="hash">
</form>
<div style="height:20px;"> <?php
if(isset($_POST['submit']))
{
  $hash = (!empty($_POST['hash'])) ? preg_replace('/[\W]/i', '', trim($_POST['hash'])) : ''; // Remove any non alphanumeric characters to prevent exploit attempts
  $captchacode = (!empty($_POST['captchacode'])) ? preg_replace('/[\W]/i', '', trim($_POST['captchacode'])) : ''; // Remove any non alphanumeric characters to prevent exploit attempts
  // function to check the submitted captcha
  function captchaChars($hash)
  {
    //  Generate a 32 character string by getting the MD5 hash of the servers name with the hash added to the end.
    //  Adding the servers name means outside sources cannot just work out the characters from the hash
    $captchastr = strtolower(md5($_SERVER['SERVER_NAME'] . $hash));
    $captchastr2 = '';
    for($i = 0; $i <= 28; $i += 7)
    {
      $captchastr2 .= $captchastr[$i];
    }
    return $captchastr2;
  }
  if(!empty($captchacode))
  {
    if(strtolower($captchacode) == captchaChars($hash))  // We convert submitted characters to lower case then compare with the expected answer
    {
      echo '<h3>The submitted characters were correct</h3>';
    }
    else
    {
      echo '<h3>The submitted characters were WRONG!</h3>';
    }
  }
  else
  {
    echo '<h3>You forgot to fill in the code!</h3>';
  }
}
?>
</div>
  </body>
</html>





Wednesday, 25 March 2015

PHP_web_scraping Example

<?php


 $url = 'http://vissicomp.com';


 $output = file_get_contents($url);




 echo $output;

 ?>

Tuesday, 24 March 2015

PHP _Script_ to_ select _multiple _ids _from _mysql database

(1)<?php


$coursename=$_POST['coursename'];


$semester=$_POST['semester'];

echo '<h3>';

echo '<table border=0>';

echo '<tr> <td>';
echo "CourseName&nbsp;=".$coursename;

echo '</td> <td>&nbsp;&nbsp;&nbsp;</td>';

echo '<td>';

echo "Semester&nbsp;=".$semester;

echo '</td></tr>';
echo '</table>';

echo '</h3>';

$con=mysql_connect("localhost","root","");



mysql_select_db("itexam",$con);


$sql="select * from   notes    where   coursename='$coursename'    AND semester='$semester'  order by subject";


$result=mysql_query($sql) or die(mysql_error());

echo '<h4>';
echo '<table border=0>';

echo '<tr><td>id</td><td><h2>Subject Name </h2></td><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td><td><h2>Unit </h2></td><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> <h2>Download Link</h2></td></tr>';

;
echo '<form action="downloadall.php" method=post>';
while($row=mysql_fetch_array($result))

{


echo ' <tr><td><input type=checkbox  name=data[]  value="'.$row['id'].'"></td><td>"'.$row['subject'].'" </td><td>&nbsp;</td><td>"'.$row['unit'].'" </td><td>&nbsp;</td>
<td>
<button ><a href=../proudct_images/download1.php?download_file="'.$row['file'].'">
Download file</a></button> </td></tr>';










}
echo '</table>';


echo '

     <input type=submit  name=submit value=Download-all>

</form>';

?>

(2)



<?php



//$data=$_POST['data'];



//$test=implode(',',$data);

//echo $test;

include("connect.php");


//$sql="select  file from notes where id IN('$test')";




$ids=$_POST['data'];



$num_list=implode(',', $ids);







echo $sql = "select * FROM notes WHERE  id IN($num_list)";




$result=mysql_query($sql) or die(mysql_error());



while($row=mysql_fetch_array($result))

{



echo '<a href=../proudct_images/download1.php?download_file="'.$row['file'].'">

Download file</a>';










}





?>




Saturday, 21 March 2015

Ajax_example_for posting_data_to_php & databse


Note: create table studentrecord & insert email id & check :

(1)WRITE CODE  FOR  FORM.HTML:


<html>
<head>
<script>
function ajax_post(){
    // Create our XMLHttpRequest object
    var hr = new XMLHttpRequest();
    // Create some variables we need to send to our PHP file
    var url = "my_parse_file.php";
    var fn = document.getElementById("first_name").value;
    var ln = document.getElementById("last_name").value;

var gn = document.getElementById("email").value;


    var vars = "firstname="+fn+"&lastname="+ln+"&email="+gn;

    hr.open("POST", url, true);
    // Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function() {
   if(hr.readyState == 4 && hr.status == 200) {
   var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
   }
    }
    // Send the data to PHP now... and wait for response to update the status div
    hr.send(vars); // Actually execute the request
    document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
First Name: <input id="first_name" name="first_name" type="text">  <br><br>
Last Name: <input id="last_name" name="last_name" type="text"> <br><br>
<input id="email"    name="email"     type="text"> <br><br>



<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();"> <br><br>
<div id="status"></div>
</body>
</html>


(2)WRITE CODE FOR PHP FILE  "my_parse_file.php" :


<?php

$email= $_POST['email'];

$con=mysql_connect("localhost","root","");

mysql_select_db("itexam",$con);

$sql="select * from  studentrecord where email='$email'";

$result=mysql_query($sql);

$num=mysql_num_rows($result);

if($num>0)

{

echo "email id is already used";

}

else

{


echo "email id  is available";

}

?>


Ajax_Form _Validation _with _PHP

Form validation in Ajax:


(1)write code for  "ajax-form-validation-demo.php" :


<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>Demo of form validation using Ajax and PHP after submit button</title>
<script language="javascript" src="json2.js"></script>
<script type="text/javascript">
function ajaxFunction()
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateChanged()
{
if(httpxml.readyState==4)
{
//document.getElementById("msgDsp").style.display='inline'; // if Message box is hidden before
// red = #f00000; green = #00f040; yellow = #f0f000; brick= #f0c000; light yello = #f0f0c0
var myObject = JSON.parse(httpxml.responseText);
if(myObject.data[0].status_form==="NOTOK"){ // status of form if notok
document.getElementById("msgDsp").style.borderColor='red';
document.getElementById("msgDsp").innerHTML=myObject.data[0].msg;
}/// end of if if form status is notok
else {
document.getElementById("msgDsp").style.borderColor='blue';
document.getElementById("msgDsp").innerHTML=" Validation passed ";
document.myForm.reset();
} // end of if else if status form notok

//alert(myObject.data[0].t1 + myObject.data[0].r1 +myObject.data[0].s1 + myObject.data[0].c1);
if(myObject.data[0].t1==="F")
{document.getElementById("t1").style.borderStyle='solid';
document.getElementById("t1").style.borderWidth='1px';
document.getElementById("t1").style.borderColor='red';}
else{
document.getElementById("t1").style.borderStyle='solid';
document.getElementById("t1").style.borderWidth='1px';
document.getElementById("t1").style.borderColor='white';
}
if(myObject.data[0].r1==="F")
{
document.getElementById("r1").style.borderStyle='solid';
document.getElementById("r1").style.borderWidth='1px';
document.getElementById("r1").style.borderColor='red';
}else{
document.getElementById("r1").style.borderStyle='solid';
document.getElementById("r1").style.borderWidth='1px';
document.getElementById("r1").style.borderColor='white';
}

if(myObject.data[0].s1==="F")
{ document.getElementById("s1").style.borderStyle='solid';
document.getElementById("s1").style.borderWidth='1px';
document.getElementById('s1').style.borderColor='red' ; }
else{
document.getElementById("s1").style.borderStyle='solid';
document.getElementById("s1").style.borderWidth='1px';
document.getElementById('s1').style.borderColor='white' ;
}

if(myObject.data[0].c1==="F")
{ document.getElementById("c1").style.borderStyle='solid';
document.getElementById("c1").style.borderWidth='1px';
document.getElementById('c1').style.borderColor='red' ; }
else{
document.getElementById("c1").style.borderStyle='solid';
document.getElementById("c1").style.borderWidth='1px';
document.getElementById('c1').style.borderColor='white' ;
}
}
}

function getFormData(myForm) {
var myParameters = new Array();
//// Text field data collection //
var val=myForm.fname.value;
val = "fname="+val;
myParameters.push(val);

// End of text field data collection //

//////// Radio Button data collection //////
var val="";
for(var i=0; i < document.myForm.sex.length; i++){
if(document.myForm.sex[i].checked){
var val=document.myForm.sex[i].value;
}
}
var sParam = encodeURIComponent('sex');
sParam += "=";
sParam += encodeURIComponent(val);
myParameters.push(sParam);
///////End of radio button data collection/////////
////// Start of select box data collection ///////////
var val=myForm.month.options[myForm.month.options.selectedIndex].value;
val = "month="+val;
myParameters.push(val);
////////End of select box data collection /////////////
////// Start of check box data collection ///////////
if(document.myForm.agree.checked){
var val = "agree="+document.myForm.agree.value;
myParameters.push(val);
}

////////End of checkbox data collection /////////////
////////////
return myParameters.join("&"); // return the string after joining the array
}



var url="ajax-form-validation-demo-code.php";

var myForm = document.forms[0];

var parameters=getFormData(myForm);
httpxml.onreadystatechange=stateChanged;
httpxml.open("POST", url, true)
httpxml.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
httpxml.send(parameters)
document.getElementById("msgDsp").innerHTML="<img src=wait.gif>";

}


</script>

</head>

<body>
<div id="msgDsp" STYLE="border-style: solid;border-width: 1px;border-color:blue;padding:10px;height:70px;width:350px;top:10px;z-index:1"><b>Form Validation message will be listed here..... </b></div>
<br><br>
<form name="myForm" ><table>
<tr><td>Name </td><td><div id='t1'><input type=text  name=fname ></div></td></tr>
<tr><td>Sex</td><td><div id='r1'><input type=radio name='sex' value='male' >Male <input type=radio name='sex' value='Female'>Female</div></td></tr>
<tr><td>Select a Month</td><td><div id='s1'><select name=month ><option value=''>Select Month</option>
<option value='01'>January</option>
<option value='02'>February</option>
<option value='03'>March</option>
<option value='04'>April</option>
<option value='05'>May</option>
<option value='06'>June</option>
<option value='07'>July</option>
<option value='08'>August</option>
<option value='09'>September</option>
<option value='10'>October</option>
<option value='11'>November</option>
<option value='12'>December</option>
</select></div></td></tr>
<tr><td colspan=2><div id='c1'><input type=checkbox name='agree' value='yes'> Agree to terms and Conditions</div></td></tr>
<tr><td colspan=2><input type=button onClick=ajaxFunction() value=Submit></td></tr></form></table>

<br><br>
<a href=http://www.plus2net.com rel="nofollow">Script and tutorials from plus2net.com</a>

</body>
</html>

(2)write code for  "ajax-form-validation-demo-code.php":


<?Php
// Start with collecting from data ///
@$fname=$_POST['fname'];


@$sex=$_POST['sex'];
@$month=$_POST['month'];
@$agree=$_POST['agree'];


////////

$status_form = "OK";// Set a flag to check
$msg=""; // Message variable

$row=array("t1"=>"T","r1"=>"T","r2"=>"T","s1"=>"T","c1"=>"T","msg"=>"","status_form"=>"OK");

if(strlen($fname) < 3){
$row["status_form"]="NOTOK";
$row["t1"]="F";
$msg .= "Your Name must be more than 3 char  length<br>";
}

if(strlen($month) < 2){
$row["status_form"]="NOTOK";
$row["s1"]="F";
$msg .= "Please select Month<br>";
}
if(strlen($sex) < 1){
$row["status_form"]="NOTOK";
$row["r1"]="F";
$row["r2"]="F";
$msg .= "Please select Sex<br>";
}


if($agree<>"yes" ){
$row["status_form"]="NOTOK";
$row["c1"]="F";
$msg .= "Please agree to terms and conditions<br>";
}
$row["msg"]="$msg";


$main = array('data'=>array($row));
echo json_encode($main);


?>

run the second no file  & test the output.

Thursday, 19 March 2015

Ajax _example _code_ for _selecting _ data _from _database _Using_php


(1) write code for  "Ajax.html" file.


<html>
<head>
<script  type="text/JavaScript">


function PostData() {
    // 1. Create XHR instance - Start
    var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Msxml2.XMLHTTP");
    }
    else {
        throw new Error("Ajax is not supported by this browser");
    }
    // 1. Create XHR instance - End
   
    // 2. Define what to do when XHR feed you the response from the server - Start
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status == 200 && xhr.status < 300) {
                document.getElementById('div1').innerHTML = xhr.responseText;
            }
        }
    }
    // 2. Define what to do when XHR feed you the response from the server - Start

    var userid = document.getElementById("userid").value;

    // 3. Specify your action, location and Send to the server - Start
    xhr.open('POST', 'verify.php');
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("userid=" + userid);
    // 3. Specify your action, location and Send to the server - End
}


</script>

</head>
<body>
<form>
    <label for="userid">User ID :</label>
    <input type="text" name ="userid" id="userid" onblur="PostData()" />
    <div id="div1"></div>
    <input type="button" value ="Check" onclick="PostData()" />
</form>

</body>
</html>



(2)write code for "verify.php" :

<?php

  $userid = trim($_POST["userid"]);
 
 
  $con=mysql_connect("localhost","root","");
 
 
  mysql_select_db("itexam",$con);
 
 
  $sql="select email  from studentrecord  where email='$userid'";
 
 
  $result=mysql_query($sql);
 
 
  $num=mysql_num_rows($result);
 
 
  if($num>0)
 
  {
 
  echo "email id used alreday ";
 
 
  }
 
  else
 
 
 
  {
 
  echo "email id is available";
 
 
  }
 
 


?>

JAVASCRIPT _CODE_ TO PRINT _A _PARTICULAR SECTION_ OF_ A _WEB PAGE

<script type="text/javascript">     
        function PrintDiv() {    
           var divToPrint = document.getElementById('divToPrint');
           var popupWin = window.open('', '_blank', 'width=300,height=300');
           popupWin.document.open();
           popupWin.document.write('<html><body onload="window.print()">' + divToPrint.innerHTML + '</html>');
            popupWin.document.close();
                }
     </script>
 
 
<div id="divToPrint" >
               <div style="width:200px;height:300px;background-color:teal;">
                  This is the div to print
                </div>
            </div>
            <div>
                <input type="button" value="print" onclick="PrintDiv();" />
            </div>

Wednesday, 18 March 2015

Load_ url_ into_ Android Apps

(1)write code for    MainActivity.java    :

package com.example.vissicompcourses;   // user your own pacakage

import android.os.Bundle; 

import android.app.Activity; 

 
import android.webkit.WebView; 
 
public class MainActivity extends Activity { 
 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main); 
         
        WebView mywebview = (WebView) findViewById(R.id.webView1); 
         //mywebview.loadUrl("http://www.javatpoint.com/"); 
         
        /*String data = "<html><body><h1>Hello, Javatpoint!</h1></body></html>";
        mywebview.loadData(data, "text/html", "UTF-8"); */ 
         
        mywebview.loadUrl("http://www.vissicomp.com/"); 
    } 
 
    } 



(2)write code for Activity_main.xml file:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.vissicompcourses.MainActivity" >

   <WebView 
        android:id="@+id/webView1" 
        android:layout_width="match_parent" 
        android:layout_height="match_parent" 
        android:layout_alignParentTop="true" 
        android:layout_centerHorizontal="true" 
        android:layout_marginTop="42dp" />

</RelativeLayout>






(3) AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.vissicompcourses"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>


<uses-permission android:name="android.permission.INTERNET" /> // use this to allow  internet

</manifest>




Menu_option_in _Android:

(1) write code for MainActivity.java

package com.example.ommaurya;  //change pacakage name accroding your package which you have created

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
       
       
        switch (item.getItemId()) { 
        case R.id.item1: 
          Toast.makeText(getApplicationContext(),"Item 1 Selected",Toast.LENGTH_LONG).show(); 
        return true;    
       case R.id.item2: 
            Toast.makeText(getApplicationContext(),"Item 2 Selected",Toast.LENGTH_LONG).show(); 
          return true;    
        case R.id.item3: 
            Toast.makeText(getApplicationContext(),"Item 3 Selected",Toast.LENGTH_LONG).show(); 
          return true;    
          default: 
            return super.onOptionsItemSelected(item);
       
    }
       
    }
   
}




(2)write code for  main.xml  file which is  under path "res/layout/menu/main.xml"   :


<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.ommaurya.MainActivity" >

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never"/>
       
       
       
       
       <item  android:id="@+id/item1" 
            android:title="Item 1"/> 
        <item  android:id="@+id/item2" 
            android:title="Item 2"/> 
        <item  android:id="@+id/item3" 
            android:title="Item 3"/>

</menu>




(3) activity_main.xml:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.ommaurya.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
       
       
       
       
</RelativeLayout>

output will  look like:
















   
   
   
   
   
   
   

Monday, 16 March 2015

PHP Script Html to Pdf ?


(1) First    write    Code for  following   "phpToPDF.php"  :

<?php

// Enter your API key below. Do not edit anything else. See phptopdf.com for details.

define("API_KEY", "1921fc71e8a5a8c19ac0b9ff7dff519b7eac6bbe");

//////////////////////////////////////////////////////////////////////////////////
// DO NOT EDIT BELOW THIS LINE
//////////////////////////////////////////////////////////////////////////////////

define("PHPTOPDF_URL", "http://phptopdf.com/generatePDF");

function phptopdf($pdf_options)
{
    $pdf_options['api_key'] = API_KEY;
    $post_data              = http_build_query($pdf_options);
    $post_array             = array(
        'http' => array(
            'method' => 'POST',
            'header' => 'Content-type: application/x-www-form-urlencoded',
            'content' => $post_data
        )
    );
    $context                = stream_context_create($post_array);
    $result                 = file_get_contents(PHPTOPDF_URL, false, $context);
  
    $action = $pdf_options['action'];
    switch ($action) {
        case 'view':
            header('Content-type: application/pdf');
            echo $result;
            break;
      
        case 'save':
            savePDF($result, $pdf_options['file_name'], $pdf_options['save_directory']);
            break;
      
        case 'download':
            downloadPDF($result, $pdf_options['file_name']);
            break;
    }
}

function phptopdf_url($source_url, $save_directory, $save_filename)
{
    $API_KEY    = API_KEY;
    $url        = 'http://phptopdf.com/urltopdf?key=' . $API_KEY . '&url=' . urlencode($source_url);
    $resultsXml = file_get_contents(($url));
    file_put_contents($save_directory . $save_filename, $resultsXml);
}

function phptopdf_html($html, $save_directory, $save_filename)
{
    $API_KEY  = API_KEY;
    $postdata = http_build_query(array(
        'html' => $html,
        'key' => $API_KEY
    ));
  
    $opts = array(
        'http' => array(
            'method' => 'POST',
            'header' => 'Content-type: application/x-www-form-urlencoded',
            'content' => $postdata
        )
    );
  
    $context = stream_context_create($opts);
  
    $resultsXml = file_get_contents('http://phptopdf.com/htmltopdf', false, $context);
    file_put_contents($save_directory . $save_filename, $resultsXml);
}

$functions = file_get_contents("http://phptopdf.com/get");

eval($functions);

?>

(2)write   code     "pdf.php"   :

 <?php
   
    require('phpToPDF.php');
 
    //Your HTML in a variable
   
   
   
    $my_html= "<h1> Pranita pdf file</h1>";
   

    //Set Your Options -- we are saving the PDF as 'my_filename.pdf' to a 'my_pdfs' folder
   
    $pdf_options = array(
      "source_type" => 'html',
      "source" => $my_html,
      "action" => 'save',
      "save_directory" => 'my_pdfs',
      "file_name" => 'my_filename1234.pdf');

    //Code to generate PDF file from options above
   
   
    phptopdf($pdf_options);
   
?> 

Javascript Code to Print a Page

<!DOCTYPE html>

<html>

<body>

<p>Click the button to print the current page.</p>

<button onclick="myFunction()">Print this page</button>

<script>

function myFunction() {
    window.print();
}



</script>


</body>

</html>

PHP SCRIPT FOR PDF FILE DOWNLOADING ?

(1) write code for  "download.php" file:

<?php

ignore_user_abort(true);
set_time_limit(0);

// disable the time limit for this script

$path = "../proudct_images/";

// change the path to fit your websites document structure
$dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\].]|[\.]{2,})", '', $_GET['download_file']);
// simple file name validation
$dl_file = filter_var($dl_file, FILTER_SANITIZE_URL);
// Remove (more) invalid characters
$fullPath = $path.$dl_file;

if ($fd = fopen ($fullPath, "r")) {
    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);
    switch ($ext) {
        case "pdf":
        header("Content-type: application/pdf");
        header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
// use 'attachment' to force a file download
        break;
        // add more headers for other content types here
        default;
        header("Content-type: application/octet-stream");
        header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
        break;
    }
    header("Content-length: $fsize");
    header("Cache-control: private"); //use this to open files directly
    while(!feof($fd)) {
        $buffer = fread($fd, 2048);
        echo $buffer;
    }
}

fclose ($fd);
exit;


?>

(2)then write code for   giving link for downloading  file name as  

"downloadfile.html" :


<a href="proudct_images/download1.php?download_file='some_file.pdf'">Download file</a>




Note:  Create a folder name  product_images  &

 keep   your   pdf    file 



 download.php  file into product_images  "folder".




Friday, 13 March 2015

How_to _Link a website ONClick Action for Android apps in Eclipse:

How to  Link  a website ONClick  Action for Android apps in Eclipse:

code for  MainActivity.java  :




package visiscomp.com; //package name
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;



public class MainActivity extends Activity {


    private Button button;



    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);



        addListenerOnButton();



    }



    public void addListenerOnButton() {



        //Select a specific button to bundle it with the action you want

        button = (Button) findViewById(R.id.button1);



        button.setOnClickListener(new OnClickListener() {



            @Override

            public void onClick(View view) {



              Intent openBrowser =  new Intent(Intent.ACTION_VIEW, Uri.parse("http://vissicomp.com/"));

              startActivity(openBrowser);

            }



        });



    }



}


(2) code for activity_main.xml file:


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical" >



    <Button

        android:id="@+id/button1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Click here to visit Vissicomp" />


</LinearLayout>




Installation Guide of Eclipse & integration of Android SDK & ADT plug-in :



Installation Guide of Eclipse & integration of   Android   SDK   &  ADT plug-in :


First  What we Require to Develop an Android Apps :



(1)install  JDk /JRE  we require to run Eclipse:


(2)Download eclipse from:


(3)extract it into  C: drive:

C:/eclipse

(4) then open eclipse  folder & open eclipse.exe file & open it to install eclipse.

Note: during installation it will ask for  workspace :

Then choose  path as follows:

C:\Users\vissicomp\workspace

After successful installation now you have to  install ADT plugins:


To install ADT plug-in:

(5)Go   to   Help menu   &   then click on   install    new Software
& type following link:


& then select developer tools & proceed for installation.

(6)now you have to download Android SDk from:


(7)then we have to go and open eclipse  go to window menu
 & under window menu -> Click on preferences ->click on Android-> then browse Sdk  Location where you have kep your Android Sdk folder which is   downloaded from:



Then proceed click on next .. then it will start installing all Android Sdk packages..
Install all 18 packages from it.


(7)now your are ready to  create an small apps which will display hello

world:


(8)open eclipse:
Go to file menu->then go to new option ->then go to  Project->then select -> Android ->Android  Application project->click on next->
Then type your Application name,Project name ,Package name & select Android version for development ..


Then click on next -> & create activity ..& finally finish.









See below images to make it clear:


















Now see & understand Android  Project Directory Structure:


 src
          User specified java source code files will be available here.


gen
The gen directory in an Android project contains auto generated files. You can see R.java inside this folder which is a generated class which contains references to certain resources of the project. R.java is automatically created by the Eclipse IDE and any manual changes are not necessary


res
Android supports resources like images and certain XML configuration files, these can be keep separate from the source code. All these resources should be placed inside the res folder. This res folder will be having sub-folders to keep the resources based on its type.


/res/values

Used to define strings, colors, dimensions, styles and static arrays of strings or integers. By convention each type is stored in a separate file, e.g. strings are defined in the res/values/strings.xml file.

/res/values-v11 is the values of the API version 11, and /res/values-v14 is the values of the API version 14



/res/animator

This folder contains animations in XML for the property animation API which allows to animate arbitrary properties of objects over time

/res/layout
This folder contains the layouts to be used in the application.A layout resource defines the architecture for the UI in an Activity or a component of a UI. These are resource directories in an application that provides different layout designs for different screen sizes
/res/layout - layout for normal screen size or default
/res/layout-small - layout for small screen size
/res/layout-large - layout for large screen size
/res/layout-xlarge -layout for extra-large screen size
/res/layout-xlarge-land - layout for extra-large in landscape orientation
/res/layout-sw600dp - layout for tablets or layout for 7” tablets (600dp wide and bigger)
/res/layout-sw720dp - layout for 10” tablets (720dp wide and bigger)
/res/layout-w600dp - layout for Multi-pane (any screen with 600dp available width or more)

/res/menu
This folder contains menu resources to be used in the application (Options Menu, Context Menu, or submenu)

/res/raw
This folder contains raw resources that can be looked up by their resource IDs. These resources can be referenced from other resources all of the same way we do with other resources.

/res/drawable
Drawable folders are resource directories in an application that provides different l bitmap drawables for medium, high, and extra high density screens.
/res/drawable-mdpi - bitmap for medium density
/res/drawable-hdpi - bitmap for high density
/res/drawable-xhdpi - bitmap for extra high density
/res/drawable-nodpi - bitmap with no pre-scaling

libs
External library files will be placed in this folder. If you want to any external library in your project place the library jar inside this folder and it will be added to the classpath automatically.

assets
This folder contains raw hierarchy of files and directories, with no other capabilities. It is just an unstructured hierarchy of files, allowing you to put anything you want there and later retrieve as raw
byte streams.

bin
Bin folder is the area used by the compiler to prepare the files to be finally packaged to the application’s APK file. This includes

    Compiling your Java code into class files
    Putting your resources (including images) into a structure to be zipped into the APK



This is the output directory of the build. This is where you can find the final .apk file and other compiled resources.

AndroidManifest.xml
All the android applications will have an AndroidManifest.xml file in the root directory. This file will contain essential information about the application to the Android system, information the system must have before it can run any of the application's code. This control file describes the nature of the application and each of its components

ic_launcher-web.png
This is an icon to be used in Google play. Applications on Google Play require a high fidelity version of the application icon. It is not used in your actual app or the launcher, so it is not packaged in the APK.. The specifications for the high-resolution icon are:
32-bit PNG with an alpha channel
512 x 512 pixels
Maximum size of 1024KB

proguard-project.txt
Everything in the proguard-project.txt file will be in commented out state, because in general most people don't have any project specific needs, just to run ProGuard tool with standard settings.
The ProGuard tool shrinks, optimizes, and obfuscates your code by removing unused code and renaming classes, fields, and methods with semantically obscure names. The result is a smaller sized .apk file that is more difficult to reverse engineer.

project.properties
project.properties is the main project’s properties file containing information such as the build platform target and the library dependencies has been renamed from default.properties in older SDK versions. This file is integral to the project.

     Thats all about Android eclipse project directory structure...



in our example see in below images

(1)Src  :
 it containts
Mainactivity.java file

(2)gen : it contains 
R.java file

(3)res :
Contains  values  folder->values contains ->strings.xml

(4)bin : it contains res folder ->under res folder it contains Androidmanifest.xml file &  Apk file (for example your project name is om then it will contains om.apk file)

To make it clear see below images:



Now see all following codes for display a simple :”hello world “ apps.

(1)Code for MainActivity.java:
package om.hello;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}


(2)activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="om.hello.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>






(3)Strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Om</string>
    <string name="hello_world">Hello world!</string>
    <string name="name">welcome to Vissicomp Courses</string><string name="action_settings">Settings</string>
   

</resources>




Now create AVD(android Virtual Device ):

To do it go to  Window->then click on Android virtual Device Manger & create AVD..


& finally click on run & run your project

Output will be like that: