Contoh simple ajax di CodeIgniter

Kali ini saya akan sedikit sharing ttg ajax dg menggunakan library jQuery di CodeIgniter. CodeIgniter adalah framework PHP yg cukup populer. Beberapa jenis dr framework php yg lainnya misalnya cake PHP, zend, dll.

Seperti kebanyakan framework lainnya, CodeIgniter menggunakan metode MVC dalam gaya pemrogramanannya. Untuk lebih mengenal apa itu MVC bisa dengan googling.

Pertama buat database, lalu buat table mhs dengan fieldnya nama dan npm.

Lalu buat file di view dg nama latihan.php

<script>

insert_data(){
var nama = $("#nama").val();
var npm = $("#npm").val();
$.ajax(function(){
type: 'POST',
url: '<?php echo site_url(); ?>/latihan/input_npm',
data: {nama: nama, npm:npm}
success: function(msg){
alert(msg);
}
});

}

</script>

<table>
<tbody>
<tr><td>Nama</td><td>:</td><td><input type="text" name="nama" id="nama" size="25" /></td></tr>
<tr><td>NPM</td><td>:</td><td><input type="text" name="npm" id="npm" size="25" /></td></tr>
</tbody>
</table>
<input type="button" value="Insert" onclick="insert_data()" />



lalu buat controller dengan nama latihan.php, dan buat function di controller tsb dengan nama input_npm()

function input_npm(){
$nama = $this->input->post('nama');
$npm = $this->input->post('npm');
$q = $this->M_latihan->proses_input($nama, $npm);
if ($q == true){
echo "Insert Berhasil";
}else{
echo "Insert Gagal";
}
}

Terakhir buat file di models dg nama m_latihan, dan buat function di models dg dg nama proses_input()

function proses_input($nama, $npm){
$data = array(
'nama' => $nama,
'npm' => $npm
);
$q = $this->db->insert('mhs', $data);
return $q;
}

Semoga bermanfaat.

Advertisement
This entry was posted in CodeIgniter, jQuery and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s