Friday, 20 November 2015

chat-Application-in-php

Step 1. HTML
As usual, we start with the HTML.

This main chat window.

index.html   file code :

<frameset rows="65%,35%" framespacing="1" frameborder="yes" border="1" bordercolor="#FF0000">

    <frame src="messages.php" name="main_frame">

    <frame src="main.php" name="login_frame" scrolling="no" noresize target="middle">

</frameset>
This is login form code.

login_form.html  file code :

<link type="text/css" rel="stylesheet" href="styles.css" />



<form class="login_form" method="post" action="main.php">

 <div>Username: <input type="text" name="username" /></div>

 <div>Password: <input type="password" name="password" /></div>

 <div><input type="submit" value="Login" name="Login" /></div>

</form>

<div>You can use username "User1" or "User2" or "User3" and password "qwerty" to login in system</div>
Here are new 3 template files to chat (2 to messages box and 1 to send message form):

chat_begin.html file code:
<link type="text/css" rel="stylesheet" href="styles.css" />



<div class="chat_main">

 <h3>Chat</h3>
chat_end.html file code:


</div>
chat_input.html file code:

<link type="text/css" rel="stylesheet" href="styles.css" />



<form class="submit_form" method="post" action="main.php">

 <div><input type="text" name="s_message" /><input type="submit" value="Say" name="s_say" /></div>

</form>

<div>You can type anything in chat</div>
Step 2. CSS
Here are used CSS styles.

styles.css  file   code:

.login_form {

 border: 1px solid #AAA;

 padding:10px;

}



h3 {margin-top:3px;}



.chat_main {

 border:1px solid #AAA;

 -moz-box-shadow:0 0 10px #ccc;

 -webkit-box-shadow: 0 0 10px #ccc;

 width:350px;

 padding:10px;

 background:#f3f3f3;

}



.message {

 border:1px solid #AAA;

 margin:4px;

 padding:5px;

 -moz-border-radius:7px;

 -webkit-border-radius:7px;

 background:#ffffff;

}



.textf {

-moz-box-shadow:0 0 10px #CCCCCC;

-webkit-box-shadow:0 0 10px #CCCCCC;

border:1px solid #CCCCCC;

height:40px;

}



.submit {

-moz-border-radius:7px;

-webkit-border-radius:7px;

background:#F3F3F3;

border:1px solid #CCCCCC;

font-size:16px;

font-weight:bold;

height:35px;

margin-left:10px;

padding:5px;

}

.message span {

 font-size:10px;

 color:#888;

 margin-left:10px;

}



.submit_form {

 margin:10px 0px;

}

Step 3.  SQL
We will need to execute next SQL in our database.


CREATE TABLE  `s_chat_messages` (

`id` INT(11) NOT NULL AUTO_INCREMENT ,

`user` VARCHAR(255) NOT NULL ,

`message` VARCHAR(255) NOT NULL ,

`when` INT(11) NOT NULL ,

PRIMARY KEY (`id`)

) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Step 4. PHP
As you remember – we had ready easy authentication system. I moved it to external library file (inc/login.inc.php). This will useful for us – now code more structured and it comfortable to use in different places of code.

After I created new library to work with chat (inc/chat.inc.php). This class have next functions:

acceptMessages – function accept sent messages and store it in DB table

getMessages – return list of last 15 messages

After I created 2 last files: messages.php and main.php. First file used to draw list of messages. It have autoupdate each 5 second (I thing this is enough to our chat). Second draw login form and input field of chat. Where we due logged able to post text in chat.

Ok, here are all used PHP files:

main.php  file code:

<?php



// set error reporting level

if (version_compare(phpversion(), "5.3.0", ">=") == 1)

 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);

else

 error_reporting(E_ALL & ~E_NOTICE);



require_once('inc/login.inc.php');

require_once('inc/chat.inc.php');



// initialization of login system and generation code

$oSimpleLoginSystem = new SimpleLoginSystem();



$oSimpleChat = new SimpleChat();



// draw login box

echo $oSimpleLoginSystem->getLoginBox();



// draw chat application

$sChatResult = 'Need login before using';

if ($_COOKIE['member_name'] && $_COOKIE['member_pass']) {

 if ($oSimpleLoginSystem->check_login($_COOKIE['member_name'], $_COOKIE['member_pass'])) {

 $sChatResult = $oSimpleChat->acceptMessages();

 }

}

echo $sChatResult;



?>

messages.php file code:

<meta http-equiv="refresh" content="5">

<?php



require_once('inc/chat.inc.php');

$oSimpleChat = new SimpleChat();

echo $oSimpleChat->getMessages();



?>

Inc/chat.inc.php   file code:



<?php

// simple chat class
class SimpleChat {

    // DB variables
    var $sDbName;
    var $sDbUser;
    var $sDbPass;

    // constructor
    function SimpleChat() {
        //mysql_connect("localhost","username","password");
        $this->sDbName = 'amrapali';
        $this->sDbUser = 'root';
        $this->sDbPass = '';
    }

    // adding to DB table posted message
    function acceptMessages() {
        if ($_COOKIE['member_name']) {
            if(isset($_POST['s_say']) && $_POST['s_message']) {
                $sUsername = $_COOKIE['member_name'];

                //the host, name, and password for your mysql
                $vLink = mysql_connect("localhost", $this->sDbUser, $this->sDbPass);

                //select the database
                mysql_select_db($this->sDbName);

                $sMessage = mysql_real_escape_string($_POST['s_message']);
                if ($sMessage != '') {
                    mysql_query("INSERT INTO `s_chat_messages` SET `user`='{$sUsername}', `message`='{$sMessage}', `when`=UNIX_TIMESTAMP()");
                }

                mysql_close($vLink);
            }
        }

        ob_start();
        require_once('chat_input.html');
        $sShoutboxForm = ob_get_clean();

        return $sShoutboxForm;
    }

    function getMessages() {
        $vLink = mysql_connect("localhost", $this->sDbUser, $this->sDbPass);

        //select the database
        mysql_select_db($this->sDbName);

        //returning the last 15 messages
        $vRes = mysql_query("SELECT * FROM `s_chat_messages` ORDER BY `id` ASC LIMIT 15");

        $sMessages = '';

        // collecting list of messages
        if ($vRes) {
            while($aMessages = mysql_fetch_array($vRes)) {
                $sWhen = date("H:i:s", $aMessages['when']);
                $sMessages .= '<div class="message">' . $aMessages['user'] . ': ' . $aMessages['message'] . '<span>(' . $sWhen . ')</span></div>';
            }
        } else {
            $sMessages = 'DB error, create SQL table before';
        }

        mysql_close($vLink);

        ob_start();
        require_once('chat_begin.html');
        echo $sMessages;
        require_once('chat_end.html');
        return ob_get_clean();
    }
}

?>
Inc/login.inc.php  chat code:


<?php

// class SimpleLoginSystem
class SimpleLoginSystem {

    // variables
    var $aExistedMembers; // Existed members array

    // constructor
    function SimpleLoginSystem() {
        $this->aExistedMembers = array(
            'User1' => 'd8578edf8458ce06fbc5bb76a58c5ca4',
            'User2' => 'd8578edf8458ce06fbc5bb76a58c5ca4',
            'User3' => 'd8578edf8458ce06fbc5bb76a58c5ca4'
                                               
        );
    }

    function getLoginBox() {
        ob_start();
        require_once('login_form.html');
        $sLoginForm = ob_get_clean();

        $sLogoutForm = '<a href="'.$_SERVER['PHP_SELF'].'?logout=1">logout</a>';

        if ((int)$_REQUEST['logout'] == 1) {
            if (isset($_COOKIE['member_name']) && isset($_COOKIE['member_pass']))
                $this->simple_logout();
        }

        if ($_REQUEST['username'] && $_REQUEST['password']) {
            if ($this->check_login($_REQUEST['username'], MD5($_REQUEST['password']))) {
                $this->simple_login($_REQUEST['username'], $_REQUEST['password']);
                return 'Hello ' . $_REQUEST['username'] . '! ' . $sLogoutForm;
            } else {
                return 'Username or Password is incorrect' . $sLoginForm;
            }
        } else {
            if ($_COOKIE['member_name'] && $_COOKIE['member_pass']) {
                if ($this->check_login($_COOKIE['member_name'], $_COOKIE['member_pass'])) {
                    return 'Hello ' . $_COOKIE['member_name'] . '! ' . $sLogoutForm;
                }
            }
            return $sLoginForm;
        }
    }

    function simple_login($sName, $sPass) {
        $this->simple_logout();

        $sMd5Password = MD5($sPass);

        $iCookieTime = time() + 24*60*60*30;
        setcookie("member_name", $sName, $iCookieTime, '/');
        $_COOKIE['member_name'] = $sName;
        setcookie("member_pass", $sMd5Password, $iCookieTime, '/');
        $_COOKIE['member_pass'] = $sMd5Password;
    }

    function simple_logout() {
        setcookie('member_name', '', time() - 96 * 3600, '/');
        setcookie('member_pass', '', time() - 96 * 3600, '/');

        unset($_COOKIE['member_name']);
        unset($_COOKIE['member_pass']);
    }

    function check_login($sName, $sPass) {
        return ($this->aExistedMembers[$sName] == $sPass);
    }
}


?>

Friday, 13 November 2015

Registration Module Code

Step 1 : 

create table  studentrecord
(id  int primary key auto_increment,
 name   varchar(20),
 email varchar(20),
 phone  varchar(20),
 password varchar(20));


(1)step one write code for  file  "registration.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 = "validation.php";
    var fn = document.getElementById("name").value;
    var en = document.getElementById("email").value;
     var pn = document.getElementById("phone").value;
var pd = document.getElementById("password").value;
var cpd = document.getElementById("cpassword").value;
var cap=document.getElementById("captcha").value;
 var vars = "name="+fn+"&email="+en+"&phone="+pn+"&password="+pd+"&cpassword="+cpd+"&captcha="+cap;
    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 with PHP examples</h2>
Name:<input id="name" name="name" type="text"><br><br>
EMAIL:<input id="email" name="email" type="text"><br><br>
PHONE<input id="phone"    name="phone"     type="text"><br><br>
PASSWORD<input id="password"    name="password"     type="text"><br><br>
cPASSWORD<input id="cpassword"    name="cpassword"     type="text"><br><br>
(2+ 2)answer<input id="captcha"    name="captcha"     type="text"><br><br>
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();"> <br><br>
<div id="status"></div>
</body>
</html>


output:



(2)Now    write  code     for  "validation.php " :


<?php

$name=$_POST['name'];

$email=$_POST['email'];

$phone=$_POST['phone'];

$password=$_POST['password'];

$cpassword=$_POST['cpassword'];

$capcha=$_POST['captcha'];

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

mysql_select_db("aniket",$con);

//include("connect.php");

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

$result=mysql_query($sql);

$num=mysql_num_rows($result);

$regex = "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$^"; 

$errormsg=array();

 if($capcha=="" )
 {
 $errormsg="Plase Enter Your Answer";
 }
 else if($capcha==4)
 {
  $errormsg="";

 }
 else 
 {
 $errormsg="incorrect answer";
 }















if($password!==$cpassword)

{

$errormsg="password did not match";



}

if($password=="")

{

$errormsg="enter  your password ";

}
if($phone=="")

{

$errormsg="enter  your phone ";

}

if(!preg_match( $regex, $email ))

{

$errormsg="enter your valid email";



}
if($email=="")

{

$errormsg="enter  your email ";

}

if($name=="")

{

$errormsg="enter  your Name ";

}

if(empty($errormsg))

{



if($num>0)
{

echo "<font color=red>email id is already used please use another email id</font>";

}



else  

{


$sql1="insert into studentrecord(name,email,phone,password)values('$name','$email','$phone','$password')";

mysql_query($sql1);

echo "<font color=red>successfully  registered </font>";

}


}

else

{


echo"<font color=red> $errormsg </font>";


}


?>


==============================================================================================================================================
Another example:

<!DOCTYPE HTML>  
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>  

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr =$commentErr= "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $nameErr = "Name is required";
  } else {
    $name = test_input($_POST["name"]);
  }
  
  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
  }
    
  if (empty($_POST["website"])) {
    $websiteErr = "enter your website url";
  } else {
    $website = test_input($_POST["website"]);
  }

  if (empty($_POST["comment"])) {
    $commentErr = "enter your comment";
  } else {
    $comment = test_input($_POST["comment"]);
  }

  if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
  } else {
    $gender = test_input($_POST["gender"]);
  }
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
  Name: <input type="text" name="name">
  <span class="error">* <?php echo $nameErr;?></span>
  <br><br>
  E-mail: <input type="text" name="email">
  <span class="error">* <?php echo $emailErr;?></span>
  <br><br>
  Website: <input type="text" name="website">
  <span class="error"><?php echo $websiteErr;?></span>
  <br><br>
  Comment: <textarea name="comment" rows="5" cols="40"></textarea>
  <br><br>
  Gender:
  <input type="radio" name="gender" value="female">Female
  <input type="radio" name="gender" value="male">Male
  <span class="error">* <?php echo $genderErr;?></span>
  <br><br>
  <input type="submit" name="submit" value="Submit">  
</form>

<?php
if(empty($emailErr) && empty($nameErr) && empty($genderErr )&& empty($websiteErr))
{
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
}
?>

</body>

</html>


============Registration using php for email ,contact ,fullname  =====================
(1)write code for userregistration.html file:

<html>
<head>
<title>
PHP FORM VALIDATION BY OM SIR
</title>

<link rel="stylesheet" href="bootstrap.min.css">

 <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>


<script type="text/javascript">
$(document).ready(function (event) {
// triggered when the form submitted
$("#myform").on('submit',(function(event) {
event.preventDefault();
$("#response").empty();
$.ajax({
// URL to move the uploaded image file to server
url: "submit.php",
// Request type
type: "POST",
// To send the full form data
data: new FormData(this),
contentType: false,  
processData:false,
// UI response after the file upload
success: function(data)
{
$("#response").html(data);
}
});
}));

// Triggered when the image changed (browse)

// Function to show the image as a preview

});
</script>
</head>
<body>
   
<div  class="container">
<img  src="otts.png"  style="min-wdith:300px; width:100%; height:200px;">
<h1>If you are already a Registered User, Please Sign In with your Email & Password</h1>
<div  class="form-group">
<a href="userlogin.html"><input  type="submit"      name="submit" Value="Sign-In"  class="btn-lg btn-primary"></a>
</div>
<h1>New User Registration For OTTS!</h1>

<div id=response>   </div>
<form id=myform  action="" method="post"   >
<div class="form-group">
Name <input type="text" name="name"   class="form-control">
</div>
<div class="form-group">
Contact<input type="text" name="contact"  class="form-control">
</div>
<div class="form-group">
Email<input type="email" name="email"   class="form-control">
</div>
<div class="form-group">
Password<input type="password"  name="password"   class="form-control">
</div>
<div class="form-group">
<input  type="submit"      name="submit"   class="btn-lg btn-primary">
</div>
</form>
</div>

</body>
</html>


(2)WRITE CODE FOR  "submit.php"  file:

<?php

$name=$_POST['name'];

$email=$_POST['email'];

$contact=$_POST['contact'];

$password=$_POST['password'];



$con=mysqli_connect("localhost","root","password","databasename");



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

$result=mysqli_query($con,$sql);

$num=mysqli_num_rows($result);

$regex = "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$^";

$errormsg=array();


if(!preg_match( $regex, $email ))

{

$errormsg="enter your valid email";



}


if($password=="")

{

$errormsg="enter  your password ";

}

if(!preg_match('/^[0-9]{10}+$/', $_POST['contact']))
    {
      $errormsg = 'Invalid Number,Please enter 10 digit mobile number !';
    }
   
   
if($email=="")

{

$errormsg="enter  your email ";

}



if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$errormsg = "Only letters and white space allowed";
}

if (empty($_POST["name"]))
{
$errormsg = "Name is required";

}

if(empty($errormsg))

{



if($num>0)
{

echo "<font color=red>email id is already used please use another email id</font>";

}



else

{


$sql1="insert into userrecord(name,email,contact,password)values('$name','$email','$contact','$password')";

mysqli_query($con,$sql1);

echo "<font color=red>successfully  registered </font>";

}


}

else

{


echo"<font color=red> $errormsg </font>";


}


?>




Php script to create Category & Sub Category

(1)create table cat1:

create table cat1

(

c_id  int primary key auto_increment,

 c_name   varchar(200),

 p_id     varchar(200)


);


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


<?php


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

mysql_select_db("cat",$con) or die(mysql_error());

if(!$con)

{

echo "Not connected";


}




?>


Code for adding Main Category:

(3)write   "main.html"   code:


<form    action="add.php"       method="post">

ADD main Category<input type=text name="name">

<input type="submit"    name="submit"     value="submit">


</form>

(4)write code for "add.php" :


<?php



include("connect.php");



$c_name=$_POST['name'];



$p_id='0';


$sql="insert into cat1(c_name,p_id)values('$c_name','$p_id')";



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


echo "added successfully";



?>


Now below code for adding subcategory:


(5)write code for "disp.php" :


<form   action="subadd.php"      method="post">


<select name="p_id"  >

<?php


include("connect.php");



$sql="select * from  cat1 where  p_id='0'" ;



$result=mysql_query($sql);



while($row=mysql_fetch_array($result))

{


echo '<option   value="'.$row['c_id'].'">';


echo $row['c_name'];

echo '</option>';



}






?>

</select>

sub category name <input type=text name="name">

<input type="submit"  name="submit"   vlaue="add-sub" />


</form>


(6)now write code for "subadd.php"  file:


<?php

include("connect.php");

$c_name=$_POST['name'];

$p_id=$_POST['p_id'];

$sql="insert into cat1(c_name,p_id)values('$c_name','$p_id')";


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


?>


Now code for Display  subcategory on basis of Main category :



(7)write code for  "maincatdisp.php"  file:


<html>



<body>

<form name="myform" action="handle-data.php"  method="post">

<select  name="sub_cat">

<?php


include("connect.php");




$sql="select *   from    cat1  where     p_id='0'" ;




$result=mysql_query($sql);




while($row=mysql_fetch_array($result))

{



echo '<option  value="'.$row['c_id'].'">';

echo $row['c_name'];

echo '</option>';








}



?>

</select>

<input type="submit" name="submit"  value="disp_subcat">

</form>


</body>


</html>


(8)now write code for "handle_data.php file":



<?php


$id=$_POST['sub_cat'];




include("connect.php");


$sql="select c_name  from cat1 where   p_id='$id'";


$result=mysql_query($sql);


echo "sub category";


echo '<br></br>';


while($row=mysql_fetch_array($result))

{


echo $row['c_name'];

echo '<br></br>';


}




?>
===================Display Sub Category using Ajax =============================
(1)write Ajax  code in    "maincatdisp.php"  file:
<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 = "handle_data.php";

    var fn = document.getElementById("sub_cat").value;

   

    var vars = "sub_cat="+fn;

    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>
<select  name="sub_cat"  id="sub_cat">

<?php


include("connect.php");




$sql="select *   from    cat1  where     p_id='0'" ;




$result=mysql_query($sql);




while($row=mysql_fetch_array($result))

{



echo '<option  value="'.$row['c_id'].'">';

echo $row['c_name'];

echo '</option>';








}



?>

</select>
<input type="submit" name="submit"  value="disp_subcat"     onclick="ajax_post();">
<div id="status"></div>
</body>

</html>

(2)we use same  code for "handle_data.php file:

<?php


$id=$_POST['sub_cat'];




include("connect.php");


$sql="select c_name  from cat1 where   p_id='$id'";


$result=mysql_query($sql);


echo "sub category";


echo '<br></br>';


while($row=mysql_fetch_array($result))

{


echo $row['c_name'];

echo '<br></br>';


}




?>

PHP Script for Dynamic Drop down List

(1)create table   account:


create table account
(
id  int(5) primary key auto_increment,
name  varchar(20),
contact  varchar(20),
address  varchar(200),
emailid  varchar(20),
account   varchar(20),
password   varchar(20),
image      varchar(200),
idproof     varchar(200),
addressproof varchar(200));

(2)insert some values  into table

(3) then use following code :


<html>
<head>
<title>
Deposit money
</title>
</head>

<body>
<form   >
<select name=account>
<?php

include("connect.php");

$sql="select * from account";

$result=mysql_query($sql);

while($row=mysql_fetch_array($result))
{

echo '<option value="'.$row['id'].'">';

echo $row['id'];

echo '</option>';

}

?>
</select>
<form>
</body>
</html>
=================================================================================
Dynamic Drop-down code   using   Ajax ...
=================================================================================
Step 1:

(1)create table categories:
Create table   categories
( id  int    primary key   auto_increment,
catname   varchar(200)
);
(2)create table  food:
Create table food
(id  int primary key auto_increment,
food_name varchar(200),
catname  varchar(200)
);

Step 2:

(1)write code for   foold.html   file:
<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 = "food.php";

    var fn = document.getElementById("catname").value;

   
 var vars ="catname="+fn;

    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...";
}

function ajax_submit()
{

    // Create our XMLHttpRequest object

    var hr = new XMLHttpRequest();

    // Create some variables we need to send to our PHP file

    var url = "submit.php";

    var fn = document.getElementById("catname").value;
     var fd = document.getElementById("food_name").value;

   
 var vars ="catname="+fn+"&food_name="+fd;

    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>
<select id=catname  onchange="ajax_post();">
<option value=sweet> sweet</option>
<option value=salty>salty</option>
</select>
 <div id="status"></div>
<input type=submit   name=submit  value=submit   onclick="ajax_submit();">
</body>
</html>
(2)write   code for food.php file:
<html>
<head>
</head>
<body>
<select name=foodname    id=food_name>
<?php
 $food=$_POST['catname'];
 $con=mysql_connect("Localhost","root","");
mysql_select_db("abhi",$con);
$sql="select * from food where catname='$food'";
$result=mysql_query($sql);

while($row=mysql_fetch_array($result))
{
echo '<option value="'.$row['food_name'].'">';
echo $row['food_name'];
echo '<option>';
}
?>
</select>
</body>
</html>
(3)write   code  for submit.php file:
<?php
echo "testing for onclick ".'<Br>';
echo $catname=$_POST['catname'];
echo $foodname=$_POST['food_name'];
?>

==================================================================================================================================================================
PERFECT   DROPDWON  GUIDANCE STEP BY STEP:

Dynamic Drop Down code   with Ajax  :

Step 1:

(1)create table categories:
Create table   categories
( id  int    primary key   auto_increment,
catname   varchar(200)
);
(2)create table  food:
Create table food
(id  int primary key auto_increment,
food_name varchar(200),
catname  varchar(200)

);


Step 2:

(1)write  code for  Dropdown.php    file:
<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 = "food.php";

    var fn = document.getElementById("catname").value;

  
 var vars ="catname="+fn;

    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...";
}

function ajax_submit()
{

    // Create our XMLHttpRequest object

    var hr = new XMLHttpRequest();

    // Create some variables we need to send to our PHP file

    var url = "submit.php";

    var fn = document.getElementById("catname").value;
     var fd = document.getElementById("food_name").value;

  
 var vars ="catname="+fn+"&food_name="+fd;

    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("status1").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("status1").innerHTML = "processing...";
}
</script>
</head>
<body>
<table width="40%"border=1>
<tr><td width="50%"><center><select id=catname  onchange="ajax_post();">
<option>SELECT</option>
<?php
$con=mysql_connect("Localhost","root","");
mysql_select_db("suchi",$con);
$sql="select * from categories";
$result=mysql_query($sql);

while($row=mysql_fetch_array($result))
{
echo '<option value="'.$row['catname'].'">';
echo $row['catname'];
echo '</option>';
}

?>
</select></center></td>

 <td width="50%"><div id=status>
<select name=foodname    id=food_name>
<option>SELECT</option>
 <?php

 $con=mysql_connect("Localhost","root","");
mysql_select_db("suchi",$con);
$sql="select * from food";
$result=mysql_query($sql);

while($row=mysql_fetch_array($result))
{
echo '<option value="'.$row['food_name'].'">';
echo $row['food_name'];
echo '</option>';
}
?>
 </select></div></td>
 </tr>
 <tr><td height="30px" colspan=2><div id="status1"></div></td></tr>
 <tr><td colspan=2>
<center><input type=submit   name=submit  value=submit   onclick="ajax_submit();"></center></td></tr>

</table>
</body>
</html>

(2)write code for food.php file:
<html>
<head>
</head>
<body>
<select name=foodname    id=food_name>
<?php
 $food=$_POST['catname'];
 $con=mysql_connect("Localhost","root","");
mysql_select_db("suchi",$con);
$sql="select * from food where catname='$food'";
$result=mysql_query($sql);

while($row=mysql_fetch_array($result))
{
echo '<option value="'.$row['food_name'].'">';
echo $row['food_name'];
echo '</option>';
}
?>
</select>
</body>
</html>
(3)write code for   submit.php  file:
<?php
echo "testing for onclick ".'<Br>';
echo $catname=$_POST['catname'];
echo $foodname=$_POST['food_name'];

?>
==================================================================================================================================================================


Another  dynamic dropdown practice on  state wise city selection..

Create    table   city   :
create   table  city
(id     int,
city     varchar(200),
state    varchar(200)
);
Create   table   mystate:
create  table  mystate
(id      int,
state    varchar(200)
);
create  table  cityrecord:
create    table  cityrecord
(id      int,
state     varchar(200),
city       varchar(200),
name varchar(200),
contact varchar(200)
);


just see following output:
and follow step by step  :




(1)First   write code for     “statedropdown.php”     file  :
<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 = "city.php";

    var fn = document.getElementById("mystate").value;

 
 var vars ="mystate="+fn;

    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...";
}

function ajax_submit()
{

    // Create our XMLHttpRequest object

    var hr = new XMLHttpRequest();

    // Create some variables we need to send to our PHP file

    var url = "cityrecord.php";

    var fn = document.getElementById("mystate").value;
     var fd = document.getElementById("city").value;
 var nm = document.getElementById("name").value;
     var cn= document.getElementById("contact").value;

 
 var vars ="mystate="+fn+"&city="+fd+"&name="+nm+"&contact="+cn;

    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("status1").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("status1").innerHTML = "processing...";
}
</script>
</head>
<body>
name <input type=text id=name>
contact<input type=text id=contact>
<table width="40%"border=1>
<tr><td width="50%"><center><select id=mystate  onchange="ajax_post();">
<option>SELECT</option>



<?php
$con=mysql_connect("Localhost","root","");
mysql_select_db("rajiv",$con);
$sql="select * from mystate";
$result=mysql_query($sql);

while($row=mysql_fetch_array($result))
{
echo '<option value="'.$row['state'].'">';
echo $row['state'];
echo '</option>';
}

?>

</select></center></td>

 <td width="50%"><div id=status>
<select    id=city>
<option>SELECT</option>


 <?php

 $con=mysql_connect("Localhost","root","");
mysql_select_db("rajiv",$con);
$sql="select * from city";
$result=mysql_query($sql);

while($row=mysql_fetch_array($result))
{
echo '<option value="'.$row['city'].'">';
echo $row['city'];
echo '</option>';
}
?>
 </select></div></td>
 </tr>
 <tr><td height="30px" colspan=2><div id="status1"></div></td></tr>
 <tr><td colspan=2>



<center><input type=submit   name=submit  value=submit   onclick="ajax_submit();"></center></td></tr>

</table>
</body>
</html>

(2)write code for  city.php file:
<html>
<head>
</head>
<body>
<select name=city   id=city>
<?php
 $state=$_POST['mystate'];
 $con=mysql_connect("Localhost","root","");
mysql_select_db("rajiv",$con);
$sql="select * from city where state='$state'";
$result=mysql_query($sql);

while($row=mysql_fetch_array($result))
{
echo '<option value="'.$row['city'].'">';
echo $row['city'];
echo '</option>';
}
?>
</select>
</body>
</html>

(3)write  code for cityrecord.php file:
<?php

 $city=$_POST['city'];
 $state=$_POST['mystate'];
 $name=$_POST['name'];
 $contact=$_POST['contact'];


$con=mysql_connect("localhost","root","");
mysql_select_db("rajiv",$con);
$sql="insert into cityrecord(state,city,name,contact) values('$state','$city','$name','$contact')";
$result=mysql_query($sql)or die(mysql_error());
if($result)
{
               echo "inserted";
               }
               else
               {
                              echo "not inserted";
                              }
                             

                              ?>



==================================================================================================================================================================
how to display   dynamic   drop down menu with submenu example:

<ul class="nav navbar-nav">
                <li class="active"><a href="index.php">HOME</a></li>
                <li><a href="About-Us.php">ABOUT US</a></li>
                <li> 
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">COURSES<b class="caret"></b></a>
                    <ul class="dropdown-menu multi-level">
<?php
$con=mysql_connect("Localhost","root","");
mysql_select_db("vissicomp",$con);
$sql="select * from category";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{


echo '<li class="dropdown-submenu">';
//<a href="#c2" class="dropdown-toggle" data-toggle="dropdown">CAREER COURSES</a>';
                        ?>


<a href="<?php echo $row['link']; ?>" class="dropdown-toggle" data-toggle="dropdown"><?php echo $row['category'];  ?>
<?php

echo '</a>';
//echo  '</li>';


?>
<?php
//$catname=$_GET['category']; 
$con1=mysql_connect("Localhost","root","");
mysql_select_db("vissicomp",$con1);
$catname=$row['category'];
   $sql1="select * from course where category='$catname'";
$result1=mysql_query($sql1);
echo '<ul class="dropdown-menu">';
while($row1=mysql_fetch_array($result1))
{
echo '<li>';
?>
<!--<a href="<?php //echo $row1['link']; ?>"> <?php //echo $row1['coursename']; ?> </a>-->
<!--<a href="selectcourse1.php?coursename=<?php //echo $row1['coursename'];  ?>"><?php //echo $row1['coursename']; ?></a>-->
<a href="<?php echo $row1['coursename'];  ?>.php"><?php echo $row1['coursename']; ?></a>
<?php
//echo '<h3>';
//echo $row1['coursename'];
//echo '</h3>';
//echo '</a>';
echo  '</li>';
}
echo '</ul>';
//echo '</ul>';
echo '</li>';
}
                        ?>    
                             
                         
                         
                  
                </ul>
                </li>
            

Browsers

Powered by Blogger.

Feature Post

About Me

My photo
B.E.(COMPUTER ENGINEER) PHP Web developer & Provide Training for Web Development , Digital Marketing ,Android Mobile Apps Development

Post Slider (Homepage)

Blog Archive

Malwares

Transfer Files

Media Players

Download Manager

Window

Torrents Soft

Developer Tools

Botton Ad

Ads

Newsletter

 

© 2013 PHP TRAINING IN MUMBAI BY OM SIR . All rights resevered. Designed by OM SIR

Back To Top