Monday, 25 July 2016

Ajax with PHP & MYSQL Database

Ajax   with    PHP  &  MYSQL   Database :



PHP  Ajax :

What is AJAX ?.....

AJAX stands for Asynchronous JavaScript and  XML.

AJAX is a new technique for creating better, faster, and...

more interactive web applications with the help of XML, HTML, CSS and Java Script.

Conventional web application trasmit information to and from the sever using synchronous requests.

This means you fill out a form,

hit submit,and get directed to a new page with new information from the server.

With AJAX when submit is pressed, JavaScript will make a request to the server,

interpret the results and update the current screen. In the purest sense,



the user would never know that anything was even transmitted to the server.

FIRST CREATE  TABLE    details :
create table  details
(id  int,
name   varchar(200),
city    varchar(200));



Ajax example code  for   inserting record from  form   to MYSQL  Database :


(1)first write code for  insert.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 = "insert.php";
     
    var id = document.getElementById("id").value;
     
    var nm = document.getElementById("name").value;
     
      var cy = document.getElementById("city").value;
     

     

    var vars = "id="+id+"&name="+nm+"&city="+cy;
     
    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>
<input type="text" id="id" name="id">
<input type="text" id="name" name="name">
<input type="text" id="city" name="city">
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();">
<div id="status"></div>
</body>
</html>


(2)Then    write    code   for     insert.php   :
<?php
$id=$_POST['id'];
$nm=$_POST['name'];
$cy=$_POST['city'];
$con=mysql_connect('localhost','root','' );
mysql_select_db('needa',$con);
$sql="insert into details (id,name,city) values('$id','$nm','$cy')";
mysql_query($sql);
echo "record inserted successfully";


?>

Ajax example code   to   update record   from    form   to MYSQL   Database   :
(1) write   code for    update.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 = "update.php";
     
    var id = document.getElementById("id").value;
     
    var nm = document.getElementById("name").value;
     
      var cy = document.getElementById("city").value;
     

     

    var vars = "id="+id+"&name="+nm+"&city="+cy;
     
    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>
<input type="text" id="id" name="id">
<input type="text" id="name" name="name">
<input type="text" id="city" name="city">
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();">
<div id="status"></div>
</body>
</html>
(2)write    code   for   update.php  :
<?php
$id=$_POST['id'];
$nm=$_POST['name'];
$cy=$_POST['city'];
$con=mysql_connect('localhost','root','' );
mysql_select_db('needa',$con);
$sql="update details set name ='$nm', city='$cy' where id='$id'";
mysql_query($sql);
echo "record updated successfully";

?>



Ajax example code   to   search record   from       MYSQL   Database   :
(1)write   code search.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 = "search.php";
           

           
    var nm = document.getElementById("name").value;
           

           

           

    var vars = "name="+nm;
           
    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>
<input type="text" id="name" name="name">
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();">
<div id="status"></div>
</body>
</html>


(2)write  code for search.php:
<?php
$nm=$_POST['name'];
$con=mysql_connect('localhost','root','' );
mysql_select_db('needa',$con);
$sql="select * from details where name='$nm'";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
echo $row['id'];
echo $row['name'];
echo $row['city'];

}
?>







Ajax example code   to     Delete    record   from       MYSQL   Database   :
(1)write    code   for   delete.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 = "delete.php";
           
    var id = document.getElementById("id").value;
           
    var vars = "id="+id;
           
    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>
<input type="text" id="id" name="id">
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();">
<div id="status"></div>
</body>
</html>


(2) write  code for   delete.php  :

<?php
$id=$_POST['id'];
$con=mysql_connect('localhost','root','' );
mysql_select_db('needa',$con);
$sql="delete from details where id='$id'";
mysql_query($sql);
echo "record deleted successfully";

?>

==============================================================
Ajax code using GET method :
==============================================================
(1)write code for ajax.html  file:
<html>
   <body>
     
      <script language = "javascript" type = "text/javascript">
         <!--
            //Browser Support Code
            function ajaxFunction(){
               var ajaxRequest;  // The variable that makes Ajax possible!
              
               try {
                  // Opera 8.0+, Firefox, Safari
                  ajaxRequest = new XMLHttpRequest();
               }catch (e) {
                  // Internet Explorer Browsers
                  try {
                     ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                  }catch (e) {
                     try{
                        ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                     }catch (e){
                        // Something went wrong
                        alert("Your browser broke!");
                        return false;
                     }
                  }
               }
              
               // Create a function that will receive data
               // sent from the server and will update
               // div section in the same page.
                                                                               
               ajaxRequest.onreadystatechange = function(){
                  if(ajaxRequest.readyState == 4){
                     var ajaxDisplay = document.getElementById('ajaxDiv');
                     ajaxDisplay.innerHTML = ajaxRequest.responseText;
                  }
               }
              
               // Now get the value from user and pass it to
               // server script.
                                                                               
               var age = document.getElementById('age').value;
               var wpm = document.getElementById('wpm').value;
               var name = document.getElementById('name').value;
               var queryString = "?age=" + age ;
           
               queryString +=  "&wpm=" + wpm + "&name=" + name;
               ajaxRequest.open("GET", "test.php" + queryString, true);
               ajaxRequest.send(null);
            }
         //-->
      </script>
                               
      <form name = 'myForm'>
          Age: <input type = 'text' id = 'age' /> <br />
         WPM: <input type = 'text' id = 'wpm' />
                                 NAME <input type='text'  id='name' />
                                 
         <br />
        
               
         <input type = 'button' onclick = 'ajaxFunction()' value = 'Query MySQL'/>
                                               
      </form>
     
      <div id = 'ajaxDiv'>Your result will display here</div>
   </body>
</html>

(2)write  code for   test.php  file :
<?php

echo $age=$_GET['age'];

echo $wpm=$_GET['wpm'];

echo $name=$_GET['name'];

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


(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>';


?>


Now  see below example for dynamic drop down &  Onchange  & Onclick event with Ajax:



First of all Write code for filterdownload.php :

 <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 = "displaynotes1previous.php";
    var fn = document.getElementById("coursename").value;
           
    var en = document.getElementById("semseter").value;
           
           
           
           
           
           
           

    var vars = "coursename="+fn+"&semseter="+en;
           
    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_disp(){
    // Create our XMLHttpRequest object
    var hr = new XMLHttpRequest();
    // Create some variables we need to send to our PHP file
    var url = "displaynotes1.php";
    var fn = document.getElementById("coursename").value;
           
    var en = document.getElementById("semseter").value;
           
            var pn = document.getElementById("subject").value;
           
           
           
           
           
           

    var vars = "coursename="+fn+"&semseter="+en+"&subject="+pn;
           
    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>
                                                             <span style="color:#000;">Select Course Name : -</span>
<select  name=coursename  id="coursename"    >
<?php




$con = mysql_connect('localhost', 'root', '');
mysql_select_db("itexam", $con);

$sql="select * from subject group by coursename ";

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



while ($row=mysql_fetch_array($result))

{

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


echo $row['coursename'];


echo '<option>';




}

?>
</select>

<span style="color:#000;"> Select Semester : -</span>
<select  name=semseter  id="semseter"   onChange="ajax_post();">

<?php



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

mysql_select_db("itexam",$con);

$sql="select * from subject  group by semseter  ";

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



while ($row=mysql_fetch_array($result))

{

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


echo $row['semseter'];


echo '<option>';




}

?>
</select>

<!------>

<br /><br />

<div id="status">

</div>



<br /><br />

<input align="middle" name="myBtn" type="submit" value="Submit Data"    onclick="ajax_disp();">








<br />





<?php

ob_flush();

?>
<br /><br />
</div>


</center>

(2)now write code for displaynotes1previous.php:


<html>
<head>


</head>
<body>
<?php
$coursename=$_POST['coursename'];
//echo $coursename;
$semseter=$_POST['semseter'];
//echo $semseter;
?>

Subject  <select  name="subject"   id="subject">
<?php
$con = mysql_connect('localhost', 'root', '');
mysql_select_db("itexam", $con);
$sql="select  subject  from subject where coursename='$coursename' AND  semseter='$semseter'";
$result=mysql_query($sql) or die(mysql_error());
while ($row=mysql_fetch_array($result))
{
echo '<option  value="'.$row['subject'].'">';
echo $row['subject'];
echo '<option>';
}
?>
</select>


</td></tr>
<tr>
<td>

</tr>

</body>
</html>

(3)now write code for displaynotes1.php:

<?php


ob_start();

?>

<?php
$coursename=$_POST['coursename'];
//echo $coursename;
$semseter=$_POST['semseter'];
//echo $semseter;
?>

Subject  <select  name="subject"   id="subject">
<?php
$con=mysql_connect("localhost","root","");

mysql_select_db("itexam",$con);
$sql="select  subject  from subject where coursename='$coursename' AND  semseter='$semseter'";
$result=mysql_query($sql) or die(mysql_error());
while ($row=mysql_fetch_array($result))
{
echo '<option  value="'.$row['subject'].'">';
echo $row['subject'];
echo '<option>';
}
?>
</select>


<?php


$coursename=$_POST['coursename'];


$semester=$_POST['semseter'];


$subject=$_POST['subject'];


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","");

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

mysql_select_db("itexam",$con);

//mysql_select_db("itexam",$con);


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


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

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

echo '<tr><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>';



while($row=mysql_fetch_array($result))
{
echo ' <tr><td>"'.$row['subject'].'" </td><td>&nbsp;</td><td>"'.$row['unit'].'" </td><td>&nbsp;</td>
<td>
<button ><a href=../proudct_images/'.$row['file'].'>
Download file</a></button> </td></tr>';
}
echo '</table>';
?>

<?php

ob_flush();

?>
================================================================================================================================================
ONCHANGE    DROPDWON   EXAMPLE  USING JQUERY AND AJAX WITH PHP & MYSQL:

STEP 1: create table   categorie :


create   table   categorie
(
category_id   int  primary  key auto_increment ,
type                      varchar(200),
categoryname     varchar(200)
);


STEP   2   :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Sections Demo</title>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".country").change(function()
{
var data=$(this).val();
var dataString = 'data='+ data;

$.ajax
({
type: "POST",
url: "ajax_city.php",
data: dataString,
cache: false,
success: function(html)
{
$(".city").html(html);
}
});

});
});
</script>
<style>
label
{
font-weight:bold;
padding:10px;
}
</style>
</head>
<body>
<form action=test.php    method=post  enctype="multipart/form-data">
<div style="margin:80px">
<label>Country :</label>
<select name="country" class="country">
<option selected="selected">--Select Country--</option>

<?php
include('db.php');
echo $sql1="select * from categorie group by type";
$result1=mysql_query($sql1) or die(mysql_error());
while($row1=mysql_fetch_array($result1))
{
               
                echo '<option value="'.$row1['type'].'">';
                echo  $row1['type'];
                echo '</option>';
               
}
?>
</select>
<textarea  type=text name=hello  > </textarea>
<script>
                // Replace the <textarea id="editor1"> with a CKEditor
                // instance, using default configuration.
                CKEDITOR.replace( 'hello' );
            </script>
<input type=file  name=image>
<input type=submit name=submit value=submit>
</form> <br/><br/>
<label>City :</label>
<div name="city" class="city">
</div>
</div>
</body>
</html>

OUTPUT:


STEP 3: now write code for ajax_city.php file which will execute on  onchange of dropdown:

<select name="categoryname" id="categoryname">';
<?php
include("db.php");
$type=$_POST['data'];
echo $sql2="select * from categorie where type='$type'";
$result2=mysql_query($sql2) or die(mysql_error());
while($row2=mysql_fetch_array($result2))
{
                echo '<option value="'.$row2['categoryname'].'">';
                echo  $row2['categoryname'];
                echo '</option>';
}
?>
</select>

Step 4: now write code for   test.php file which will execute on   click on submit button:

<?php

echo "country =". $test=$_POST['country'];
echo '<br>';

echo "categoryname=". $categoryname=$_POST['categoryname'];
echo '<br>';
echo "hello=".$hello=$_POST['hello'];
echo '<br>';
echo "image =". $image=$_FILES['image']['name'];
echo '<br>';
move_uploaded_file($_FILES['image']['tmp_name'],"upload/".$_FILES['image']['name']);

?>




================================================================================================================================================
                               
========================================================================Ajax  with Jquery & php & mysql
========================================================================
HTML File – refreshform.html
·         Consists of form with id = “form”.

<!DOCTYPE html>
<html>
<head>
<title>Submit Form Without Refreshing Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link href="css/refreshform.css" rel="stylesheet">
<script src="js/refreshform.js"></script>
</head>
<body>
<div id="mainform">
<h2>Submit Form Without Refreshing Page</h2>
<!-- Required Div Starts Here -->
<form id="form" name="form">
<h3>Fill Your Information!</h3>
<label>Name:</label>
<input id="name" placeholder="Your Name" type="text">
<label>Email:</label>
<input id="email" placeholder="Your Email" type="text">
<label>Contact No.</label>
<input id="contact" placeholder="Your Mobile No." type="text">
<label>Gender:</label>
<input name="gender" type="radio" value="male">Male
<input name="gender" type="radio" value="female">Female
<label>Message:</label>
<textarea id="msg" placeholder="Your message..">
</textarea>
<input id="submit" type="button" value="Submit">
</form>
</div>
</body>
</html>
jQuery File – refreshform.js
·         Sends request to php script with form details. Return notification on successful data submission.

$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var contact = $("#contact").val();
var gender = $("input[type=radio]:checked").val();
var msg = $("#msg").val();
if (name == '' || email == '' || contact == '' || gender == '' || msg == '') {
alert("Insertion Failed Some Fields are Blank....!!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("refreshform.php", {
name1: name,
email1: email,
contact1: contact,
gender1: gender,
msg1: msg
}, function(data) {
alert(data);
$('#form')[0].reset(); // To reset form fields
});
}
});
});

My-SQL Code
·         My-SQL command for creation of database ‘mydba’ and table ‘form_elements’.

CREATE DATABASE mydba;
CREATE TABLE form_element (
id int(25) NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
email varchar(255) NOT NULL,
contact int(25) NOT NULL,
gender varchar(255) NOT NULL,
message varchar(255) NOT NULL,
PRIMARY KEY (id)
)
PHP File – refreshform.php
·         Insert form information into database.

<?php
// Establishing connection with server by passing "server_name", "user_id", "password".
$connection = mysql_connect("localhost", "root", "");
// Selecting Database by passing "database_name" and above connection variable.
$db = mysql_select_db("mydba", $connection);
$name2=$_POST['name1']; // Fetching Values from URL
$email2=$_POST['email1'];
$contact2=$_POST['contact1'];
$gender2=$_POST['gender1'];
$msg2=$_POST['msg1'];
$query = mysql_query("insert into form_element(name, email, contact, gender, message) values ('$name2','$email2','$contact2','$gender2','$msg2')"); //Insert query
if($query){
echo "Data Submitted succesfully";
}
mysql_close($connection); // Connection Closed.
?>
Css File – refreshform.css
·         Includes basic styling of form.

@import "http://fonts.googleapis.com/css?family=Fauna+One|Muli";
#form{
background-color:#556b2f;
color:#D5FFFA;
border-radius:5px;
border:3px solid #d3cd3d;
padding:4px 30px;
font-weight:700;
width:350px;
font-size:12px;
float:left;
height:auto;
margin-left:35px
}
label{
font-size:15px
}
h3{
text-align:center;
font-size:21px
}
div#mainform{
width:960px;
margin:50px auto;
font-family:'Fauna One',serif
}
input[type=text]{
width:100%;
height:40px;
margin-top:10px;
border:none;
border-radius:3px;
padding:5px
}
textarea{
width:100%;
height:60px;
margin-top:10px;
border:none;
border-radius:3px;
padding:5px;
resize:none
}
input[type=radio]{
margin:10px 5px 5px
}
input[type=button]{
width:100%;
height:40px;
margin:35px 0 30px;
background-color:#f4a460;
border:1px solid #fff;
border-radius:3px;
font-family:'Fauna One',serif;
font-weight:700;
font-size:18px
}



=====================================================================
same example in different way:
=====================================================================
HTML File: ajaxsubmit.html
Here, we create our form

<!DOCTYPE html>
<html>
<head>
<title>Submit Form Using AJAX and jQuery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link href="style.css" rel="stylesheet">
<script src="script.js"></script>
</head>
<body>
<div id="mainform">
<h2>Submit Form Using AJAX and jQuery</h2> <!-- Required div Starts Here -->
<div id="form">
<h3>Fill Your Information !</h3>
<div>
<label>Name :</label>
<input id="name" type="text">
<label>Email :</label>
<input id="email" type="text">
<label>Password :</label>
<input id="password" type="password">
<label>Contact No :</label>
<input id="contact" type="text">
<input id="submit" type="button" value="Submit">
</div>
</div>
</div>
</body>
</html>

PHP File: ajaxsubmit.php

<?php
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("mydba", $connection); // Selecting Database
//Fetching Values from URL
$name2=$_POST['name1'];
$email2=$_POST['email1'];
$password2=$_POST['password1'];
$contact2=$_POST['contact1'];
//Insert query
$query = mysql_query("insert into form_element(name, email, password, contact) values ('$name2', '$email2', '$password2','$contact2')");
echo "Form Submitted Succesfully";
mysql_close($connection); // Connection Closed
?>
 jQuery File: script.js
jQuery file consist of ajax functionality.

$(document).ready(function(){
$("#submit").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var contact = $("#contact").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name1='+ name + '&email1='+ email + '&password1='+ password + '&contact1='+ contact;
if(name==''||email==''||password==''||contact=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});

MY-SQL Code Segment:
Here is the My-SQL code for creating database and table.

CREATE DATABASE mydba;
CREATE TABLE form_element(
id int(10) NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
email varchar(255) NOT NULL,
password varchar(255) NOT NULL,
contact varchar(255) NOT NULL,
PRIMARY KEY (id)
)
 CSS File: style.css

@import "http://fonts.googleapis.com/css?family=Fauna+One|Muli";
#form {
background-color:#fff;
color:#123456;
box-shadow:0 1px 1px 1px #123456;
font-weight:400;
width:350px;
margin:50px 250px 0 35px;
float:left;
height:500px
}
#form div {
padding:10px 0 0 30px
}
h3 {
margin-top:0;
color:#fff;
background-color:#3C599B;
text-align:center;
width:100%;
height:50px;
padding-top:30px
}
#mainform {
width:960px;
margin:50px auto;
padding-top:20px;
font-family:'Fauna One',serif
}
input {
width:90%;
height:30px;
margin-top:10px;
border-radius:3px;
padding:2px;
box-shadow:0 1px 1px 0 #123456
}
input[type=button] {
background-color:#3C599B;
border:1px solid #fff;
font-family:'Fauna One',serif;
font-weight:700;
font-size:18px;
color:#fff
}ouput:

Simple project to understand about register a user account , user login & admin login & admin managing user account

Simple project    to understand   about register a  user   account , user login  & admin login & admin managing user account:

Step 1:

Create  two table first userrecord for user and  adminlogin  for  admin:

Create table userrecord
(id  int primary key auto_increment,
namevarchar(200),
contactvarchar(200),
emailvarchar(200),
password  varchar(200)
);

Create table  adminlogin
(idint primary key auto_increment,
usernamevarchar(200),
passwordvarchar(200)
);

Step 2:
(a)write code for register.html:

<form action="register.php" method="post">
name<input type="text" name="name">
contact<input type="text" name="contact">
email<input type="text" name="email">
password<input type="password" name="password">
<input type="submit" name="submit" value="submit">
</form>



(b)write code for  register.php  :
<?php
$name=$_POST['name'];
$email=$_POST['email'];
$contact=$_POST['contact'];
$password=$_POST['password'];
$con=mysql_connect("localhost","root","");
mysql_select_db("simpleproject",$con);
$sql="select * from userrecord where email='$email'";
                $result=mysql_query($sql);
                $num=mysql_num_rows($result);
                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')";
                                mysql_query($sql1);
                                echo "<font color=red>successfully  registered </font>";
                }
?>


Step 3:

(a)write code for  userlogin.html:

<form action="userlogin.php" method="post">
email<input type="text" name="email">
password<input type="password" name="password">
<input type="submit" name="submit" value="submit">
</form>

(b)write code for    userlogin.php :

<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("simpleproject",$con);
$email=$_POST['email'];
$password=$_POST['password'];
$sql="select email,password from userrecord where email='$email' and password='$password'";
$result=mysql_query($sql);
$num=mysql_num_rows($result);
if($num>0)
{
session_start();
$_SESSION['email']=$email;
header('location:userwelcome.php');
}
else
{
echo "invalid userlogin";
}
?>

( c) now write code for  userwelcome.php  :


<?php
session_start();
if(!isset($_SESSION['email']))
{
header("location:usererror.php");
}
echo "<h1>welcome</h1>";
echo '<a href="userlogout.php">userlogout</a>'.'<br>';

$email=$_SESSION['email'];

echo "welocme =".$email.'<br>';

//display code  for user record who made current login//

$con=mysql_connect("Localhost","root","");
mysql_select_db("simpleproject",$con);

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

$result=mysql_query($sql);
while($row=mysql_fetch_array($result))

 {
 echo "<h1>user details </h1>";
  echo "ID=".$row['id'];

  echo '<br>';
   echo "NAME=".$row['name'];

   echo '<br>';
    echo "CONTACT=".$row['contact'];
 
    echo '<br>';
     echo "PASSWORD=".$row['password'];



 }


 echo '<a href="change_password.php">change password</a>'.'<br>';
 echo '<a href="change_profile.php">change profile</a>'.'<br>';

?>


output:




(d)now write code for  userlogout.php:

<?php

session_start();
session_destroy();
header('Location:userlogin.html');
?>
(e)write code for usererror.php:

<?php

echo "make login first";

echo '<a href="userlogin.html">login</a>';

?>

(f) Now write code for  change_password.php   file:
<?php
session_start();
if(!isset($_SESSION['email']))
{
header("location:usererror.php");
}
?>
<form action="final_change_password.php" method="post">
Enter New Password<input type="password" name="password">
<input type="submit" name="submit" value="change password">
</form>

(g)Now  write code  for  final_change_password.php  file:


<?php
session_start();
if(!isset($_SESSION['email']))
{
header("location:usererror.php");
}
?>
<?php
$email=$_SESSION['email'];

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



$password=$_POST["password"];


$sql="update userrecord set password='$password' where email='$email'";

$result=mysql_query($sql) or die (mysql_error());
if($result)
{
echo "record update successfully";
}
else
{
echo "record not updated";
}

?>


(h)write code for   change_profile.php    file:

<?php
session_start();
if(!isset($_SESSION['email']))
{
header("location:usererror.php");
}
?>


<?php

$email=$_SESSION['email'];

$con=mysql_connect("Localhost","root","");
mysql_select_db("simpleproject",$con);

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

$result=mysql_query($sql);
while($row=mysql_fetch_array($result))

 {

echo '
<form action="final_change_profile.php" method="post">
name<input type="name"  name=name   value="'.$row['name'].'">
contact<input type="name" name=contact  value="'.$row['contact'].'">
<input type="submit" name="submit" value="update-profile">
</form>';

}


(i)write code for  final_change_profile.php   file:


<?php
session_start();
if(!isset($_SESSION['email']))
{
header("location:usererror.php");
}
?>




<?php
$email=$_SESSION['email'];

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



$name=$_POST["name"];
$contact=$_POST["contact"];


$sql="update userrecord set name='$name',contact='$contact' where email='$email'";

$result=mysql_query($sql) or die (mysql_error());
if($result)
{
echo "record update successfully";
}
else
{
echo "record not updated";
}

?>





Now start coding part for admin :


Step  1:

(a)write code for adminlogin.html:

<form action="adminlogin.php" method="post">
username<input type="text" name="username">
password<input type="password" name="password">
<input type="submit" name="submit" value="submit">
</form>


(b)now write code for adminlogin.php:

<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("abhi",$con);
$username=$_POST['username'];
$password=$_POST['password'];
$sql="select username,password from adminlogin where username='$username' and password='$password'";
$result=mysql_query($sql);
$num=mysql_num_rows($result);
if($num>0)
{
session_start();
$_SESSION['username']=$username;
header('location:display.php');
}
else
{
echo "invalid login";
}
?>

(c )now write code for display.php :

<?php
session_start();
if(!isset($_SESSION['username']))
{
                header('location:adminerror.php');
               
}
?>

<a href="adminlogout.php">Logout</a>
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("abhi",$con);
$sql="select * from userrecord";
$result=mysql_query($sql);
echo '<table border=1><tr><td>id</td><td>name</td><td>email</td><td>password</td><td>&nbsp;</td><td>&nbsp;</td></td>';
while($row=mysql_fetch_array($result))
{
echo '<tr>';
echo '<td>';
echo $row['id'];
echo '</td>';
echo '<td>';
echo $row['name'];
echo '</td>';
echo '<td>';
echo $row['email'];
echo '</td>';
echo '<td>';
echo $row["password"];

echo '</td>';
echo '<td><form action="update.php" method="post">
<input type="hidden" name="hidden" value="'.$row['id'].'">
<input type="submit" name="button" value="update">
</form></td>';

echo '<td><form action="delete.php" method="post">
<input type="hidden" name="hidden" value="'.$row['id'].'">
<input type="submit" name="button" value="delete">
</form></td>';

echo '</tr>';

}
echo '</table>';

?>

(d)now write code for  update.php   file:           
           
<?php
session_start();
if(!isset($_SESSION['username']))
{
   header('location:adminerror.php');
                                                                                                       
}
?>

<?php
$hidden=$_POST["hidden"];
$con=mysql_connect("localhost","root","");

mysql_select_db("abhi",$con);

$sql="select * from userrecord where id='$hidden'";

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

echo 'id<input type="text" name="id" value="'.$row['id'].'">';

echo 'name<input type="text" name="name" value="'.$row['name'].'">';
echo 'contact<input type="text" name="contact" value="'.$row['contact'].'">';
echo '
email<input type="text" name="email" value="'.$row['email'].'">';
echo '
password<input type="password" name="password" value="'.$row['password'].'"> ';
echo '
<input type="hidden" name="hidden"  value="'.$row['id'].'">';
echo '
<input type="submit" value="update" name="update">';

echo '</form>';

}

?>

(e)now write code  for  finalupdate.php :

<?php
session_start();
if(!isset($_SESSION['username']))
{
                                                                     header('location:adminerror.php');
                                                                                                       
}
?>
<?php
$hidden=$_POST["hidden"];
$name=$_POST["name"];
$contact=$_POST['contact'];
$email=$_POST["email"];
$password=$_POST["password"];
$con=mysql_connect("localhost","root","");
mysql_select_db("abhi",$con);
$sql="update userrecord set name='$name',contact='$contact',email='$email',password='$password'where id='$hidden'";
mysql_query($sql)or die(mysql_error());

echo "userrecord update successfully";
?>

(f)now write code for  delete.php:

<?php
$hidden=$_POST["hidden"];
$con=mysql_connect("localhost","root","");
mysql_select_db("abhi",$con);
$sql="delete from userrecord where id='$hidden'";
mysql_query($sql);
echo "userrecord deleted successfully";
?>

(g)write code for adminerror.php:

<?php

echo "make login first";

echo '<a href="adminlogin.html">login</a>';

?>

(h)now write code for  adminlogout.php:

<?php

session_start();
session_destroy();
header('Location:adminlogin.html');
?>

Wednesday, 4 November 2015

CHAT-APPLICATIONS (using socket.io, express and Nodejs )

(1)First of All install Nodejs  on your Windows system:

https://nodejs.org/en/download/

(2)After  That create a folder into your D: drive and name it "chat code" & now you need to  Open your command Prompt:

& perform following  command in command prompt

step 1:

D:\>cd chat code

step 2: to install socket.io

D:\chat code>npm   install  socket.io


step 3:to install  express


D:\chat code>npm   install   express

step 4: Prepare a file name it  as   "package.json " write given code below:

{
  "name": "socket-chat-example",
  "version": "0.0.1",
  "description": "my first socket.io app",
  "dependencies": {
    "express": "4.10.2",
    "socket.io": "1.2.0"
  }
}


& save it.






(3)Now write code for    "om.js"    file code which act as server program at server side keep this file  inside "chat code" folder :

var express = require('express')
  , app = express()
  , http = require('http')
  , server = http.createServer(app)
  , io = require('socket.io').listen(server);

server.listen(8080);

// routing
app.get('/', function (req, res) {
  res.sendfile(__dirname + '/om.html');
});

// usernames which are currently connected to the chat
var usernames = {};

io.sockets.on('connection', function (socket) {

  // when the client emits 'sendchat', this listens and executes
  socket.on('sendchat', function (data) {
    // we tell the client to execute 'updatechat' with 2 parameters
    io.sockets.emit('updatechat', socket.username, data);
  });

  // when the client emits 'adduser', this listens and executes
  socket.on('adduser', function(username){
    // we store the username in the socket session for this client
    socket.username = username;
    // add the client's username to the global list
    usernames[username] = username;
    // echo to client they've connected
    socket.emit('updatechat', 'SERVER', 'you have connected');
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
    // update the list of users in chat, client-side
    io.sockets.emit('updateusers', usernames);
  });

  // when the user disconnects.. perform this
  socket.on('disconnect', function(){
    // remove the username from global usernames list
    delete usernames[socket.username];
    // update list of users in chat, client-side
    io.sockets.emit('updateusers', usernames);
    // echo globally that this client has left
    socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
  });
});

(4)Now write code for file "om.html" client side   "userinterface"  keep this file inside "chat code " folder :

<style>
.button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
</style>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>

    //var socket = io.connect('http://Localhost:8080');

   //var socket = io.connect('http://vissicomp.evennode.com:8080');
   var socket=io.connect();
   //var socket = io.connect('http://192.168.1.4:8080');
 
  // on connection to server, ask for user's name with an anonymous callback

  socket.on('connect', function()
  {
    // call the server-side function 'adduser' and send one parameter (value of prompt)
    socket.emit('adduser', prompt("What's your name?"));

  });
  // listener, whenever the server emits 'updatechat', this updates the chat body
  socket.on('updatechat', function (username, data) {
    $('#conversation').append('<b>'+username + ':</b> ' + data + '<br>');
  });
  // listener, whenever the server emits 'updateusers', this updates the username list
  socket.on('updateusers', function(data) {
    $('#users').empty();
    $.each(data, function(key, value) {
      $('#users').append('<div>' + key + '</div>');
    });
  });
  // on load of page
  $(function(){
    // when the client clicks SEND
    $('#datasend').click( function() {
      var message = $('#data').val();
      $('#data').val('');
      // tell server to execute 'sendchat' and send along one parameter
      socket.emit('sendchat', message);
    });
    // when the client hits ENTER on their keyboard
    $('#data').keypress(function(e) {
      if(e.which == 13) {
        $(this).blur();
        $('#datasend').focus().click();
      }
    });
  });
</script>
<div style="float:left;width:100px;border-right:1px solid black;height:300px;padding:10px;overflow:scroll-y;">
  <b>USERS</b>
  <div id="users"></div>
</div>
<div style="float:left;width:300px;height:250px;overflow:scroll-y;padding:10px;">
  <div id="conversation"></div>
  <input id="data" style="width:200px;" />
  <input type="button" id="datasend" value="send" />
  </div>


(5)Now  run your  "om.js"  server file first:


D:\chat code>node  om.js

(6)Then  Run   client side file open any browser and type on address bar "Localhost:8080 :

"Localhost:8080"