Wednesday, 26 October 2016

Ajax Add & Delete MySQL records using jQuery & PHP

 Demo - Download




1st create a MySQL table called add_delete_record.

CREATE TABLE IF NOT EXISTS `add_delete_record` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `content` text NOT NULL,
  PRIMARY KEY (`id`)
) AUT


 config.php

<?php $username = "root";   $password = "" $hostname = "localhost";  
$databasename = 'mysql_table';   
$mysqli = new mysqli($hostname, $username, $password, $databasename); ?>
 

 Index.php

 <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Add/Delete a Record with jQuery Fade In/Fade Out</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {

    //##### send add record Ajax request to response.php #########
    $("#FormSubmit").click(function (e) {
            e.preventDefault();
            if($("#contentText").val()==='')
            {
                alert("Please enter some text!");
                return false;
            }
          
            $("#FormSubmit").hide(); //hide submit button
            $("#LoadingImage").show(); //show loading image
           
             var myData = 'content_txt='+ $("#contentText").val(); //build a post data structure
            jQuery.ajax({
            type: "POST", // HTTP method POST or GET
            url: "response.php", //Where to make Ajax calls
            dataType:"text", // Data type, HTML, json etc.
            data:myData, //Form variables
            success:function(response){
                $("#responds").append(response);
                $("#contentText").val(''); //empty text field on successful
                $("#FormSubmit").show(); //show submit button
                $("#LoadingImage").hide(); //hide loading image

            },
            error:function (xhr, ajaxOptions, thrownError){
                $("#FormSubmit").show(); //show submit button
                $("#LoadingImage").hide(); //hide loading image
                alert(thrownError);
            }
            });
    });

    //##### Send delete Ajax request to response.php #########
    $("body").on("click", "#responds .del_button", function(e) {
         e.preventDefault();
         var clickedID = this.id.split('-'); //Split ID string (Split works as PHP explode)
         var DbNumberID = clickedID[1]; //and get number from array
         var myData = 'recordToDelete='+ DbNumberID; //build a post data structure
       
        $('#item_'+DbNumberID).addClass( "sel" ); //change background of this element by adding class
        $(this).hide(); //hide currently clicked delete button
       
            jQuery.ajax({
            type: "POST", // HTTP method POST or GET
            url: "response.php", //Where to make Ajax calls
            dataType:"text", // Data type, HTML, json etc.
            data:myData, //Form variables
            success:function(response){
                //on success, hide  element user wants to delete.
                $('#item_'+DbNumberID).fadeOut();
            },
            error:function (xhr, ajaxOptions, thrownError){
                //On error, we alert user
                alert(thrownError);
            }
            });
    });

});
</script>
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="content_wrapper">
<ul id="responds">
<?php
//include db configuration file
include_once("config.php");

//MySQL query
$results = $mysqli->query("SELECT id,content FROM add_delete_record");
//get all records from add_delete_record table
while($row = $results->fetch_assoc())
{
  echo '<li id="item_'.$row["id"].'">';
  echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$row["id"].'">';
  echo '<img src="images/icon_del.gif" border="0" />';
  echo '</a></div>';
  echo $row["content"].'</li>';
}

//close db connection
$mysqli->close();
?>
</ul>
    <div class="form_style">
    <textarea name="content_txt" id="contentText" cols="45" rows="5" placeholder="Enter some text"></textarea>
    <button id="FormSubmit">Add record</button>
    <img src="images/loading.gif" id="LoadingImage" style="display:none" />
    </div>
</div>

</body>
</html>




response.php

 <?php
//include db configuration file
include_once("config.php");

if(isset($_POST["content_txt"]) && strlen($_POST["content_txt"])>0)
{    //check $_POST["content_txt"] is not empty

    //sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH Strip tags, encode special characters.
    $contentToSave = filter_var($_POST["content_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
  
    // Insert sanitize string in record
    $insert_row = $mysqli->query("INSERT INTO add_delete_record(content) VALUES('".$contentToSave."')");
  
    if($insert_row)
    {
         //Record was successfully inserted, respond result back to index page
          $my_id = $mysqli->insert_id; //Get ID of last inserted row from MySQL
          echo '<li id="item_'.$my_id.'">';
          echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$my_id.'">';
          echo '<img src="images/icon_del.gif" border="0" />';
          echo '</a></div>';
          echo $contentToSave.'</li>';
          $mysqli->close(); //close db connection

    }else{
      
        //header('HTTP/1.1 500 '.mysql_error()); //display sql errors.. must not output sql errors in live mode.
        header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
        exit();
    }

}
elseif(isset($_POST["recordToDelete"]) && strlen($_POST["recordToDelete"])>0 && is_numeric($_POST["recordToDelete"]))
{    //do we have a delete request? $_POST["recordToDelete"]

    //sanitize post value, PHP filter FILTER_SANITIZE_NUMBER_INT removes all characters except digits, plus and minus sign.
    $idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT);
  
    //try deleting record using the record ID we received from POST
    $delete_row = $mysqli->query("DELETE FROM add_delete_record WHERE id=".$idToDelete);
  
    if(!$delete_row)
    {  
        //If mysql delete query was unsuccessful, output error
        header('HTTP/1.1 500 Could not delete record!');
        exit();
    }
    $mysqli->close(); //close db connection
}
else
{
    //Output error
    header('HTTP/1.1 500 Error occurred, Could not process request!');
    exit();
}
?>

 Demo - Download

Tuesday, 13 September 2016

image upload using ajax php mysql

Demo - download

liberoram - image upload

Index.php

<html>
<head>
<title>Libero Ram | PHP AJAX Image Upload</title>
<link href="styles.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
    $("#uploadForm").on('submit',(function(e) {
        e.preventDefault();
        $.ajax({
            url: "upload.php",
            type: "POST",
            data:  new FormData(this),
            contentType: false,
            cache: false,
            processData:false,
            success: function(data)
            {
            $("#targetLayer").html(data);
            },
              error: function()
            {
            }            
       });
    }));
});

</script>
</head>
<body>
<div class="bgColor">
 <form id="uploadForm"  method="post">
<div id="targetLayer">No Image</div>
<div id="uploadFormLayer" >
<label>Upload Image File:</label><br/>
<input name="userImage" type="file" class="inputFile" />
<input type="submit" value="Submit" class="btnSubmit" />
</form>
</div>
</div>
</body>
</html>


Upload.php

<?php
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
$sourcePath = $_FILES['userImage']['tmp_name'];
$targetPath = "images/".$_FILES['userImage']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
?>
<img src="<?php echo $targetPath; ?>" width="100px" height="100px" />
<?php
}
}
}
?>


Style.css

body {
font-family: Arial;
font-size: 14px;
}
.bgColor {
width: 440px;
height:100px;
background-color: #F9D735;
}
.bgColor label{
font-weight: bold;
color: #A0A0A0;
}
#targetLayer{
float:left;
text-align:center;
line-height:100px;
font-weight: bold;
color: #C0C0C0;
background-color: #F0E8E0;
overflow:hidden;
}
#targetLayer img{
        border: 0 none;
    height: auto;
    max-width: 100%;
    vertical-align: middle;
}
#uploadFormLayer{
float:right;
padding: 10px;
}
.btnSubmit {
background-color: #3FA849;
padding:4px;
border: #3FA849 1px solid;
color: #FFFFFF;
}
.inputFile {
padding: 3px;
background-color: #FFFFFF;
}

Demo - download


Thursday, 1 September 2016

Table Sorting with jQuery Grid using PHP and MySQL

 

Click here to Download

Demo



Demo

Index.php

<div class="example ex-1">
<table>
<thead>
<tr>
<th>Name</th>
<th>Post</th>
<th>Date of Birth</th>
<th class="number">Age</th>
<th class="no-sort">Photo</th>
</tr>
</thead>
<tbody>
<tr>
<td>Libero Ram</td>
<td>Software Developer</td>
<td data-sort-value="2">Aug 15, 1991</td>
<td>26</td>
<td><img src="http://img.scoop.it/VPAC30TM-Tk_tmRBHKqlLTl72eJkfbmt4t8yenImKBVvK0kTmF0xjctABnaLJIm9" width="50"></td>
</tr>
<tr>
<td>Ram Kumar</td>
<td>Designer</td>
<td data-sort-value="4">may 01, 1992</td>
<td>28</td>
<th><img src="https://s-media-cache-ak0.pinimg.com/564x/1f/4b/ef/1f4bef480d10f159c1a8f317a432da0b.jpg" width="50"></td>
</tr>
<tr>
<td>Libero</td>
<td>Php Developer</td>
<td data-sort-value="1">June 18, 1942</td>
<td>24</td>
<td><img src="http://d13pix9kaak6wt.cloudfront.net/background/users/l/i/b/liberoram_1409038556_33.jpg" width="50"></td>
</tr>
<tr>
<td>Ram</td>
<td>Testing</td>
<td data-sort-value="3">July 26, 1974</td>
<td>22</td>
<td><img src="https://liberoram.files.wordpress.com/2014/12/liberoram.png" width="50"></td>
</tr>
</tbody>
</table></div>
 
</div>

Java Script

<script   src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="jquery.tablesort.min.js"></ script>
<script type="text/javascript">

$(function() {
$('table').tablesort().data('tablesort');

$('thead th.number').data('sortBy', function(th, td, sorter) {
return parseInt(td.text(), 10);
});

});
</script>

Style.css

<style type="text/css">
body {
font: normal 14px/21px Arial, serif;
}
.example {
float: left;
width: 40%;
margin: 5%;
}
table {
font-size: 1em;
border-collapse: collapse;
margin: 0 auto;
}
table, th, td {
border: 1px solid #999;
padding: 8px 16px;
text-align: left;
}

th {
background: #f4f4f4;
cursor: pointer;
}

th:hover,
th.sorted {
background: #d4d4d4;
}

th.no-sort,
th.no-sort:hover {
background: #f4f4f4;
cursor: not-allowed;
}

th.sorted.ascending:after {
content: "  \2191";
}

th.sorted.descending:after {
content: " \2193";
}

.disabled {
opacity: 0.5;
}
</style>

Click here to Download

Table Sorting with jQuery Grid using PHP and MySQL

 

Click here to Download

Demo

Index.php

<div class="example ex-1">
<table>
<thead>
<tr>
<th>Name</th>
<th>Post</th>
<th>Date of Birth</th>
<th class="number">Age</th>
<th class="no-sort">Photo</th>
</tr>
</thead>
<tbody>
<tr>
<td>Libero Ram</td>
<td>Software Developer</td>
<td data-sort-value="2">Aug 15, 1991</td>
<td>26</td>
<td><img src="http://img.scoop.it/VPAC30TM-Tk_tmRBHKqlLTl72eJkfbmt4t8yenImKBVvK0kTmF0xjctABnaLJIm9" width="50"></td>
</tr>
<tr>
<td>Ram Kumar</td>
<td>Designer</td>
<td data-sort-value="4">may 01, 1992</td>
<td>28</td>
<th><img src="https://s-media-cache-ak0.pinimg.com/564x/1f/4b/ef/1f4bef480d10f159c1a8f317a432da0b.jpg" width="50"></td>
</tr>
<tr>
<td>Libero</td>
<td>Php Developer</td>
<td data-sort-value="1">June 18, 1942</td>
<td>24</td>
<td><img src="http://d13pix9kaak6wt.cloudfront.net/background/users/l/i/b/liberoram_1409038556_33.jpg" width="50"></td>
</tr>
<tr>
<td>Ram</td>
<td>Testing</td>
<td data-sort-value="3">July 26, 1974</td>
<td>22</td>
<td><img src="https://liberoram.files.wordpress.com/2014/12/liberoram.png" width="50"></td>
</tr>
</tbody>
</table></div>
 
</div>

Java Script

<script   src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="jquery.tablesort.min.js"></ script>
<script type="text/javascript">

$(function() {
$('table').tablesort().data('tablesort');

$('thead th.number').data('sortBy', function(th, td, sorter) {
return parseInt(td.text(), 10);
});

});
</script>

Style.css

<style type="text/css">
body {
font: normal 14px/21px Arial, serif;
}
.example {
float: left;
width: 40%;
margin: 5%;
}
table {
font-size: 1em;
border-collapse: collapse;
margin: 0 auto;
}
table, th, td {
border: 1px solid #999;
padding: 8px 16px;
text-align: left;
}

th {
background: #f4f4f4;
cursor: pointer;
}

th:hover,
th.sorted {
background: #d4d4d4;
}

th.no-sort,
th.no-sort:hover {
background: #f4f4f4;
cursor: not-allowed;
}

th.sorted.ascending:after {
content: "  \2191";
}

th.sorted.descending:after {
content: " \2193";
}

.disabled {
opacity: 0.5;
}
</style>

Click here to Download

Thursday, 12 May 2016

how to calculate running balance like entries of bank passbook using php mysql

how to calculate running balance like entries of bank passbook using php mysql

Demo - Download


Inded.php

<?php
error_reporting(0);
include('connection.php'); ?>
 <div class="col-lg-12">
 <style>
.mytab td, th {
    border: 1px solid #0da3e2;
    padding: 5px !important;
    text-align: center !important;
}

.mytab {
    width: 100%;
}
.red{
    color:red;}
h2{
    text-align:center;
}
</style>
<h2>Libero <span class="red">Ram</span></h2>
<table class="mytab">
<tr style="font-weight:bold">
<td>S.no</td>
<td>date</td>
<td>Credit</td>
<td>Debit</td>
<td>Balance</td></tr>
<?php
$sql = mysql_query("select * from test");
$i =1;
$x =1;

//<!--------- previous_balance using search by date ----->

$cridit =mysql_query("select sum(Credit) AS cri from test where  STR_TO_DATE(TransDate,'%Y-%m-%d')  < '2014-02-21'");
 $cridits= mysql_fetch_assoc($cridit);
 $previous_balance22 = $cridits['cri'] ;

 $Debit =mysql_query("select sum(Debit) AS dit from test where  STR_TO_DATE(TransDate,'%Y-%m-%d')  < '2014-02-21'");
 $Debits= mysql_fetch_assoc($Debit);
   $previous_balance1 = $Debits['dit'] ;
 echo $previous_balance1 =$previous_balance22 -  $previous_balance1;

 //<!--------- previous_balance ----->

while($rlt = mysql_fetch_array($sql)){
$cr = $rlt['Credit'];
$dit= $rlt['Debit'];
$tbal.$i  = ($bal.$i+$cr -$dit - 1);
 ?>

<tr><td><?php echo $x ?></td>
<td><?php echo $rlt['TransDate']; ?></td>
<td><?php echo  $cr ?></td>
<td><?php echo $dit  ?></td>
<td><?php echo $tbal.$i;
?></td>
</tr>
 <?php $i++;  $x++; }

?> </table></div>



Connection.php
<?php
    $dbhost = "localhost";
    $dbusername = "root";
    $dbpassword = "";
    $dbname = "new-trade";
    $item_per_page = 1;
$connection = mysql_connect($dbhost, $dbusername, $dbpassword) or die('Could not connect');
$db = mysql_select_db($dbname);

?>


Demo - Download

Monday, 11 January 2016

PHP MySQL Table Inline Editing using jQuery Ajax

 

Click Here to Download 

 Index.php

<?php include('connection.php'); ?>
<div id="Profile" class="content">
<div id="rlt" style="text-align:center; color:red;"></div>
<?php $profile_sqls=mysql_query("SELECT * from registration  where id='93'");
while($pro_relt= mysql_fetch_array($profile_sqls)) {
$id = $pro_relt['id'];  ?>     
<form method="post" action="" name="editpro">
<div class="col-lg-6">
<div class="form-group input-group edit_tr" id="<?php echo $id; ?>">
<span class="input-group-addon"> Email </span>
<input class="form-control" type="text"  id="email_<?php echo $id; ?>"  value="<?php echo $pro_relt['email']; ?>" name="email" placeholder="Email">
</div>  </div>
<div class="col-lg-6" >
<div class="form-group input-group edit_tr" id="<?php echo $id; ?>" >
<span class="input-group-addon" > Name </span>
<input class="form-control" type="text" id="first_input_<?php echo $id; ?>" value="<?php echo $pro_relt['name']; ?>" name="name" placeholder="User Name">
</div> </div>
 </form>
<?php } ?>
 </div>  

Java Script 


<script type="text/javascript" src="https://ajax.googleapis.com/
ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".edit_tr").change(function()
{
var ID=$(this).attr('id');
var name=$("#first_input_"+ID).val();
var email=$("#email_"+ID).val();

var dataString = 'id='+ID+'&name='+name+'&email='+email;
//alert(dataString);
if(name.length>0 && email.length>0 )
{
$.ajax({
type: "POST",
url: "save.php",
data: dataString,
cache: false,
success: function(html)
{
document.getElementById('rlt').innerHTML='Updated Successfully';
}
});
}
else
{
alert('Enter something.');
}
});
});
</script>

Save.php 

<?php
include("connection.php");
if($_POST['id'])
{
$id=mysql_escape_String($_POST['id']);
$firstname=mysql_escape_String($_POST['name']);
$email=mysql_escape_String($_POST['email']);
$sql = "update registration set name='$firstname', email='$email' where id='$id'";
mysql_query($sql);
}
?>


Connection.php
<?php
    $dbhost = "localhost";
    $dbusername = "root";
    $dbpassword = "";
    $dbname = "simple_inline_edit";
$connection = mysql_connect($dbhost, $dbusername, $dbpassword) or die('Could not connect');
$db = mysql_select_db($dbname);

?>


Click Here to Download