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:

No comments:

Post a Comment