Langsung ke konten utama

Insert Edit Record Menggunakan Ajax PHP Modal & Bootstrap Validator

 

Insert Edit Record Menggunakan Ajax PHP Modal & Bootstrap Validator
TUTORIAL AJAX PHP

INSERT EDIT RECORD MENGGUNAKAN AJAX PHP MODAL & BOOTSTRAP VALIDATOR


Tutorial Insert Edit Record Menggunakan Ajax PHP Modal & Bootstrap Validator ini akan membahas bagaimana cara membuat form input dan form edit menggunakan modal bootstrap dan bootstrap validator. Develindo.com

Menggunakan modal bootstrap akan membuat website anda semakin interaktif, dan bootsrap validator akan membuat form input dan edit yang anda buat semakin aman dengan fungsi-fungsi yang telah ditentukan.

ikuti langkah berikut ini.
Buat database dengan nama praktek dan buat tabel dengan nama tb_siswa

develindo.com

Isikan Beberapak data pada tabel yang telah anda buat

 

langkah berikutnya :

Buat file koneksi.php untuk menghubungkan database dengan form anda.

koneksi.php
 

<?php
//set time zone location sesuai negara, jadikan Asia Jakarta
date_default_timezone_set('Asia/Jakarta');

//set koneksi ke server sesuai host, user, password dan database
$server="localhost";
$user="root";
$pass="";
$database="praktek";
mysql_connect($server,$user,$pass)
 or die('Koneksi Ke database Error'); //mengkoneksikan dengan server 
jika tidak akan muncul pesan error
mysql_select_db($database) or 
die('Database Tidak Ditemukan');   //mengkoneksikan dengan database jika
 tidak akan muncul pesan database tidak ada

?>


buat file index.php untuk menampilkan data yang ada pada tabel siswa

index.php 

<!DOCTYPE html>
<html>
<head>
    <title>Develindo | Ajax PHP - Insert Edit Record Menggunakan Ajax php</title>
    <!-- Bootstrap core CSS -->
    <link href="css/bootstrap.css" rel="stylesheet">
    <link rel="stylesheet" href="dist/css/bootstrapValidator.css" />

    <!-- Bootstrap core JavaScript-->
    <script src="js/jquery.min.js"></script>
    <script src="js/bootstrap.js"></script>
    <!-- validator -->
    <script type="text/javascript" src="dist/js/bootstrapValidator.js"></script>
</head>
<body>
    <br /><br />
    <div class="container" style="width:800px;">
        <h2 align="center">Insert Edit Record Menggunakan Ajax PHP Modal Bootstrap Validator</h2>
        <br>
        <div>
           
 <button type="button" name="add" id="add" data-toggle="modal" 
data-target="#add_data_Modal" data-backdrop="static" class="btn 
btn-success">Tambah Data</button>
        </div><br>
        <div id="tabel_siswa">
            <div class="table-responsive">
                <table class="table table-bordered">
                    <tr>
                        <th>NIS</th>
                        <th>NISN</th>
                        <th>Nama Lengkap</th>
                        <th>Gender</th>
                        <th>Foto</th>
                        <th>Action</th>
                    </tr>
                    <?php
                    //panggil fungsi koneksi.php
                    include "koneksi.php";
                    //ambil data dari tb_siswa dan lakukan perulangan dengan while
                    $ambildata=mysql_query("select*from tb_siswa order by id_siswa desc");
                    while($a = mysql_fetch_array($ambildata))
                    {
                    ?>
                    <tr>
                        <td><strong><?php echo $a['id_siswa']; ?></strong></td>
                        <td><?php echo $a['nisn'];?></td>
                        <td><?php echo $a['nama_siswa'];?></td>
                        <td><?php echo $a['gender_siswa'];?></td>
                       
 <td><img src="images/<?php echo $a['foto_siswa'];?>" 
class="img-thumbnail" style="width:100px; height:100px;"></td>
                       
 <td><a class="btn btn-primary edit_data" id="<?php echo 
$a['id_siswa'];?>" href="javascript:void(0);" data-toggle="modal" 
data-target="#edit_data_Modal" 
data-backdrop="static">Edit</a></td>
                    </tr>
                    <?php
                    }
                    ?>
                </table>
            </div>
        </div>
    </div>


    <!-- Modal Popup untuk Input-->
    <div id="add_data_Modal" class="modal fade">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Input Data Siswa </h4>
                </div>
                <div class="modal-body">
                    <form id="defaultForm" method="post" class="form-horizontal" enctype="multipart/form-data">
                        <div class="form-group">
                            <label class="col-lg-3 control-label">Foto Siswa</label>
                            <div class="col-lg-5">
                                <input type="file" class="form-control" name="foto" id="foto" accept=".jpg, .png" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-lg-3 control-label">Nama Siswa</label>
                            <div class="col-lg-5">
                               
 <input type="text" class="form-control" name="nama" id="nama" 
placeholder="Nama Siswa" maxlength="30" autocomplete="off" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-lg-3 control-label">No Induk Siswa NIS)</label>
                            <div class="col-lg-5">
                               
 <input type="text" class="form-control" name="nis" id="nis" 
placeholder="No Induk Siswa" maxlength="8" autocomplete="off" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-lg-3 control-label">No Induk Siswa Nasional (NISN)</label>
                            <div class="col-lg-5">
                               
 <input type="text" class="form-control" name="nisn" id="nisn" 
placeholder="No Induk Siswa Nasional" maxlength="10" autocomplete="off" 
/>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-lg-3 control-label">Gender</label>
                            <div class="col-lg-5">
                                <div class="radio">
                                    <label>
                                        <input type="radio" name="jk" id="stat" value="L" /> Laki-laki
                                    </label>
                                </div>
                                <div class="radio">
                                    <label>
                                        <input type="radio" name="jk" id="stat" value="P" /> Perempuan
                                    </label>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-lg-9 col-lg-offset-3">
                                <input type="submit" name="submit" class="btn btn-primary" id="insert" value="Simpan">

                            </div>
                        </div>
                    </form>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal Popup untuk Edit-->
    <div id="edit_data_Modal" class="modal fade">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title"> Edit Data Siswa</h4>
                </div>
                <div class="modal-body">
                    <form id="editForm" method="post" class="form-horizontal" enctype="multipart/form-data">
                        <div class="form-group">
                            <label class="col-lg-3 control-label">Foto Siswa</label>
                            <div class="col-lg-5">
                                <input type="file" class="form-control" name="foto" id="foto" accept=".jpg, .png" />

                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-lg-3 control-label">Nama Siswa</label>
                            <div class="col-lg-5">
                               
 <input type="text" class="form-control" name="namas" id="namas" 
placeholder="Nama Siswa" maxlength="30" autocomplete="off" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-lg-3 control-label">No Induk Siswa NIS)</label>
                            <div class="col-lg-5">
                               
 <input type="text" class="form-control" name="niss" id="niss" 
placeholder="No Induk Siswa" maxlength="8" autocomplete="off" disabled 
/>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-lg-3 control-label">No Induk Siswa Nasional (NISN)</label>
                            <div class="col-lg-5">
                               
 <input type="text" class="form-control" name="nisns" id="nisns" 
placeholder="No Induk Siswa Nasional" maxlength="10" autocomplete="off" 
/>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-lg-3 control-label">Gender</label>
                            <div class="col-lg-5">
                                <div class="radio">
                                    <label>
                                        <input type="radio" name="jks" id="stat" value="L" /> Laki-laki
                                    </label>
                                </div>
                                <div class="radio">
                                    <label>
                                        <input type="radio" name="jks" id="stat" value="P" /> Perempuan
                                    </label>
                                </div>

                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-lg-9 col-lg-offset-3">
                                <input type="hidden" class="form-control" name="lama" id="lama" />
                                <input type="hidden" class="form-control" name="id" id="id" />
                               
 <input type="submit" name="submit" class="btn btn-primary" 
id="update" value="Update Data">
                            </div>
                        </div>
                    </form>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

</body>
</html>
<script>
    /*insert form*/

    $(document).ready(function () {
        $('#defaultForm')
            .bootstrapValidator({
                fields: {
                    foto: {
                        validators: {
                            notEmpty: {
                                message: 'Gambar Tidak Boleh Kosong !'
                            },
                            file: {
                                extension: 'png,jpg,jpeg',
                                type: 'image/png,image/jpg,image/jpeg',
                                maxSize: 2 * 1024 * 1024,
                                message: 'Ekstensi yang diperbolehkan hanya .jpg,.png dan Maksimal 2MB'
                            }
                        }
                    },
                    nama: {
                        validators: {
                            notEmpty: {
                                message: 'Nama Tidak Boleh Kosong !'
                            },
                        }
                    },
                    nis: {
                        validators: {
                            notEmpty: {
                                message: 'NIS Tidak Boleh Kosong !'
                            },
                            remote: {
                                type: 'POST',
                                url: 'remote.php',
                                message: 'NIS Sudah Terdaftar !',
                                delay: 1000
                            },
                            digits: {
                                message: 'Gunakan Angka !'
                            },
                        }
                    },
                    nisn: {
                        validators: {
                            notEmpty: {
                                message: 'NISN Tidak Boleh Kosong !'
                            },
                            digits: {
                                message: 'Gunakan Angka !'
                            }
                        }
                    },
                    jk: {
                        validators: {
                            notEmpty: {
                                message: 'Pilih Gender !'
                            },
                        }
                    },
                }
            })
            .on('success.form.bv', function (e) {
                // Prevent form submission
                e.preventDefault();

                $.ajax({
                    url: "insert.php",
                    method: "POST",
                    data: new FormData(this),
                    contentType: false,
                    cache: false,
                    processData: false,
                    beforeSend: function () {
                        $('#insert').val("sedang menyimpan...");

                    },
                    success: function (data) {
                        $('#defaultForm')[0].reset();
                        $('#defaultForm').bootstrapValidator('resetForm', true);
                        $('#add_data_Modal').modal('hide');
                        $('#tabel_siswa').html(data);
                        $('#insert').val("Simpan Data");
                        setTimeout(function () {
                            $('#success_message').fadeOut("Slow");

                        }, 2000);
                    }
                });

            });
    });

    /*edit data*/

    $(document).ready(function () {
        $(document).on('click', '.edit_data', function () {
            var id = $(this).prop("id");
            $.ajax({
                url: "fetch.php",
                method: "POST",
                data: { id: id },
                dataType: "json",
                success: function (data) {
                    $('#namas').val(data.nama_siswa);
                    $('#id').val(data.id_siswa);
                    $('#nisns').val(data.nisn);
                    $('#lama').val(data.foto_siswa);
                    if (data.gender_siswa == 'L') {
                        $('input:radio[name=jks][value="L"]').prop('checked', true)
                    } else {
                        $('input:radio[name=jks][value="P"]').prop('checked', true)
                    }
                    $('#update').val("Simpan Perubahan");
                    $('#edit_data_Modal').modal('show');
                }
            });
        });
    });

    /*edit form*/

    $(document).ready(function () {
        $('#editForm')
            .bootstrapValidator({
                fields: {
                    foto: {
                        validators: {
                            file: {
                                extension: 'png,jpg,jpeg',
                                type: 'image/png,image/jpg,image/jpeg',
                                maxSize: 2 * 1024 * 1024,
                                message: 'Ekstensi yang diperbolehkan hanya .jpg dan .png, dan Maksimal 2MB'
                            }
                        }
                    },
                    namas: {
                        validators: {
                            notEmpty: {
                                message: 'Nama Tidak Boleh Kosong !'
                            },
                        }
                    },
                    nisns: {
                        validators: {
                            notEmpty: {
                                message: 'NISN Tidak Boleh Kosong !'
                            },
                            digits: {
                                message: 'Gunakan Angka !'
                            }
                        }
                    },
                    jks: {
                        validators: {
                            notEmpty: {
                                message: 'Pilih Gender !'
                            },
                        }
                    },
                }
            })
            .on('success.form.bv', function (e) {
                // Prevent form submission
                e.preventDefault();

                $.ajax({
                    url: "update.php",
                    method: "POST",
                    data: new FormData(this),
                    contentType: false,
                    cache: false,
                    processData: false,
                    beforeSend: function () {
                        $('#update').val("sedang mengupdate...");
                    },
                    success: function (data) {
                        $('#editForm')[0].reset();
                        $('#editForm').bootstrapValidator('resetForm', true);
                        $('#edit_data_Modal').modal('hide');
                        $('#tabel_siswa').html(data);
                        $('#update').val("Simpan Perubahan");
                        setTimeout(function () {
                            $('#success_message').fadeOut("Slow");

                        }, 2000);
                    }
                });

            });
    });

</script>



buat file remote.php untuk memvalidasi NIS jika sudah terdaftar

remote.php

<?php
header('Content-type: application/json');

include "koneksi.php";
if(isset($_POST["nis"]))
{
  $valid='';
  $message='';
  $query = "SELECT * FROM tb_siswa WHERE id_siswa = '".$_POST["nis"]."'";
  $result = mysql_query($query);
  $row = mysql_num_rows($result);
  if($row < 1){
    $valid = true;
    $message="success";
  }
  else{
    $valid = false;
    $message="NIS Sudah Terdaftar";
  }
  echo json_encode(
    $valid ? array('valid' => $valid) : array('valid' => $valid, 'message' => $message)
    );
}
?>



buat file insert.php untuk menyimpan data ke database

insert.php
 

<?php
error_reporting(0);
include "koneksi.php";

if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
 header('HTTP/1.1 500 Error!');
 exit();
}
if(isset($_POST)){

  $output = '';
  $message = '';
  $nis = mysql_real_escape_string($_POST["nis"]);
  $nisn = mysql_real_escape_string($_POST["nisn"]);
  $nama = mysql_real_escape_string($_POST["nama"]);
  $jk = mysql_real_escape_string($_POST["jk"]);

  $message = '<div class="alert alert-success alert-dismissible">
 
 <button type="button" class="close" data-dismiss="alert" 
aria-label="Close"><span 
aria-hidden="true">&times;</span></button>
  <strong>Input Berhasil !</strong> Data Berhasil disimpan ke database.
  </div>';

  $foto = $_FILES["foto"]["name"];
  $size = $_FILES["foto"]["size"];
  $ext = strtolower(end(explode(".", $foto)));
  $allowed_ext = array("png", "jpg", "jpeg");
  if(in_array($ext, $allowed_ext))
  {
    if($size < (2*1024*1024))
    {
      $new_image = '';
      $new_name = md5(rand()) . '.' . $ext;
      $path = 'images/' . $new_name;
      list($width, $height) = getimagesize($_FILES["foto"]["tmp_name"]);
      if($width > "1000" || $height > "650") {
      if($ext == 'png')
      {
        $new_image = imagecreatefrompng($_FILES["foto"]["tmp_name"]);
      }
      if($ext == 'jpg' || $ext == 'jpeg')
      {
       $new_image = imagecreatefromjpeg($_FILES["foto"]["tmp_name"]);
     }
     $new_width=200;
     $new_height =($height/$width)*200;
     $tmp_image = imagecreatetruecolor($new_width, $new_height);
     imagealphablending($tmp_image, false);
     imagesavealpha($tmp_image,true);
     $transparent = imagecolorallocatealpha($tmp_image, 255, 255, 255, 127);
     imagefilledrectangle($tmp_image, 0, 0, $new_width, $new_height, $transparent);
     imagecopyresampled($tmp_image, $new_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
     imagejpeg($tmp_image, $path, 100);
     imagepng($tmp_image, $path);
     imagedestroy($new_image);
     imagedestroy($tmp_image);
     }else{
     move_uploaded_file($_FILES["foto"]["tmp_name"],"images/$new_name");
 }
    
 $query = "INSERT INTO 
tb_siswa(id_siswa,nama_siswa,nisn,gender_siswa,foto_siswa) VALUES 
('$nis','$nama','$nisn','$jk','$new_name');";

   }
   else
   {
    echo 'Gambar Maksimal berukuran 2MB';
  }
}
else
{
  echo 'Invalid Image File';
}
if(mysql_query($query))
{
 $output .= '<span id="success_message">' . $message . '</span>';
 $output .='<div class="table-responsive">
    <table class="table table-bordered">
        <tr>
            <th>NIS</th>
            <th>NISN</th>
            <th>Nama Lengkap</th>
            <th>Gender</th>
            <th>Foto</th>
            <th>Action</th>
        </tr>';
        $query = "SELECT * FROM tb_siswa order by id_siswa desc";
        $result = mysql_query($query);
        while($row = mysql_fetch_array($result))
        {
        $output .= '
        <tr>
            <td><strong>' . $row["id_siswa"] . '</strong></td>
            <td>' . $row["nisn"] . '</td>
            <td>' . $row["nama_siswa"] . '</td>
            <td>' . $row["gender_siswa"] . '</td>
           
 <td><img src="images/' .$row['foto_siswa']. '" 
class="img-thumbnail" style="width:100px; height:100px;"></td>

           
 <td><a class="edit_data" id="'.$row['id_siswa'].'" 
href="javascript:void(0);" data-toggle="modal" 
data-target="#edit_data_Modal" data-backdrop="static">Edit</a>
            </td>
        </tr>
        ';
        }
        $output .= '
    </table>
</div>';

} else{
  echo 'Error';
}
echo $output;
}
?>

buat file update.php untuk mengedit form dan menyimpan kembali ke database

update.php

<?php
error_reporting(0);
include "koneksi.php";

if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
 header('HTTP/1.1 500 Error!');
 exit();
}
if(isset($_POST)){

  $output = '';
  $message = '';
  $nis = mysql_real_escape_string($_POST["id"]);
  $nisn = mysql_real_escape_string($_POST["nisns"]);
  $nama = mysql_real_escape_string($_POST["namas"]);
  $jk = mysql_real_escape_string($_POST["jks"]);
  $lama = mysql_real_escape_string($_POST["lama"]);
  $message = '<div class="alert alert-success alert-dismissible">
 
 <button type="button" class="close" data-dismiss="alert" 
aria-label="Close"><span 
aria-hidden="true">&times;</span></button>
  <strong>Update Berhasil !</strong> Data Berhasil diupdate.
  </div>';

  if(!empty($_FILES["foto"]["name"])){
    $foto = $_FILES["foto"]["name"];
  $size = $_FILES["foto"]["size"];
  $ext = strtolower(end(explode(".", $foto)));
  $allowed_ext = array("png", "jpg", "jpeg");
  if(in_array($ext, $allowed_ext))
  {
    if($size < (2*1024*1024))
    {
      $new_image = '';
      $new_name = md5(rand()) . '.' . $ext;
      $path = 'images/' . $new_name;
      list($width, $height) = getimagesize($_FILES["foto"]["tmp_name"]);
      if($width > "1000" || $height > "450") {
      if($ext == 'png')
      {
        $new_image = imagecreatefrompng($_FILES["foto"]["tmp_name"]);
      }
      if($ext == 'jpg' || $ext == 'jpeg')
      {
       $new_image = imagecreatefromjpeg($_FILES["foto"]["tmp_name"]);
     }
     $new_width=900;
     $new_height =($height/$width)*900;
     $tmp_image = imagecreatetruecolor($new_width, $new_height);
     imagealphablending($tmp_image, false);
     imagesavealpha($tmp_image,true);
     $transparent = imagecolorallocatealpha($tmp_image, 255, 255, 255, 127);
     imagefilledrectangle($tmp_image, 0, 0, $new_width, $new_height, $transparent);
     imagecopyresampled($tmp_image, $new_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
     imagejpeg($tmp_image, $path, 100);
     imagepng($tmp_image, $path);
     imagedestroy($new_image);
     imagedestroy($tmp_image);
     }else{
     move_uploaded_file($_FILES["foto"]["tmp_name"],"images/$new_name");
 }

       unlink('images/'.$lama);
       $query = "UPDATE tb_siswa set nama_siswa='$nama', nisn='$nisn', foto_siswa='$new_name' WHERE id_siswa='$nis'";

     }
     else
     {
      echo 'Gambar Maksimal berukuran 2MB';
    }
  }
  else
  {
    echo 'Invalid Image File';
  }
}else{
 $query = "UPDATE tb_siswa set nama_siswa='$nama', nisn='$nisn' WHERE id_siswa='$nis'";
}

if(mysql_query($query))
{
 $output .= '<span id="success_message">' . $message . '</span>';
 $output .='<div class="table-responsive">
    <table class="table table-bordered">
        <tr>
            <th>NIS</th>
            <th>NISN</th>
            <th>Nama Lengkap</th>
            <th>Gender</th>
            <th>Foto</th>
            <th>Action</th>
        </tr>';
        $query = "SELECT * FROM tb_siswa order by id_siswa desc";
        $result = mysql_query($query);
        while($row = mysql_fetch_array($result))
        {
        $output .= '
        <tr>
            <td><strong>' . $row["id_siswa"] . '</strong></td>
            <td>' . $row["nisn"] . '</td>
            <td>' . $row["nama_siswa"] . '</td>
            <td>' . $row["gender_siswa"] . '</td>
           
 <td><img src="images/' .$row['foto_siswa']. '" 
class="img-thumbnail" style="width:100px; height:100px;"></td>

           
 <td><a class="btn btn-primary edit_data" 
id="'.$row['id_siswa'].'" href="javascript:void(0);" data-toggle="modal"
 data-target="#edit_data_Modal" data-backdrop="static">Edit</a>
            </td>
        </tr>
        ';
        }
        $output .= '
    </table>
</div>';

} else{
  echo 'Error';
}
echo $output;
}
?>


setelah semua file anda buat silahkan anda coba run di localhost anda.

silahkan download dan share artikel ini. Terimakasih, selamat mencoba
 

 DOWNLOAD SOURCE CODE  PREVIEW DEMO

DEVELINDO WEB | TUTORIAL PEMROGRAMAN WEBSITE

Komentar

Posting Komentar

Postingan populer dari blog ini

Login, Session, dan Logout

Cara Membuat File Setup / Installer Aplikasi Sendiri dengan Inno Setup Compiler