CodeIgniter Tutorial - Cek Email Availability Menggunakan AJAX

 




Buatlah sebuah database dengan nama Blog (penamaan bebas). Dan tambahkan satu table dengan nama tb_users (penamaan bebas), kemudian tambahkan data kedalam tb_users satu baris data aja.


Gambar 1: Data dalam tabel tb_users


Setting database di file database.php
$active_group = 'default';
$query_builder = TRUE;

$db['default'= array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'blog',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

Setting base_url di file config.php
$config['base_url'= 'http://localhost/blog/';

Edit file autoload.php seperti dibawah ini:
$autoload['libraries'= array('database');
$autoload['helper'= array('url');

Edit file routes.php
$route['default_controller'= 'controller_email';
$route['404_override'= '';
$route['translate_uri_dashes'= FALSE;

Setelah melakukan beberapa set up, marilah kita eksekusi programnya. let's do it! 

Controller_email.php
<?php
defined('BASEPATH'or exit('No direct script access allowed');

class Controller_email extends CI_Controller
{
    public function index()
    {
        $data['title']  = "Email Availability";
        $this->load->view('view_email'$data);
    }

    public function cek_email()
    {
        if (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
            echo "<label class='text-danger'><span class='fa fa-times'></span> Email tidak sah</label>";
        } else {
            $this->load->model('Model_email');
            if ($this->Model_email->cek_email($_POST["email"])) {
                echo '<label class="text-danger"><span class="fa fa-times"></span> Email Sudah Terdaftar</label>';
            } else {
                echo '<label class="text-success"><span class="fa fa-check"></span> Email Tersedia</label>';
            }
        }
    }
}

Model_email.php
<?php

class Model_email extends CI_Model
{

    public function cek_email($email)
    {
        $this->db->where('email'$email);
        $query = $this->db->get('tb_users');

        if ($query->num_rows() > 0) {
            return true;
        } else {
            return false;
        }
    }
}

view_email.php
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $title?></title>

    <!-- CDN Bootstrap -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <!-- CDN Fontawesome -->
    <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <!-- CDN Jquery -->
    <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
</head>

<body>
    <div class="container mt-3" style="width:600px">
        <h4><?= $title?></h4>
        <br />
        <label>Masukkan Email Anda</label>
        <input type="text" name="email" id="email" class="form-control">
        <span id="hasil_email"></span>
    </div>
</body>

</html>

<script>
    $(document).ready(function() {
        $("#email").change(function() {
            var email = $("#email").val();                               // ambil value dari id email

            //cek jika email kosong
            if (email != "") {
                $.ajax({
                    url"<?= base_url(); ?>controller_email/cek_email"// controller untuk cek email
                    method"POST"                                     // method request yang digunakan
                    data: {
                        emailemail  // data yang dikirim ke server (name : value)
                    },
                    successfunction(data) {                            // callback jika berhasil
                        $("#hasil_email").html(data);                    // set id hasil_email dengan data yg di response dari server
                    }
                });
            }
        });
    });
</script>

DEMO PROGRAM


Semoga bermanfaat !!!

Posting Komentar

0 Komentar