CodeIgniter jQuery

203
MENGGUNAKAN CODEIGNITER DAN JQUERY WAS-01 | Pemrograman PHP

Transcript of CodeIgniter jQuery

Page 1: CodeIgniter  jQuery

MENGGUNAKAN CODEIGNITER DAN JQUERY

WAS-01 | Pemrograman PHP

Page 2: CodeIgniter  jQuery

Sesi 01

Page 3: CodeIgniter  jQuery

PreRequisite

Page 4: CodeIgniter  jQuery

Sebelum Memulai...

WebserverWebprogramming PHP+HTMLOOP (Object Oriented Programming)MySQL + phpMyAdmin

Page 5: CodeIgniter  jQuery

Webserver

Definisi: A web server program is software that runs on the web site

hosting Server computer. Its main purpose is serving web pages; which means it waits for requests from web browsers (also known as clients) and responds by sending the required data back.

http://www.webdevelopersnotes.com/basics/what_is_web_server.php

Apache Tomcat Paket webserver: XAMPP (Windows), MAMP (Mac OS X), LAMP

(Linux)Microsoft's Internet Information Services (IIS)

Windows ServerNginx web server, Jigsaw, Klone, Abyss web server,

Oracle Web Tier, X5 (Xitami) web server, Zeus web server

Page 6: CodeIgniter  jQuery

Webprogramming PHP+HTML

HTML Static Web pages Tag dan Style

PHP Dynamic and interactive Web pages Menghasilkan dokumen HTML untuk dimunculkan di

browser Disisipkan ke dalam dokumen HTML

Page 7: CodeIgniter  jQuery

PHP

Tipe Data integer, floating point, character dan boolean array

Variabel Semua variabel diawali dengan $.

Misal: $nama, $alamat Nama variabel boleh sepanjang apapun, akan tetapi lebih baik jika nama

itu simple dan bermakna. Misal: $tempat_dan_tanggal_lahir

Nama variabel hanya boleh dibentuk dari alphabet, angka dan underscore. Misal: $data1_a

Nama variabel boleh diawali alphabet atau underscore tapi tidak boleh angka. Misal: $3bersaudara, $2wanita, $1lelaki

Nama variabel merupakan case-sensitive artinya variabel $nama tidak sama dengan $Nama atau $NaMa

Page 8: CodeIgniter  jQuery

PHP (cont.)

Operator Aritmetik: +, -, *, /, % Logika: and, or, xor, !, &&, || Pembanding: ==, !=, <>, ===, !==, <, >, <=, >= Bitwise: &, |, ^, ~, <<, >>

Page 9: CodeIgniter  jQuery

PHP (cont.)

Percabanganif (kondisi) { ... } [ else { ... } ]if (kondisi) { ... } elseif { ... } [ else { ... } ]switch (ekspresi) { case ‘nilai_ekspresi_1’: ....; break; case ‘nilai_ekspresi_2’: ....; break; case ‘nilai_ekspresi_3’: ....; break; ... case ‘nilai_ekspresi_n’: ....; break; default: ...; [ break; ]}

Page 10: CodeIgniter  jQuery

PHP (cont.)

Operator Ternary ‘?’ kondisi ? pernyataan1_jika_benar :

pernyataan2_jika_salah;

<?php$nilai = 80;$status = ($nilai>70)?“Lulus”:“Tidak Lulus”;echo “Status kita adalah $status”;?>

Page 11: CodeIgniter  jQuery

PHP (cont.)

Looping / Pengulanganwhile (kondisi) { ... }do { ... } while (kondisi);for (nilaiAwal; kondisi; increment) { ... }foreach (array_expression as $value) { ... }foreach (array_expression as $key => $value) { ... }

Page 12: CodeIgniter  jQuery

PHP (cont.)

Fungsifunction nama_fungsi(<arg1>,<arg2>,...,<argN>) { Blok pernyataan; return <return_value>; //opsional}

Page 13: CodeIgniter  jQuery

OOP

Object Oriented Programming (Pemrograman Berorientasi Object) merupakan sebuah paradigma baru dalam teknik pemrograman. Dimana isu terpenting dari pemrograman OOP adalah objek itu sendiri

ClassObjekPropertyMethodConstructor / Destructor

Page 14: CodeIgniter  jQuery

OOP (cont.)

Sumber: http://www.4guysfromrolla.com/webtech/chapters/BuildASPNETWebSite/ch02.2.shtml

Page 15: CodeIgniter  jQuery

OOP (cont.)

Inheritance Merupakan mekanisme pewarisan sebuah kelas oleh kelas yang lain.

Artinya, kelas yang mewarisi kelas lain akan memiliki sifat dari kelas yang diwarisinya.

Contoh: kelas mobil_balap mewarisi kelas mobilEncapsulation

Merupakan suatu proteksi terhadap member kelas agar tidak dapat diakses atau diubah dari luar kelas.

Contoh: property saldo pada kelas rekeningPolymorphism

Polymorphism adalah merupakan kemampuan untuk menciptakan variable, function, atau sebuah object yang memiliki banyak bentuk. Inti dari polymorphism adalah meng-overide method pada subkelas.

Contoh: method bicara() pada kelas anjing dan kucing hasil pewarisan dari kelas hewan

Page 16: CodeIgniter  jQuery

MySQL + phpMyAdmin

MySQL merupakan database yang bersifat open source sehingga banyak digunakan di dunia. Walaupun gratis, MySQL tetap berkualitas dan sudah cukup memberikan performa yang memadai.

Ada 2 cara menggunakan MySQL: Menggunakan console (command line) Menggunakan phpMyAdmin

http://localhost/phpmyadmin

Page 17: CodeIgniter  jQuery

MySQL

Tipe Data Numeric

Integer: INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT

Fixed-Point: DECIMAL, NUMERIC Floating-Point: FLOAT, DOUBLE

String CHAR, VARCHAR, BINARY, VARBINARY, BLOB, TEXT,

ENUM, dan SET Date and Time

DATE, TIME, DATETIME, TIMESTAMP, dan YEAR

Page 18: CodeIgniter  jQuery

MySQL (cont.)

Data Definition Language (DDL) adalah query SQL yang berhubungan dengan pendefinisian basis data atau struktur tabel. create nama_database; alter table nama_tabel add nama_kolom tipe_data;

Data Manipulation Language (DDL) adalah query SQL yang berhubungan dengan pengolahan data dalam suatu tabel. select * from nama_tabel; insert into master_strata (id, nama) values(1, 'S1');

Page 19: CodeIgniter  jQuery

Web Programming vs Web Designing

Page 20: CodeIgniter  jQuery

Web Programming vs Web Designing

Web Programming Mengelola kode yang berhubungan dengan bisnis

proses suatu aplikasi (backend)Web Designing

Mengelola kode yang berhubungan dengan antar muka dan interaksi aplikasi dengan pengguna (frontend)

Web Programmer ≠ Web Designer

Page 21: CodeIgniter  jQuery

Framework

Page 22: CodeIgniter  jQuery

Evolusi Pengembangan Web

index.php

about.php news.php links.php contact.phpproduct.php

Page 23: CodeIgniter  jQuery

Evolusi Pengembangan Web

index.php

page.php

header.php

news.php

footer.php

Setiap bagian yang umum dipecah menjadi beberapa bagian

Page 24: CodeIgniter  jQuery

Evolusi Pengembangan Web

index.php

Controller

Model

View

Umumnya menggunakan framework PHP

Page 25: CodeIgniter  jQuery

Mengapa Framework?

Framework aplikasi web Membangun website dinamis Pustaka untuk koneksi ke berbagai database Template frameworks Manajemen session Fungsi paging untuk menampilkan data Menyediakan banyak fungsi yang siap pakai ... dan banyak lagi lainnya

Page 26: CodeIgniter  jQuery

Arsitektur MVC

Page 27: CodeIgniter  jQuery

Arsitektur HMVC

Page 28: CodeIgniter  jQuery

MVC

View (views/showProduct.php)<html>

<body><p>Product Count:<?=$count?></p></body>

</html>

Controller (controllers/product.php)function showProduct($id) {

$this->load->model(“product”);$count = $this->product->getCount($id);$data[‘count’] = $count;$this->load->view(“showProduct”, $data);

}

Model (models/product.php)function getCount($id) {

$this->db->where(“id”, $id);$this->db->from(“my_product”);$query = $this->db->get();return $query->num_rows();

}

View

Controller

Model

Page 29: CodeIgniter  jQuery

Beberapa Framework

Page 30: CodeIgniter  jQuery

Kenapa CodeIgniter?

GratisRingan & CepatMenggunakan M-V-CMemiliki pustaka yang lengkapTerdokumentasi dengan baikKomunitas berkembang pesat

Page 31: CodeIgniter  jQuery

Instalasi CodeIgniter

Download http://ellislab.com/codeigniter/download

Unzip file CodeIgniter_2.1.3.zip ke DocumentRoot webserver (/xampp/htdocs/)

Rename folder “CodeIgniter_2.1.3” menjadi “ci”

Edit application/config/config.php application/config/database.php

Buka http://localhost/ci/index.php

Page 32: CodeIgniter  jQuery

Application Flow of CodeIgniter

Page 33: CodeIgniter  jQuery

URL pada CodeIgniter

http://localhost/news.php?mode=edit&id=10

http://localhost/index.php/news/edit/10

Page 34: CodeIgniter  jQuery

Struktur Direktori

applicationsystemuser_guideindex.php

Front controller yang bergfungsi menginisiasi

segala sumber daya yang dibutuhkan untuk

menjalankan CodeIgniter

Tempat kita menyimpan coding aplikasi

Core dari framework CodeIgniter

Page 35: CodeIgniter  jQuery

Struktur Direktori Aplikasi

Config -> konfigurasi aplikasiControllers -> tempat menyimpan ControllerErrors -> CI error messageHelpers -> tempat menyimpan HelpersLibraries -> tempat menyimpan LibrariesLanguage -> jika menggunakan multi bahasaModels -> tempat menyimpan ModelViews -> tempat menyimpan View

Page 36: CodeIgniter  jQuery

Membangun Aplikasi

Page 37: CodeIgniter  jQuery

Konfigurasi

Edit file application/config/config.php $config['base_url'] = 'http://localhost/ci/index.php/';

Buka http://localhost/ci/index.php application/controllers/welcome.php application/views/welcome_message.php

Default controller: application/config/routes.php

$route['default_controller'] = "welcome";

Alternatif: http://localhost/ci/index.php/welcome http://localhost/ci/index.php/welcome/index

Page 38: CodeIgniter  jQuery

Latihan 10 menit

Modifikasi bebas view welcome_message.php

Page 39: CodeIgniter  jQuery

Controller

[BARU] application/controllers/about.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class About extends CI_Controller {public function __construct() {

parent::__construct();}

function index(){ echo "About Me";}

}

/* End of file about.php *//* Location: ./application/controllers/about.php */

http://localhost/ci/index.php/about

Page 40: CodeIgniter  jQuery

View

[BARU] application/views/v_about.php

<html><title> View Pertama</title><body> <h1>About me</h1></body></html>

Page 41: CodeIgniter  jQuery

Controller

[EDIT] application/controllers/about.php

...class About extends CI_Controller {

public function __construct() { parent::__construct();

}

function index(){ echo "About Me";}

function me() { $this->load->view('v_about');}

}...

http://localhost/ci/index.php/about/me

Page 42: CodeIgniter  jQuery

Controller -> View

[EDIT] application/controllers/about.php

...function me() { $this->load->view('v_about');}

function person() {$data = array( ‘nama’ => ‘Kenggo’, ‘email’ => ‘[email protected]’);$this->load->view(‘v_about_person’, $data);

}}...

Page 43: CodeIgniter  jQuery

View

[BARU] application/views/v_about_person.php

<html><title> View Pertama</title>

<body> <h1>About <?=$nama?></h1> <h2>Email me at <?=$email?></h2></body></html>

http://localhost/ci/index.php/about/person

Page 44: CodeIgniter  jQuery

Controller -> View

[EDIT] application/controllers/about.php

...function person() {$data = array( ‘nama’ => ‘Kenggo’, ‘email’ => ‘[email protected]’);$this->load->view(‘v_about_person’, $data);}

function post($nama, $email) {$data = array( ‘nama’ => $nama, ‘email’ => urldecode($email));$this->load->view(‘v_about_person’, $data);}

}...

http://localhost/ci/index.php/about/post/Yuki/yuki%40gmail.com

Page 45: CodeIgniter  jQuery

Referensi

http://localhost/ci/index.php/about/post/Yuki/yuki%40gmail.com

yuki%40gmail.com = urlencode(‘[email protected]’); [email protected] = urldecode(‘yuki%40gmail.com’); Beberapa karakter khusus tidak boleh dilewatkan ke URL

Page 46: CodeIgniter  jQuery

PHP Closing Tag

INCORRECT:<?php

echo "Here's my code!";

?>

CORRECT:<?php

echo "Here's my code!";

/* End of file myfile.php *//* Location: ./system/modules/mymodule/myfile.php */

Page 47: CodeIgniter  jQuery

Latihan 15 menit

Modifikasi bebas :

- about.php

- v_about_person.php

Page 48: CodeIgniter  jQuery

Model

[BARU] application/models/m_about.php

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class M_about extends CI_Model { function __construct() { parent::__construct(); }

function get_data() {return array('nama' => 'Miu', 'email' => '[email protected]');

}

}

/* End of file m_about.php */ /* Location: ./application/models/m_about.php */

Page 49: CodeIgniter  jQuery

Controller

[EDIT] application/controllers/about.php

...function post($nama, $email) {$data = array( 'nama' => $nama, 'email' => urldecode($email));$this->load->view('v_about_person', $data);}

function get_person() {$this->load->model('M_about');$data = $this->M_about->get_data();//$data = M_about::get_data();$this->load->view('v_about_person', $data);}

}...

http://localhost/ci/index.php/about/get_person

Page 50: CodeIgniter  jQuery

• Buka phpMyAdmin• Buat database “ci_training”• Buat tabel “person” sbb:

• Isi dengan data sbb:

Buat db & tabel

Page 51: CodeIgniter  jQuery

• [EDIT] application/config/database.php• $db['default']['hostname'] = 'localhost';• $db['default']['username'] = 'root';• $db['default']['password'] = ‘password';• $db['default']['database'] = 'ci_training';• $db['default']['dbdriver'] = 'mysql';

• [EDIT] application/config/autoload.php• $autoload['libraries'] = array('database');

Configurasi

Page 52: CodeIgniter  jQuery

Model

[EDIT] application/models/m_about.php

... function get_data($id) {

$this->db->select(‘nama, email’);$this->db->from(‘person’);$this->db->where(‘id’, $id);$q = $this->db->get();$r = $q->result_array();return $r[0];

}

...

Page 53: CodeIgniter  jQuery

Controller

[EDIT] application/controllers/about.php

...function get_person($id) {

$this->load->model('M_about');$data = $this->M_about->get_data($id);$this->load->view('v_about_person', $data);

}

}...

http://localhost/ci/index.php/about/get_person/1

Page 54: CodeIgniter  jQuery

Latihan 30 menit

• Buat fungsi get_email_by_nama() di model m_about.php

• Buat tabel “barang” dengan field id, nama dan jumlah (tipe data sesuaikan), kemudian buatkan model, view dan controller-nya seperti contoh sebelumnya

TIPS: ketik ulang, jangan copy-paste

Page 55: CodeIgniter  jQuery

Sesi 02

Page 56: CodeIgniter  jQuery

Pustaka CodeIgniter

DatabaseFile UploadingPaginationInput and Security (SQL Injection)SessionForm Validationdll

Page 57: CodeIgniter  jQuery

FORM DAN DATABASE

Page 58: CodeIgniter  jQuery

Form dan Database

Form Login Buat tabel user “daftar_user”

Insert data sbb:

Page 59: CodeIgniter  jQuery

View

[BARU] application/views/v_login.php

<html><head> <meta charset="utf-8"> <title>Welcome to CodeIgniter</title></head><body>

<form id='login' action='<?=base_url()?>login' method='post'><fieldset ><legend>Login</legend><input type='hidden' name='submitted' id='submitted' value='1'/> <label for='username' >UserName*:</label><input type='text' name='username' id='username' maxlength="50" /> <label for='password' >Password*:</label><input type='password' name='password' id='password' maxlength="50" /> <input type='submit' name='Submit' value='Submit' />

</fieldset></form>

</body></html>

Page 60: CodeIgniter  jQuery

Controller

[BARU] application/controllers/login.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {public function __construct() {

parent::__construct();}

function index(){$this->load->view('v_login');

}

}

/* End of file login.php *//* Location: ./application/controllers/login.php */

http://localhost/ci/index.php/login

Page 61: CodeIgniter  jQuery

Error? Blank?

[EDIT] application/views/v_login.php

…<body>

<?php$this->load->helper('url');?>

<form id='login' action='<?=base_url()?>login' method='post'>

http://localhost/ci/index.php/login

Page 62: CodeIgniter  jQuery

base_url()

Isi dari base_url() sesuai dengan konfigurasi di application/config/config.php $config['base_url'] = 'http://localhost/ci/index.php/';

Page 63: CodeIgniter  jQuery

FORM HELPER

Page 64: CodeIgniter  jQuery

View

[BARU] application/views/v_login2.php

...<body>

<?php$this->load->helper('form');$this->load->helper('url');echo form_open(base_url().'login');

echo form_fieldset('Login');echo form_hidden('submitted', '1');

echo form_label('UserName*:', 'username');

$data = array('name'=>'username', 'id'=>'username', 'maxlength'=>'50');echo form_input($data);

Page 65: CodeIgniter  jQuery

View (cont.)

… application/views/v_login2.php

… echo form_label('Password*:', 'password');

$data = array('name'=>'password', 'id'=>'password', 'maxlength'=>'50');echo form_password($data);

echo form_submit('Submit', 'Submit');

echo form_fieldset_close();echo form_close();?>

</body></html>

Page 66: CodeIgniter  jQuery

Controller

[EDIT] application/controllers/login.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {public function __construct() {

parent::__construct();}

function index(){$this->load->view('v_login2');

}

}

/* End of file login.php *//* Location: ./application/controllers/login.php */

http://localhost/ci/index.php/login

Page 67: CodeIgniter  jQuery

Autoload Helper

• [EDIT] application/config/autoload.php• $autoload['helper'] = array('url', 'form');

[EDIT] application/views/v_login2.php

...<?php$this->load->helper('form');$this->load->helper('url');echo form_open(base_url().'login');?>...

Page 68: CodeIgniter  jQuery

Form Helper

form_open()form_open_multipart(

)form_hidden()form_input()form_upload()form_textarea()form_dropdown()form_multiselect()form_fieldset()

form_fieldset_close()form_checkbox()form_radio()form_submit()form_label()form_reset()form_button()form_close()

Page 69: CodeIgniter  jQuery

VALIDATION

Page 70: CodeIgniter  jQuery

View

[BARU] application/views/v_main.php

<!DOCTYPE html><html lang="en"><head><title>Login Success</title>

</head><body>

<div><h1>Login Success</h1>

</div></body></html>

Page 71: CodeIgniter  jQuery

Model

[BARU] application/models/m_daftar_user.php<?php defined('BASEPATH') OR exit('No direct script access allowed');

class M_daftar_user extends CI_Model { function __construct() { parent::__construct(); }

function get_data($username, $passwd) {$this->db->from('daftar_user');$this->db->where(array('user' => $username, 'passwd' =>

md5($passwd)));return $this->db->count_all_results();

}}

/* End of file m_daftar_user.php */ /* Location: ./application/models/m_daftar_user.php */

Page 72: CodeIgniter  jQuery

[EDIT] Controller: login.php

function index(){ $this->load->library('input');

$submitted = $this->input->post("submitted")?$this->input->post("submitted"):""; if ($submitted == 1) { $username = $this->input->post("username")?$this->input->post("username"):""; $password = $this->input->post("password")?$this->input->post("password"):""; if ($username == "") { show_error('Kolom username kosong' ); } else { $this->load->model('M_daftar_user'); if ($this->M_daftar_user->get_data($username, $password)>0) { $this->load->view('v_main'); } else { show_error('Maaf, user/password Anda tidak cocok' ); } } } else { $this->load->view('v_login2'); }}

Page 73: CodeIgniter  jQuery

View

[BARU] application/views/v_login3.php Save as dari “v_login2.php” dengan perubahan

berikut:

... <body>

<?phpecho validation_errors();echo form_open(base_url().'login/validasi');?>...

Page 74: CodeIgniter  jQuery

[EDIT] Controller: login.php

function validasi() { $this->load->library(array('input', 'form_validation'));

$this->form_validation->set_rules('username', 'Username', 'required'); $this->form_validation->set_rules('password', 'Password', 'required'); if ($this->form_validation->run() == FALSE) { $this->load->view('v_login3'); } else { $submitted = $this->input->post("submitted")?$this->input->post("submitted"):""; if ($submitted == 1) { $username = $this->input->post("username")?$this->input->post("username"):""; $password = $this->input->post("password")?$this->input->post("password"):""; if ($username == "") { show_error('Kolom username kosong' ); } else { $this->load->model('M_daftar_user'); if ($this->M_daftar_user->get_data($username, $password)>0) { $this->load->view('v_main'); } else { show_error('Maaf, user/password Anda tidak cocok' ); } } } }}

Page 75: CodeIgniter  jQuery

Tes Validasi

URL: http://localhost/ci/index.php/login/validasi

Kasus: User/Password dikosongkan User/Password diisi data salah User/Password diisi data valid

Page 76: CodeIgniter  jQuery

[EDIT] Controller: login.php

function validasi() { $this->load->library(array('input', 'form_validation'));

$this->form_validation->set_message('required', ‘Maaf, kolom %s tidak boleh dikosongkan.');

$this->form_validation->set_rules('username', 'Username', 'required'); $this->form_validation->set_rules('password', 'Password', 'required'); ...

Page 77: CodeIgniter  jQuery

Update

[EDIT] application/views/v_login3.phpGanti teks “UserName*” menjadi “Nama User*”Ganti teks “Password*” menjadi “Kata Kunci*”

[EDIT] application/controllers/login.php$this->form_validation->set_rules('username', 'Nama User',

'required');$this->form_validation->set_rules('password', 'Kata Kunci',

'required');

http://localhost/ci/index.php/login/validasi

Page 78: CodeIgniter  jQuery

Rule Validasi

Page 79: CodeIgniter  jQuery

PAGINATION

Page 80: CodeIgniter  jQuery

Data

Download http://167.205.108.215/ci/mhs.sqlImport ke database “ci_training”

Tabel: tmst_mahasiswa Jumlah data: 30 records

Page 81: CodeIgniter  jQuery

[BARU] Model: m_mahasiswa.php

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class M_mahasiswa extends CI_Model { function __construct() { parent::__construct(); }

function get_all_data() {$this->db->order_by('nim', 'asc');return $this->db->get('tmst_mahasiswa');

}

}

/* End of file m_mahasiswa.php */ /* Location: ./application/models/m_mahasiswa.php */

Page 82: CodeIgniter  jQuery

[BARU] Controller: mahasiswa.php

...class Mahasiswa extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('M_mahasiswa'); } function index(){ $q = $this->M_mahasiswa->get_all_data(); if ($q->num_rows()>0) { $m = array(); foreach ($q->result() as $row) { $m[] = array($row->nim, $row->nama_mahasiswa, $row->jk, $row->tanggal_masuk); } $data['mhs'] = $m; $this->load->view('v_mahasiswa', $data); } else { show_error('Sorry, no data'); } }}...

Page 83: CodeIgniter  jQuery

[BARU] View: v_mahasiswa.php

...<table> <thead> <tr><td>No</td><td>NIM</td><td>Nama Mahasiswa</td><td>JK</td><td>Tgl Masuk</td></tr> </thead> <tbody> <?php $i = 1; foreach ($mhs as $m) { ?> <tr> <td align="right"><?=$i?></td> <?php foreach ($m as $v) { echo "<td>$v</td>"; }; ?> </tr> <?php $i++; } ?> </tbody></table>...

http://localhost/ci/index.php/mahasiswa

Page 84: CodeIgniter  jQuery

[EDIT] Model: m_mahasiswa.php

... function get_data($page=0) { $this->db->limit(10,$page); $this->db->order_by('nim', 'asc'); return $this->db->get('tmst_mahasiswa'); } ...

Page 85: CodeIgniter  jQuery

[EDIT] Controller: mahasiswa.php

...function data($idx=0){ $this->load->library('pagination');

$config['base_url'] = base_url().'mahasiswa/data/'; $config['total_rows'] = 30; $config['per_page'] = 10;

$this->pagination->initialize($config);

$q = $this->M_mahasiswa->get_data($idx); if ($q->num_rows()>0) { $m = array(); foreach ($q->result() as $row) { $m[] = array($row->nim, $row->nama_mahasiswa, $row->jk, $row->tanggal_masuk); } $data['mhs'] = $m; $data['page'] = $this->pagination->create_links(); $this->load->view('v_mahasiswa_page', $data); } else { show_error('Sorry, no data'); }}...

Page 86: CodeIgniter  jQuery

[BARU] View: v_mahasiswa_page.php

...<table> <thead> <tr><td>No</td><td>NIM</td><td>Nama Mahasiswa</td><td>JK</td><td>Tgl Masuk</td></tr> </thead> <tbody> <?php $i = 1; foreach ($mhs as $m) { ?> <tr> <td align="right"><?=$i?></td> <?php foreach ($m as $v) { echo "<td>$v</td>"; }; ?> </tr> <?php $i++; } ?>

<tr><td colspan="5"><?=$page?></td></tr> </tbody></table>...

http://localhost/ci/index.php/mahasiswa/data

Page 87: CodeIgniter  jQuery

Active Record

SELECT * FROM tabel$query = $this->db->get(‘tabel');

atau

$this->db->from(‘tabel’);$query = $this->db->get();

Page 88: CodeIgniter  jQuery

Active Record

SELECT * FROM tabel WHERE id=10$this->db->where(‘id’, 10);$query = $this->db->get(‘tabel');

atau

$this->db->where(‘id’, 10); $this->db->from(‘tabel’);$query = $this->db->get();

Page 89: CodeIgniter  jQuery

Active Record

SELECT * FROM tabel WHERE id=10 AND jk=‘P’$this->db->where(‘id’, 10);$this->db->where(‘jk’, ‘P’);

atau

$this->db->where(array(‘id’ => 10, ‘jk’ => ‘P’));

Page 90: CodeIgniter  jQuery

Active Record

... WHERE id>10 and jk=‘P’ AND LEFT(nama, 1)=‘A’

$this->db->where(array(‘id >’ => 10, ‘jk’ => ‘P’)); $this->db->where(“LEFT(nama,1)=‘A’”, NULL, FALSE);...

Page 91: CodeIgniter  jQuery

Active Record

SELECT * FROM tabel WHERE id=10 OR jk=‘P’$this->db->where(‘id’, 10);$this->db->or_where(‘jk’, ‘P’);

Page 92: CodeIgniter  jQuery

Active Record

SELECT * FROM tabel WHERE nama LIKE ‘%budi%’$this->db->like(‘nama’, ‘budi’);

SELECT * FROM tabel WHERE nama LIKE ‘budi%’$this->db->like(‘nama’, ‘budi’, ‘after’);

SELECT * FROM tabel WHERE nama LIKE ‘%budi’$this->db->like(‘nama’, ‘budi’, ‘before’);

Page 93: CodeIgniter  jQuery

Active Record

SELECT * FROM tabel WHERE id=10 OR jk=‘P’

$q = $this->db->query(“SELECT * FROM tabel WHERE id=10 OR jk=‘P’”);

Page 94: CodeIgniter  jQuery

Active Record

SELECT * FROM tabel1 JOIN tabel2 ON tabel2.id=tabel1.id;

$this->db->from(‘tabel1’);$this->db->join(‘tabel2’, ‘tabel2.id=tabel1.id’);$q = $this->db->get();

Page 95: CodeIgniter  jQuery

Latihan 15 menit

Buat fungsi pada model untuk menghitung jumlah semua record pada tabel tmst_mahasiswa

Isikan jumlah record yang dihasilkan tersebut ke baris $config['total_rows'] = 30; pada controller mahasiswa.php

Page 96: CodeIgniter  jQuery

[BARU] Helper: utility_helper.php

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

if (!function_exists('trimTime')) { function trimTime($tgl) { $temp = explode(' ', $tgl); return $temp[0]; }}

if (! function_exists('YMD2DMY')) { function YMD2DMY($tgl, $separator) { $arr = explode($separator, $tgl); if (count($arr)==3) { return sprintf('%s%s%s%s%s', $arr[2], $separator, $arr[1], $separator, $arr[0]); } else { return $tgl; } }}

Page 97: CodeIgniter  jQuery

[EDIT] View: v_mahasiswa_page.php

...$this->load->helper('utility');foreach ($mhs as $m) { ?>

<tr> <td align="right"><?=$i?></td> <?php foreach ($m as $k => $v) { if ($k==3) { $v = YMD2DMY(trimTime($v), '-'); } echo "<td>$v</td>"; }; ?> </tr> ...

http://localhost/ci/index.php/mahasiswa/data

Page 98: CodeIgniter  jQuery

FORM ENTRY

Page 99: CodeIgniter  jQuery

Form Entry Mahasiswa

[EDIT] application/config/autoload.php $autoload['libraries'] = array('database', 'input',

'form_validation'); $autoload['helper'] = array('url', 'form', 'utility');

Page 100: CodeIgniter  jQuery

[EDIT] Helper: utility_helper.php

...if (! function_exists('DMY2YMD')) { function DMY2YMD($tgl, $separator) { $arr = explode($separator, $tgl); if (count($arr)==3) { return sprintf('%s%s%s%s%s', $arr[2], $separator, $arr[1], $separator, $arr[0]); } else { return $tgl; } }}

Page 101: CodeIgniter  jQuery

[EDIT] Model: m_mahasiswa.php

...

function insert_data($fields) {$this->db->insert('tmst_mahasiswa', $fields);return $this->db->affected_rows();

}

Page 102: CodeIgniter  jQuery

[BARU] View: v_form_mahasiswa.php...<?phpecho validation_errors();echo form_open(base_url().'mahasiswa/entry');echo form_fieldset('Data Mahasiswa');echo form_hidden('submitted', '1'); echo form_label('NIM*:', 'nim');$data = array('name'=>'nim', 'id'=>'nim', 'maxlength'=>'15');echo form_input($data);

echo form_label('Nama*:', 'nama');$data = array('name'=>'nama', 'id'=>'nama', 'maxlength'=>'30');echo form_input($data);...

Page 103: CodeIgniter  jQuery

View: v_form_mahasiswa.php (cont.)...echo form_label('Jenis Kelamin:', 'jk');$data = array('name'=>'jk', 'id'=>'jk', 'value'=>'L', 'checked' => TRUE);echo 'L'.form_radio($data);$data = array('name'=>'jk', 'id'=>'jk', 'value'=>'P', 'checked' => FALSE);echo 'P'.form_radio($data);

echo form_label('Tgl Masuk (DD-MM-YYYY)*:', 'tgl_masuk');$data = array('name'=>'tgl_masuk', 'id'=>'tgl_masuk', 'value'=> date("d-m-Y"));echo form_input($data);

echo form_submit('Submit', 'Submit');

echo form_fieldset_close();echo form_close();?><p><?=isset($status)?$status:''?></p>...

Page 104: CodeIgniter  jQuery

[EDIT] Controller: mahasiswa.php

function entry() { $this->form_validation->set_message('required', 'Maaf, kolom %s tidak boleh dikosongkan.');

$this->form_validation->set_rules('nim', 'NIM', 'required|min_length[8]|max_length[15]|is_unique[tmst_mahasiswa.nim]'); $this->form_validation->set_rules('nama', 'Nama Mahasiswa', 'required|max_length[30]'); $this->form_validation->set_rules('tgl_masuk', 'Tanggal Masuk', 'required');

.... }

Page 105: CodeIgniter  jQuery

[EDIT] Controller: mahasiswa.php

function entry() { ... if ($this->form_validation->run() == FALSE) { $this->load->view('v_form_mahasiswa'); } else { $submitted = $this->input->post("submitted")?$this->input->post("submitted"):""; if ($submitted == 1) { $field['nim'] = $this->input->post("nim"); $field['nama_mahasiswa'] = $this->input->post("nama"); $field['jk'] = $this->input->post("jk"); $field['tanggal_masuk'] = $this->input->post("tgl_masuk"); $field['tanggal_masuk'] = DMY2YMD($field['tanggal_masuk'], '-'); if ($this->M_mahasiswa->insert_data($field)>0) { $data['status'] = 'Sukses'; $this->load->view('v_form_mahasiswa', $data); } else { show_error('Maaf, penambahan data gagal dilakukan.' ); } } }}

http://localhost/ci/index.php/mahasiswa/entry

Page 106: CodeIgniter  jQuery

TEMPLATE PARSER

Page 107: CodeIgniter  jQuery

[BARU] View: v_mahasiswa_template.php

... <title>{judul}</title>...<table> <thead> <tr><td>No</td><td>NIM</td><td>Nama Mahasiswa</td><td>JK</td><td>Tgl Masuk</td></tr> </thead> <tbody> {mhs} <tr> <td>{nomor}</td> <td>{nim}</td> <td>{nama_mahasiswa}</td> <td>{jk}</td> <td>{tanggal_masuk}</td> </tr> {/mhs} </tbody></table>...

Page 108: CodeIgniter  jQuery

[EDIT] Controller: mahasiswa.php

...function templating(){ $q = $this->M_mahasiswa->get_all_data(); if ($q->num_rows()>0) { $m = array(); $idx = 1; foreach ($q->result_array() as $row) { $row['tanggal_masuk'] = YMD2DMY(trimTime($row['tanggal_masuk']), '-'); $m[] = array_merge(array('nomor' => $idx), $row); $idx++; } $data['mhs'] = $m; $data['judul'] = 'Data Mahasiswa'; $this->load->library('parser'); $this->parser->parse('v_mahasiswa_template', $data); } else { show_error('Sorry, no data'); }}

http://localhost/ci/index.php/mahasiswa/templating

Page 109: CodeIgniter  jQuery

Latihan 15 menit

Buat template untuk menampilkan data mahasiswa yang menggunakan paginasi

Page 110: CodeIgniter  jQuery

EDIT DATA

Page 111: CodeIgniter  jQuery

[EDIT] Controller: mahasiswa.php

...

function edit($nim='') { if ($nim=='') { show_error('Data error'); } $data = $this->M_mahasiswa->get_data_by_nim($nim); if ($data != FALSE) { $data[‘is_update’] = 1; $this->load->view('v_form_mahasiswa', $data); } else { show_error('Data tidak ditemukan'); } }

Page 112: CodeIgniter  jQuery

[EDIT] Controller: mahasiswa.php

function entry() {... $this->form_validation->set_rules('nim', 'NIM', 'required|min_length[8]|max_length[15]');... } else { $submitted = $this->input->post("submitted")?$this->input->post("submitted"):""; $is_update = $this->input->post("is_update"); if ($submitted == 1) { $field['nama_mahasiswa'] = $this->input->post("nama"); $field['jk'] = $this->input->post("jk"); $field['tanggal_masuk'] = $this->input->post("tgl_masuk"); $field['tanggal_masuk'] = DMY2YMD($field['tanggal_masuk'], '-');...

Page 113: CodeIgniter  jQuery

[EDIT] Controller: mahasiswa.php

... if ($is_update==0) { $field['nim'] = $this->input->post("nim"); $retval = $this->M_mahasiswa->insert_data($field); } else { $nim = $this->input->post("nim"); $retval = $this->M_mahasiswa->update_data($nim, $field); } if ($retval>0) { $data['status'] = 'Sukses'; $this->load->view('v_form_mahasiswa', $data); } else { show_error('Maaf, user/password Anda tidak cocok' ); } } } }

Page 114: CodeIgniter  jQuery

[EDIT] Model: m_mahasiswa.php

...

function get_data_by_nim($nim) { $this->db->where('nim', $nim); $q = $this->db->get('tmst_mahasiswa'); if ($q->num_rows()>0) { $r = $q->row_array(); $r['tanggal_masuk'] = YMD2DMY(trimTime($r['tanggal_masuk']), '-'); return $r; } else { return FALSE; }}

function update_data($nim, $fields) { $this->db->where('nim', $nim); $this->db->update('tmst_mahasiswa', $fields); return $this->db->affected_rows();}

Page 115: CodeIgniter  jQuery

[EDIT] View: v_form_mahasiswa.php

...<body><?phpecho validation_errors();echo form_open(base_url().'mahasiswa/entry');echo form_fieldset('Data Mahasiswa');echo form_hidden('submitted', '1');echo form_hidden('is_update', (isset($is_update)?$is_update:0)); echo form_label('NIM*:', 'nim');$data = array('name'=>'nim', 'id'=>'nim', 'maxlength'=>'15', 'value' => (isset($nim)?$nim:''));echo form_input($data);

echo form_label('Nama*:', 'nama');$data = array('name'=>'nama', 'id'=>'nama', 'maxlength'=>'30', 'value' => (isset($nama_mahasiswa)?$nama_mahasiswa:''));echo form_input($data);...

Page 116: CodeIgniter  jQuery

[EDIT] View: v_form_mahasiswa.php

...echo form_label('Jenis Kelamin:', 'jk');$jk = isset($jk)?$jk:'L';$data = array('name'=>'jk', 'id'=>'jk', 'value'=>'L', 'checked' => ($jk=='L'?TRUE:FALSE));echo 'L'.form_radio($data);$data = array('name'=>'jk', 'id'=>'jk', 'value'=>'P', 'checked' => ($jk=='P'?TRUE:FALSE));echo 'P'.form_radio($data);

echo form_label('Tgl Masuk (DD-MM-YYYY)*:', 'tgl_masuk');$data = array('name'=>'tgl_masuk', 'id'=>'tgl_masuk', 'value'=>isset($tanggal_masuk)?$tanggal_masuk:date("d-m-Y"));echo form_input($data);

echo form_submit('Submit', 'Submit');

echo form_fieldset_close();echo form_close();?>...

http://localhost/ci/index.php/mahasiswa/edit/20709302

Page 117: CodeIgniter  jQuery

[EDIT] Controller: mahasiswa.php

function data($idx=0){... foreach ($q->result_array() as $row) { $row['tanggal_masuk'] = YMD2DMY(trimTime($row['tanggal_masuk']), '-'); $row['edit'] = anchor(base_url().'mahasiswa/edit/'.$row['nim'], 'edit'); $m[] = array_merge(array('nomor' => $idx), $row); $idx++; }...}

Page 118: CodeIgniter  jQuery

[EDIT] View: v_mahasiswa_page2.php

...<table> <thead> <tr><td>No</td><td>NIM</td><td>Nama Mahasiswa</td><td>JK</td><td>Tgl Masuk</td><td>Aksi</td></tr> </thead> <tbody> {mhs} <tr><td>{nomor}</td><td>{nim}</td><td>{nama_mahasiswa}</td><td>{jk}</td><td>{tanggal_masuk}</td><td>{edit}</td></tr> {/mhs} <tr><td colspan="5"><?=$page?></td></tr> </tbody></table>...

http://localhost/ci/index.php/mahasiswa/data

Page 119: CodeIgniter  jQuery

UPLOAD

Page 120: CodeIgniter  jQuery

Data

Buat folder “uploads” di dalam folder “ci”Download http://167.205.108.215

/ci/berkas.sqlImport ke database “ci_training”

Tabel: berkas Jumlah data: 0 records

Page 121: CodeIgniter  jQuery

[BARU] View: v_upload.php

...<?phpecho form_open_multipart(base_url().'berkas/unggah');?><fieldset ><legend>Unggah Berkas</legend><?=form_hidden('submitted', '1')?> <label for='namafile' >Nama File*:</label><?php$data = array('name'=>'namafile', 'id'=>'namafile');echo form_upload($data);?> <?=form_submit('Submit', 'Unggah')?> </fieldset><?=form_close()?>

<br /><?=isset($status)?$status:''?>...

Page 122: CodeIgniter  jQuery

[BARU] Model: m_berkas.php

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class M_berkas extends CI_Model { function __construct() { parent::__construct(); } function insert_data($fields) { $this->db->insert('berkas', $fields); return $this->db->affected_rows(); } }

/* End of file m_berkas.php */ /* Location: ./application/models/m_berkas.php */

Page 123: CodeIgniter  jQuery

[BARU] Controller: berkas.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Berkas extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('M_berkas'); } function index(){ $this->load->view('v_upload'); } }

/* End of file berkas.php *//* Location: ./application/controllers/berkas.php */

Page 124: CodeIgniter  jQuery

[EDIT] Controller: berkas.php

function unggah() { $submitted = $this->input->post("submitted")?$this->input->post("submitted"):""; if ($submitted == 1) { $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'gif|jpg|png'; $config['max_size'] = '100'; $config['max_width'] = '1024'; $config['max_height'] = '768';

$this->load->library('upload', $config);

.... ....

} else { $this->load->view('v_upload'); }}

Page 125: CodeIgniter  jQuery

[EDIT] Controller: berkas.php

...if ( ! $this->upload->do_upload('namafile')) { $data['status'] = $this->upload->display_errors(); $this->load->view('v_upload', $data);} else { $f = $this->upload->data(); $fields['namafile'] = $f['file_name']; $fields['ukuran'] = $f['file_size']; $fields['ekstensi'] = $f['file_ext']; $fields['tipe_file'] = $f['file_type'];

if ($this->M_berkas->insert_data($fields)>0) { $id_file = $this->db->insert_id(); rename( $config['upload_path'].$f['file_name'], $config['upload_path'].$id_file.$f['file_name']); $data['status'] = 'Upload data sukses.'; } else { $data['status'] = 'Upload data gagal.'; }

$this->load->view('v_upload', $data);}...

http://localhost/ci/index.php/berkas/unggah

Page 126: CodeIgniter  jQuery

Kasus

Kasus gagal: Upload file dengan ekstensi selain gif, jpg dan png Upload file dengan ukuran lebih besar dari 100 Kb Upload file gambar dengan resolusi lebih besar dari

1024x768 pixel

$config['allowed_types'] = 'gif|jpg|png';$config['max_size'] = '100';$config['max_width'] = '1024';$config['max_height'] = '768';

Page 127: CodeIgniter  jQuery

Konfigurasi Upload

Page 128: CodeIgniter  jQuery

Informasi Upload

$f = $this->upload->data();

Page 129: CodeIgniter  jQuery

Referensi

if ($this->M_berkas->insert_data($fields)>0) { $id_file = $this->db->insert_id(); rename( $config['upload_path'].$f['file_name'], $config['upload_path'].$id_file.$f['file_name'] ); $data['status'] = 'Upload data sukses.';} else { $data['status'] = 'Upload data gagal.';}

Jika berkas sukses di unggah dan di masukan datanya, ganti nama berkas tersebut dengan menambahkan ‘id’ didepannya.

Hal ini untuk menghindari ada berkas dengan nama yang sama (padahal isi berbeda) di unggah di kemudian hari.

Page 130: CodeIgniter  jQuery

Latihan 10 menit

Buat fungsi untuk menampilkan data yang sudah di unggah

Gunakan template pada view!

Page 131: CodeIgniter  jQuery

DOWNLOAD HELPER

Page 132: CodeIgniter  jQuery

[EDIT] Controller: berkas.php

function data($idx=0){... foreach ($q->result_array() as $row) { $row['tgl_input'] = YMD2DMY(trimTime($row['tgl_input']), '-'); $row['namafile'] = anchor(base_url().'uploads/'.$row['id'].$row['namafile'], $row['namafile'], array('target' => '_blank')); $row['unduh'] = anchor(base_url().'berkas/unduh/'.$row['id'], 'download'); $m[] = array_merge(array('nomor' => $idx), $row); $idx++; }...

Page 133: CodeIgniter  jQuery

[EDIT] Controller: berkas.php

...function unduh($id) { $namafile = $this->M_berkas->get_namafile_from_id($id); if ($namafile != FALSE) { $this->load->helper('download'); $data = file_get_contents('./uploads/'.$id.$namafile);

force_download($namafile, $data); } }

Page 134: CodeIgniter  jQuery

[EDIT] Model: m_berkas.php

...function get_namafile_from_id($id) { $this->db->select('namafile'); $this->db->where('id', $id); $q = $this->db->get('berkas'); if ($q->num_rows()>0) { $r = $q->result_array(); return $r[0]['namafile']; } else { return FALSE; }}

Page 135: CodeIgniter  jQuery

[EDIT] View: v_berkas.php

...<tr><td>No</td><td>Namafile</td><td>Ukuran</td><td>Tipe</td><td>Tgl Input</td><td>Aksi</td></tr>...<tr><td>{nomor}</td><td>{namafile}</td><td>{ukuran} Kb</td><td>{tipe_file}</td><td>{tgl_input}</td><td>{unduh}</td></tr>...

http://localhost/ci/index.php/berkas/data

Page 136: CodeIgniter  jQuery

SESSION

Page 137: CodeIgniter  jQuery

Session

[EDIT] application/config/autoload.php $autoload['libraries'] = array('database', 'input',

'form_validation‘, ‘session’);[EDIT] application/config/config.php

$config['encryption_key'] = 'BEBASbebasBeBaS';

Page 138: CodeIgniter  jQuery

[EDIT] Controller: login.php

function validasi() { ....

$this->load->model('M_daftar_user'); if ($this->M_daftar_user->get_data($username, $password)>0) { $this->session->set_userdata('userlogin', $username); redirect(base_url().'mahasiswa/data'); } else { show_error('Maaf, user/password Anda tidak cocok' ); } ...}

Page 139: CodeIgniter  jQuery

[EDIT] Controller: mahasiswa.php

public function __construct() { parent::__construct(); if (!$this->session->userdata('userlogin')) { redirect(base_url().'login/validasi'); } $this->load->model('M_mahasiswa');}

http://localhost/ci/index.php/login/validasi

Page 140: CodeIgniter  jQuery

Tentang Session

Sangat mudah menggunakan session di CI $this->session->set_userdata(‘nama_sesi’, ‘nilai_sesi’); $data = $this->session->userdata(‘nama_sesi’);

Isi session adalah sbb:[array]( 'session_id' => random hash, 'ip_address' => 'string - user IP address', 'user_agent' => 'string - user agent data', 'last_activity' => timestamp, 'user_data' => array(???))

‘user_data’ adalah session yang bisa kita tambahkan sesuai kebutuhan Catatan: ukuran maksimal session adalah 4Kb

Page 141: CodeIgniter  jQuery

HEADER-FOOTER

Page 142: CodeIgniter  jQuery

Free Simple Template

[EDIT] application/config/constants.php define('BASE_TEMPLATE', 'http://localhost/ci/');

Download http://167.205.108.215/ci/asubtlegreen.zip

Ekstrak di htdocs /asubtlegreen/

Buat folder “assets” di dalam “ci”Selain “index.html”, copy semua file di folder

“asubtlegreen” ke dalam folder “assets”Buka http://localhost/asubtlegreen/ Buka “index.html” menggunakan Notepad++

Page 143: CodeIgniter  jQuery

[BARU] View: header.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head> <title>Latihan CodeIgniter</title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <link rel="stylesheet" type="text/css" href="<?=BASE_TEMPLATE?>assets/asubtlegreen.css" /></head><body><div id="page"> <div id="header"> <div class="title">Latihan CodeIgniter</div> <div class="subText">A design by Bryant Smith</div> </div>

<?php require_once('menu.php'); ?>

<div id="pageContent">

Page 144: CodeIgniter  jQuery

[BARU] View: menu.php

<div id="bar"> <div class="menuLink"><?=anchor(base_url()."mahasiswa/data", "Home")?></div> <div class="menuLink"><?=anchor(base_url()."mahasiswa/entry", "Tambah")?></div> <div class="menuLink"><?=anchor(base_url()."berkas", "Unggah Berkas")?></div> <div class="menuLink"><?=anchor(base_url()."login/keluar", "Logout")?></div></div>

Page 145: CodeIgniter  jQuery

[BARU] View: footer.php

</div></div> <div id="footer"><a href="http://www.aszx.net">web development</a> by <a href="http://www.bryantsmith.com">bryant smith</a></div> </body></html>

Page 146: CodeIgniter  jQuery

[BARU] View: v_mahasiswa_page2.php

<?php require_once('header.php');?>

<div class="articleTitle">Data Mahasiswa</div><div class="articleContent">

<table>...</table>

</div>

<?php require_once('footer.php');?>

Page 147: CodeIgniter  jQuery

[EDIT] Controller: mahasiswa.php

function data($idx=0){ ... $data['mhs'] = $m; $data['idx'] = $idx; $data['page'] = $this->pagination->create_links(); $this->load->view('v_mahasiswa_page2', $data); } else { show_error('Sorry, no data'); }}

Page 148: CodeIgniter  jQuery

[EDIT] Controller: login.php

function keluar() { $this->session->sess_destroy(); redirect(base_url().'login/validasi');}

http://localhost/ci/index.php/login/validasi

Page 149: CodeIgniter  jQuery

Referensi: Menyertakan File Lain

include (‘file.php’); Jika file itu tidak ada, maka akan muncul pesan warning, tetapi

ekskusi program dibawahnya akan dilanjutkan. require (‘file.php’);

Jika file itu tidak ada, maka akan muncul pesan warning dan tidak akan mengekskusi program dibawahnya.

include_once (‘file.php’); Akan melihat, apakah sudah di-include-kan atau belum, karena

PHP melarang include() file yang sama lebih dari satu kali.require_once (‘file.php’);

Akan melihat, apakah sudah di-require-kan atau belum, karena PHP melarang require() file yang sama lebih dari satu kali.

Page 150: CodeIgniter  jQuery

Latihan 20 menit

Buat juga view dengan format header-footer untuk menu “Tambah” dan “Unggah Berkas”.

Page 151: CodeIgniter  jQuery

MENGHILANGKAN INDEX.PHP

Trik

Page 153: CodeIgniter  jQuery

Menghilangkan index.php (cont.)

Memanfaatkan file .htaccess yang disimpan di direktori utama aplikasi (/xampp/htdocs/ci/)

Isi file .htaccess adalah sbb:Options -Indexes

<IfModule mod_rewrite.c>RewriteEngine OnRewriteCond %{REQUEST_URI} ^system.*RewriteRule ^(.*)$ /index.php/$1 [L]RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^(.*)$ index.php/$1 [L]</IfModule>

Page 154: CodeIgniter  jQuery

Menghilangkan index.php (cont.)

Syarat utamanya adalah mengaktifkan modul mod_rewrite di Apache. Caranya: Edit /xampp/apache/conf/httpd.conf Cari baris berikut:

LoadModule rewrite_module modules/mod_rewrite.so Hapus tanda pagar (#) jika memang ada.

Jika sudah tidak ada tanda pagar, berarti mod_rewrite sudah aktif.

Simpan Restart Apache

[EDIT] application/config/config.php $config['base_url'] = 'http://localhost/ci/';

Page 155: CodeIgniter  jQuery

DYNAMIC BASE_URL

Trik

Page 156: CodeIgniter  jQuery

Dynamic base_url

Latar belakang: $config['base_url'] = 'http://localhost/ci/';

Pertanyaannya: Apa yang harus Anda lakukan jika aplikasi di upload

ke server lain? Atau aplikasi dipindah direktori?

Jawabannya: Anda harus atur ulang base_url di aplikasi

Adakah cara agar tidak perlu repot mengatur ulang base_url tersebut? ???

Page 157: CodeIgniter  jQuery

Dynamic base_url (cont.)

[EDIT] application/config/constants.php

if (isset($_SERVER['HTTP_HOST'])) { $base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ? 'https' : 'http'; $base_url .= '://' . $_SERVER['HTTP_HOST']; $base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);

// Base URI (It's different to base URL!) $base_uri = parse_url($base_url, PHP_URL_PATH); if (substr($base_uri, 0, 1) != '/') $base_uri = '/' . $base_uri; if (substr($base_uri, -1, 1) != '/') $base_uri .= '/';} else { $base_url = 'http://localhost/'; $base_uri = '/';}...

Page 158: CodeIgniter  jQuery

Dynamic base_url (cont.)

[EDIT] application/config/constants.php ...// Define these values to be used later ondefine('BASE_URL', $base_url);define('BASE_URI', $base_uri);define('APPPATH_URI', BASE_URI.APPPATH);

// We dont need these variables any moreunset($base_uri, $base_url);

[EDIT] application/config/config.php $config['base_url'] = BASE_URL;

Page 159: CodeIgniter  jQuery

Sesi 03

Page 160: CodeIgniter  jQuery

jQuery

Page 161: CodeIgniter  jQuery
Page 162: CodeIgniter  jQuery
Page 163: CodeIgniter  jQuery

jQuery

Merupakan pustaka (library) javascript, sama dengan Prototype, YUI, Dojo, mooTools, dsb

Lebih mudah menulis kode jQuery dibanding dengan Javascript murni

Extremely succinctCepat dipelajari

Page 164: CodeIgniter  jQuery

jQuery vs Javascript murni

Menyembunyikan semua div dengan JavaScript

divs = document.getElementByTagName(‘div’);for (i = 0; i < divs.length; i++) { divs[i].style.display = ‘none’;}

Menyembunyikan semua div dengan jQuery

$(“div”).hide();

Page 165: CodeIgniter  jQuery

Referensi Javascript

HTML terikat ke JavascriptFilosofi jQuery:

1. Cari suatu elemen HTML2. Lakukan sesuatu terhadap elemen HTML tersebut

Page 166: CodeIgniter  jQuery

jQuery: #1 Cari suatu elemen HTML

Gunakan selector $() $(“elemen”) $(“#idElemen”) $(“.kelasElemen”)

Page 167: CodeIgniter  jQuery

Contoh Penggunaan Selector

$(“div”) cari semua elemen div

$(“.menuLink”) cari semua elemen dengan kelas “menuLink”

$(“#nama”) cari semua elem dengan id “nama”

$(“li:first”) cari list item (<li></li>) pertama

$(“tr:odd”) cari table rows (<tr></tr>) dengan nomor ganjil

$(“form[id^=step]”) cari semua form yang id-nya diawali dengan kata “step”

$(“a[target=_blank]”) cari semua link yang isi atribut target-nya “_blank”

$(“div, #nama, li:first”) gabungan 3 kriteria

Page 168: CodeIgniter  jQuery

jQuery: #2 Lakukan sesuatu terhadap elemen tsb

$(“elemen”).method(<sesuatu>);

$(“elemen”).method(<sesuatu>).method(); Chain methods!!!

One Method, Many Uses$(...).html();$(...).html(“<p>hello</p>”);$(...).html(function(i){

return “<p>hello “ + i + “</p>”;});

Page 169: CodeIgniter  jQuery

Beberapa Method jQuery

Moving Elements: append(), appendTo(), before(), after(),

Attributes css(), attr(), html(), val(), addClass()

Traversing find(), is(), prevAll(), next(), hasClass()

Events bind(), trigger(), unbind(), live(), click()

Ajax get(), getJSON(), post(), ajax(), load()

Effects show(), fadeOut(), toggle(), animate()

Page 170: CodeIgniter  jQuery

INSTALASI JQUERY

Page 171: CodeIgniter  jQuery

Instalasi jQuery

URL: http://jquery.com/download/Klik kanan link “Download the

uncompressed, development jQuery 1.9.1”, kemudian lakukan Save link as ke direktori \ci\assets\

<script type="text/javascript" src=“http://localhost/ci/assets/jquery-1.9.1.js"></script>

Page 172: CodeIgniter  jQuery

DOCUMENT READY

Page 173: CodeIgniter  jQuery

Memulai jQuery

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

atau

<script type="text/javascript">$(function() { //kode javascript Anda});</script>

Page 174: CodeIgniter  jQuery

CODING JQUERY

Page 175: CodeIgniter  jQuery

[EDIT] View: v_login3.php

...<script type="text/javascript" src=“http://localhost/ci/assets/jquery-1.9.1.js"></script><script type="text/javascript">$(function() { alert(“DOM ready”); $("label[for=username]").css("color", "red"); $("label[for=password]").css("color", "#00FF00");}); </script>

</body></html>

http://localhost/ci/index.php/login/validasi

Page 176: CodeIgniter  jQuery

Referensi

DOM (Document Object Model) : suatu objek model standar yang dikeluarkan W3C untuk mengakses dan memanipulasi HTML.

Page 177: CodeIgniter  jQuery

EVENTS

Page 178: CodeIgniter  jQuery

[EDIT] Controller: welcome.php

...

function klik() { $this->load->view('v_jquery');}

Page 179: CodeIgniter  jQuery

[BARU] View: v_jquery.php

...<body> <?php $data = array('name'=>'btn_1', 'id'=>'btn_1'); echo form_button($data, ' Tes 1 '); ?> <script type="text/javascript" src="http://localhost/ci/assets/jquery-1.9.1.js"></script><script type="text/javascript"> $(function(){ $("button").click(function(){ var teks = $(this).text(); alert('Tombol "'+teks+'" diklik.'); }); });</script>

</body></html>

http://localhost/ci/index.php/welcome/klik

Page 180: CodeIgniter  jQuery

[EDIT] View: v_jquery.php

...<body> <?php $data = array('name'=>'btn_1', 'id'=>'btn_1'); echo form_button($data, ' Tes 1 ');

$data = array('name'=>'btn_2', 'id'=>'btn_2'); echo form_button($data, ' Tes 2 '); ?>

http://localhost/ci/index.php/welcome/klik

Page 181: CodeIgniter  jQuery

[EDIT] View: v_jquery.php

...<script type="text/javascript"> $(function(){ $(“#btn_1").click(function(){ var teks = $(this).text(); alert('Tombol "'+teks+'" diklik.'); }); });</script>

http://localhost/ci/index.php/welcome/klik

Page 182: CodeIgniter  jQuery

Daftar Event

Page 183: CodeIgniter  jQuery

AJAX

Page 184: CodeIgniter  jQuery

AJAX

AJAX = Asynchronous JavaScript and XML.

AJAX bukanlah bahasa pemrograman baru, tetapi merupakan teknik baru dalam menggunakan standar yang ada.

AJAX merupakan seni dalam pertukaran data dengan server, dan mengubah beberapa bagian pada suatu halaman web, tanpa me-reload keseluruhan isi web.

Page 185: CodeIgniter  jQuery

AJAX (cont.)

jQuery $.ajax()

$.get() $.getJSON() $.post() $.load()

Page 186: CodeIgniter  jQuery

[EDIT] View: v_jquery.php

...<body> <?php $data = array('name'=>'btn_1', 'id'=>'btn_1'); echo form_button($data, ' Tes 1 ');

$data = array('name'=>'btn_2', 'id'=>'btn_2'); echo form_button($data, ' Tes 2 '); ?>

<div id="myDiv"><h2>Teks ini akan berubah jika tombol di klik.</h2></div> <?php $data = array('name'=>'btn_ajax', 'id'=>'btn_ajax'); echo form_button($data, ' Ubah Teks '); ?>

...

Page 187: CodeIgniter  jQuery

[EDIT] View: v_jquery.php

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

... $("#btn_ajax").click(function(){ $.ajax({ type: "POST", url: "<?=base_url()?>welcome/get_info", data: "param=1", success: function(msg){ $("#myDiv").html(msg); } }); }); });</script>

...

Page 188: CodeIgniter  jQuery

[EDIT] Controller: welcome.php

...

function get_info() { echo "<b>BERUBAH!!!</b> 1...2...3...";}

http://localhost/ci/index.php/welcome/klik

Page 189: CodeIgniter  jQuery

[EDIT] View: v_jquery.php

...<div id="myDiv"><h2>Teks ini akan berubah jika tombol di klik.</h2></div> <?php $data = array('name'=>'btn_ajax', 'id'=>'btn_ajax'); echo form_button($data, ' Ubah Teks '); ?>

<h2>Get Info Mahasiswa</h2> <?php $data = array('name'=>'nim', 'id'=>'nim'); echo form_input($data, ''); $data = array('name'=>'btn_getInfo', 'id'=>'btn_getInfo'); echo form_button($data, ' Get Info '); ?> <div id="divMhs” style="background-color: #af44bb;"></div>...

Page 190: CodeIgniter  jQuery

[EDIT] Model: m_mahasiswa.php

...

function get_data_by_nim($nim) { $this->db->where('nim', $nim); $q = $this->db->get('tmst_mahasiswa'); if ($q->num_rows()>0) { $r = $q->row_array(); $r['tanggal_masuk'] = YMD2DMY(trimTime($r['tanggal_masuk']), '-'); return $r; } else { return FALSE; }}

Page 191: CodeIgniter  jQuery

[EDIT] View: v_jquery.php...<script type="text/javascript"> $(function(){

... $("#divMhs").hide(); $("#btn_getInfo").click(function(){ var nim = $("#nim").val(); $.post("<?=base_url()?>welcome/get_info_mhs", {nim: nim}, function(msg){ $("#divMhs").hide(); if (msg!='') { $("#divMhs").html('NIM '+nim+' adalah milik '+msg); } else { $("#divMhs").html('NIM '+nim+' tidak terdaftar.'); } $("#divMhs").slideDown("slow"); } ); }); });</script>

Page 192: CodeIgniter  jQuery

[EDIT] Controller: welcome.php

...

function get_info_mhs() { $nim = $this->input->post('nim')?$this->input->post('nim'):''; if ($nim!='') { $this->load->model('M_mahasiswa'); $data = M_mahasiswa::get_data_by_nim($nim); if ($data != FALSE) { echo $data['nama_mahasiswa']; } else { echo ''; } }}

http://localhost/ci/index.php/welcome/klik

Page 193: CodeIgniter  jQuery

[EDIT] View: v_jquery.php

...<h2>Get Info Mahasiswa</h2>

<?php$data = array('name'=>'nim', 'id'=>'nim');echo form_input($data, '');$data = array('name'=>'btn_getInfo', 'id'=>'btn_getInfo');echo form_button($data, ' Get Info ');?><div id="divMhs" style="background-color: #af44bb;"></div>

<h2>Cari Mahasiswa</h2><?php$data = array('name'=>'nama', 'id'=>'nama');echo form_input($data, '');?><div id="divNamaMhs"></div>

Page 194: CodeIgniter  jQuery

[EDIT] View: v_jquery.php

... $("#nama").keyup(function(e){ var nama = $(this).val(); $.ajax({ type: "POST", url: "<?=base_url()?>welcome/get_nama_mhs", data: "nama="+nama, success: function(msg){ $("#divNamaMhs").html(msg); } }); });

...

Page 195: CodeIgniter  jQuery

[EDIT] Model: m_mahasiswa.php

...

function get_nama($nama) { $this->db->select('nama_mahasiswa'); $this->db->order_by('nama_mahasiswa', 'asc'); $this->db->like('nama_mahasiswa', $nama, 'after'); return $this->db->get('tmst_mahasiswa');}

Page 196: CodeIgniter  jQuery

[EDIT] Controller: welcome.php

...

function get_nama_mhs() { $nama = $this->input->post('nama')?$this->input->post('nama'):''; if ($nama!='') { $this->load->model('M_mahasiswa'); $q = M_mahasiswa::get_nama($nama); $retval = ''; foreach ($q->result_array() as $r) { $retval .= $r['nama_mahasiswa'] . '<br />'; } echo $retval; }}

http://localhost/ci/index.php/welcome/klik

Page 197: CodeIgniter  jQuery

EFFECT

Page 198: CodeIgniter  jQuery

Jenis Efek

Hide and Show .hide() .show()

Fade In and Out .fadeIn() .fadeOut() .fadeTo()

Slide Up and Down .slideUp() .slideDown() .slideToggle()

Page 199: CodeIgniter  jQuery

[BARU] View: v_slide.php

<!DOCTYPE html><html><head> <style type="text/css"> #panel, #flip { padding:5px; text-align:center; background-color:#e5eecc; border:solid 1px #c3c3c3;}

#panel { padding:50px; display:none;}</style></head><body>...

Page 200: CodeIgniter  jQuery

[BARU] View: v_slide.php

...<div id="flip">Klik panel ini untuk buka/tutup</div><div id="panel">Hello!<br /><br />Ini adalah demo menggunakan efek slideToggle().</div>

<script type="text/javascript" src="http://localhost/ci/assets/jquery-1.9.1.js"></script><script type="text/javascript"> $(document).ready(function(){ $("#flip").click(function(){ $("#panel").slideToggle("slow"); });});</script>

</body></html>

Page 201: CodeIgniter  jQuery

[EDIT] Controller: welcome.php

...

function slide() { $this->load->view('v_slide');}

http://localhost/ci/index.php/welcome/slide

Page 202: CodeIgniter  jQuery

Referensi