Friday, June 16, 2017

Data saved edited and deleted with ajax without refresh page

Here I explain how to save data on one page without refresh any page.



 

We have create many php files. Here first name is file name and after all code is given.

Database : 
db name : chirag
query : CREATE TABLE `ragister` (
  `id` int(11) NOT NULL COMMENT 'id',
  `fullname` varchar(255) NOT NULL,
  `emailid` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `filepath` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
query : ALTER TABLE `ragister`
  ADD PRIMARY KEY (`id`);

connect.php

<?php
if(!session_start()){
    session_start();
}
global $db_conx;

$db_conx = mysqli_connect("localhost", "root", "", "chirag");
if(mysqli_connect_errno()){
    echo mysqli_connect_error();
    exit();
}


function get_all_users(){
        global $db_conx;
        $ret = array();
        $select = mysqli_query($db_conx, "SELECT * FROM ragister  ORDER BY id DESC");
        while($row = mysqli_fetch_assoc($select)){
            $ret[] = $row;
        }
        return $ret;
    }

function get_specific_data($table, $where, $order='', $limit=''){
        global $db_conx;
        $sql = "SELECT * FROM ".$table." WHERE ".$where." ".$order." ".$limit;
        $result = mysqli_query($db_conx, $sql);
        if(mysqli_num_rows($result) == 1){
            return $ret = mysqli_fetch_assoc($result);
        }else{
            return '';
        }
    }
function updateuser($id_edit,$fullname_edit,$emailid_edit,$password_edit,$filepath_edit){
    global $db_conx;
    $update = "UPDATE ragister SET fullname = '".$fullname_edit."', emailid = '".$emailid_edit."', password = '".$password_edit."', filepath = '".$filepath_edit."'  WHERE id = '".(int)$id_edit."'";
            if(mysqli_query($db_conx, $update))
            {
                return true;
            }
            else
            {
                return false;
            }
}
?>

index.php

<?php
include 'connect.php';
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Home Page</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <!-- Latest compiled JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <style type="text/css" media="screen">
        #mydiv {
            position: fixed;
            top: 0;
            left: 0;
            bottom: 0;
            width: 100%;
            height: 100%;
            z-index: 10000;
            background-color: white;
            opacity: 0.8;
            display: none;
        }
        .ajax-loader {
            position: absolute;
            left: 50%;
            top: 50%;
            margin-left: -32px; /* -1 * image width / 2 */
            margin-top: -32px;  /* -1 * image height / 2 */
            display: block;
        }
        .errorBox {  /* for the error input text fields */
            border: 1px solid red;
        }   
        td{border: 1px solid #ccc;}
    </style>
</head>
<body>
    <div id="mydiv"> <img src="http://i59.tinypic.com/mm6691.gif" class="ajax-loader"/> </div>
    <div class="container">
        <div id="msg"></div>
       
        <div class="col-md-5" id="adddataform">
        <div class="">
                <h1>Add Data Form</h1>
        </div>
        <form name="addform" id="addform" method="post" enctype="multipart/form-data">
        <table>
            <tr>
                <td>Full Name : </td>
                <td><input type="text" id="fullname" value="" placeholder="Enter Full Name"></td>
            </tr>
            <tr>
                <td>Email ID : </td>
                <td><input type="email" id="emailid" value="" placeholder="Enter EmailID"></td>
            </tr>
            <tr>
                <td>Password : </td>
                <td><input type="password" id="password" value="" placeholder="Enter Password"></td>
            </tr>
            <tr>
                <td>File : </td>
                <td><input type="file" id="filepath" ></td>
            </tr>
            <tr>
                <td colspan="2" class="text-center"><button type="button" id="addform" onclick="adddata()">Save Form</button></td>
            </tr>
        </table>
        </form>
        </div>
        <div class="col-md-5" id="editdataform" style="display: none;">
        <div class="">
                <h1>Edit Data Form</h1>
        </div>
            <form name="addform" id="addform" method="post" enctype="multipart/form-data">
            <input type="hidden" id="id_edit" value="">
        <table>
            <tr>
                <td>Full Name : </td>
                <td><input type="text" id="fullname_edit" value="" placeholder="Enter Full Name" autocomplete="off"></td>
            </tr>
            <tr>
                <td>Email ID : </td>
                <td><input type="email" id="emailid_edit" value="" placeholder="Enter EmailID" autocomplete="off"></td>
            </tr>
            <tr>
                <td>Password : </td>
                <td><input type="password" id="password_edit" value="" placeholder="Enter Password"></td>
            </tr>
            <tr>
                <td>File : </td>
                <td><input type="file" id="filepath_edit" ></td>
            </tr>
            <tr>
                <td colspan="2" class="text-center">
                <button type="button" id="adddatabtn" onclick="newuser()">New User</button>
                <button type="button" id="addform" onclick="updateuser()">Update Form</button></td>
            </tr>
        </table>
        </form>
        </div>
        <div class="col-md-7">
        <div id="content"></div>
        </div>
    </div>

    <script type="text/javascript">
    function newuser(){
        $('#editdataform').hide();
        $('#adddataform').show();
    }
        function adddata(){
            var fullname = $('#fullname').val();
            var emailid = $('#emailid').val();
            var password = $('#password').val();
            $("#msg").html('');

            if( fullname == '' || emailid == '' || password == ''){}
                else{
                    var formData = new FormData($('#addform')[0]);
                    $.ajax({
                        type: "POST",
                        url: "ajax.php",
                        data: 'fullname='+fullname+'&emailid='+emailid+'&password='+password,
                        //data: formData,
                        beforeSend: function(){
                          $('#mydiv').show();
                        },
                        success: function(data){
                          $('#mydiv').hide();
                          if(data == 1)
                          {
                              $("#msg").html("<div class='col-md-12'><div class='alert alert-success fade in'><a class='close' title='close' aria-label='close' data-dismiss='alert' href='#'>×</a><strong>Done! </strong> Data saved. </div> </div>");
                          //$("body").load("home.php").hide().fadeIn(1500).delay(6000);
                             //window.location = "profile.php";

                             //$("#branderror").html();
                             //$("#profile-img").load(location.href + " #profile-img");
                             //window.location.href = 'thankyou.php';
                             $("#content").load("showdata.php");
                          }
                          else
                          {
                              $("#msg").html("<div class='col-md-12'><div class='alert alert-danger fade in'><a class='close' title='close' aria-label='close' data-dismiss='alert' href='#'>×</a><strong>Error! </strong> Error. Please try again. </div> </div>");
                          $("#branderror2").html(data);
                          //$("#branderror2").animate({scrollTop: 0}, 1000);
                          //$('#branderror2').animate({scrollTop:$('#branderror2').offset().top}, 'slow');
                          // $("html, body, .inner-page").animate({
                          //       scrollTop: $(".inner-page").offset().top
                          //   }, 2000);
                          }
                        }
                      });
                }
        }

        function updateuser(){
            var id_edit = $('#id_edit').val();
            var fullname_edit = $('#fullname_edit').val();
            var emailid_edit = $('#emailid_edit').val();
            var password_edit = $('#password_edit').val();
            var filepath_edit = $('#filepath_edit').val();
            $("#msg").html('');

            if( fullname_edit == '' || emailid_edit == '' || password_edit == ''){}
                else{
                    $.ajax({
                        type: "POST",
                        url: "ajax.php",
                        data: 'id_edit='+id_edit+'&fullname_edit='+fullname_edit+'&emailid_edit='+emailid_edit+'&password_edit='+password_edit+'&filepath_edit='+filepath_edit,
                        beforeSend: function(){
                          $('#mydiv').show();
                        },
                        success: function(data){
                          $('#mydiv').hide();
                          if(data == 1)
                          {
                              $("#msg").html("<div class='col-md-12'><div class='alert alert-success fade in'><a class='close' title='close' aria-label='close' data-dismiss='alert' href='#'>×</a><strong>Done! </strong> Data Updated. </div> </div>");
                          //$("body").load("home.php").hide().fadeIn(1500).delay(6000);
                             //window.location = "profile.php";

                             //$("#branderror").html();
                             //$("#profile-img").load(location.href + " #profile-img");
                             //window.location.href = 'thankyou.php';
                             $("#content").load("showdata.php");
                          }
                          else
                          {
                              $("#msg").html("<div class='col-md-12'><div class='alert alert-danger fade in'><a class='close' title='close' aria-label='close' data-dismiss='alert' href='#'>×</a><strong>Error! </strong> Error. Please try again. </div> </div>");
                          $("#branderror2").html(data);
                          //$("#branderror2").animate({scrollTop: 0}, 1000);
                          //$('#branderror2').animate({scrollTop:$('#branderror2').offset().top}, 'slow');
                          // $("html, body, .inner-page").animate({
                          //       scrollTop: $(".inner-page").offset().top
                          //   }, 2000);
                          }
                        }
                      });
                }
        }
    </script>
    <script type="text/javascript">
        function edituser(id){
            $('#adddataform').hide();
            $('#editdataform').show();
            //$("#editdataform")[0].reset();
            $.post('ajax.php', {show_id:id}, function(data){
                  if(data == ''){
                    alert('no data found');
                  }else{
                    //alert(data);
                    data = JSON.parse( data );
                    //console.log( data[0].response );;
                    //var final_data = data.split(';');
                    $('#id_edit').val(data.id);
                    $('#fullname_edit').val(data.fullname);
                    $('#emailid_edit').val(data.emailid);
                    $('#password_edit').val(data.password);
                    $('#filepath_edit').val(data.filepath);

                
                  }
                });
        }
    </script>
    <script type="text/javascript">
        function deleteuser(id){
            if (confirm("Are you sure?")) {
                //alert('clicked');
                $.ajax({
                        type: "POST",
                        url: "ajax.php",
                        data: 'id_delete='+id,
                        beforeSend: function(){
                          $('#mydiv').show();
                        },
                        success: function(data){
                          $('#mydiv').hide();
                          if(data == 1)
                          {
                              $("#msg").html("<div class='col-md-12'><div class='alert alert-success fade in'><a class='close' title='close' aria-label='close' data-dismiss='alert' href='#'>×</a><strong>Done!</strong> Data deleted. </div> </div>");
                            $("#content").load("showdata.php");
                          }
                          else
                          {
                              $("#msg").html("<div class='col-md-12'><div class='alert alert-danger fade in'><a class='close' title='close' aria-label='close' data-dismiss='alert' href='#'>×</a><strong>Error! </strong> Error. Please try again. </div> </div>");
                          $("#branderror2").html(data);
                          }
                        }
                      });
            }
            return false;
        }
    </script>
    <script>
$(document).ready(function() {
    $("#content").load("showdata.php");
});
</script>
</body>
</html>

ajax.php

<?php
include 'connect.php';


if(isset($_POST['fullname'])){
    $fullname = $_POST['fullname'];
    $emailid = $_POST['emailid'];
    $password = $_POST['password'];

    $sql = "INSERT INTO `ragister`(fullname, emailid, password) VALUES ('".$fullname."','".$emailid."','".$password."')";
    $query = mysqli_query($db_conx,$sql);
    if($query == true){echo '1';}else{echo "error";}
    //code for image upload
    $lastid = mysqli_insert_id($db_conx);
   
}

if(isset($_POST['show_id'])){
    $get_purchases = get_specific_data("ragister","id = '".(int)$_POST['show_id']."'");
    if($get_purchases == ''){
        echo '';
    }else{
        /*$final_details = implode(';',$get_purchases);
        echo $final_details;*/
        echo json_encode($get_purchases);
    }
}
if(isset($_POST['fullname_edit'])){
    $id_edit = $_POST['id_edit'];
    $fullname_edit = $_POST['fullname_edit'];
    $emailid_edit = $_POST['emailid_edit'];
    $password_edit = $_POST['password_edit'];
    $filepath_edit = $_POST['filepath_edit'];
    $updatequery = updateuser($id_edit,$fullname_edit,$emailid_edit,$password_edit,$filepath_edit);
    if($updatequery == true){echo '1';}else{echo 'error';}
}
if(isset($_POST['id_delete'])){
    $id_edit = $_POST['id_delete'];
    $sql = "DELETE FROM ragister WHERE id = '".(int)$id_edit."'";
    $updatequery = mysqli_query($db_conx, $sql);
    if($updatequery == true){echo '1';}else{echo 'error';}
}
?>

showdata.php

<?php
include 'connect.php';

   

?>
<div id="" class="">
<h1>Show All Data</h1>
<table>
    <tr>
        <td>ID</td>
        <td>Full Name</td>
        <td>Email ID</td>
        <td>Password</td>
        <td>Filepath</td>
        <td>Action</td>
    </tr>
    <?php $get_all_users = get_all_users();
    foreach($get_all_users as  $key => $users)
    {
        ?>
        <tr>
            <td><?php echo $users['id']; ?></td>
            <td><?php echo $users['fullname']; ?></td>
            <td><?php echo $users['emailid']; ?></td>
            <td><?php echo $users['password']; ?></td>
            <td><?php echo $users['filepath']; ?></td>
            <td>
                <button type="button" id="edit_<?php echo $users['id']; ?>" onclick="edituser(<?php echo $users['id']; ?>)" >Edit</button>
                <button type="button" id="delete_<?php echo $users['id']; ?>" onclick="deleteuser(<?php echo $users['id']; ?>)" >Delete</button>
            </td>
        </tr>
        <?php
    } ?>
</table>
</div>

No comments:

Post a Comment