Post data dengan ajax di PHP

Gaenak badan euy, bawaannya malah makin males aja nih mau ngapa-ngapain alesan. Kerjaan di-skip buat besok aja ahh 😀 hehehe. Tapi daripada bengong bingung ngerjain apaan mending nulis blog aja sapa tau jadi terkenal nih blog saya 😀 .

Iseng-iseng kita coba bikin contoh sederhana post data pake ajax yuk. Sok diliyat penampakannya :
1. Buat file index.php

<!Doctype HTML>
<html>
<head>
	<title>
		Post Data Using Ajax
	</title>
	<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>

	<form id="formAdd">
		<label>Nama Depan</label>
		<input name="nama[]">
		<label>Nama Belakang</label>
		<input name="nama[]">
		<label>Alamat</label>
		<input name="alamat">
		<button type="button" id="btnPost">Kirim</button>
	</form>
	<br>
	<span id="pesan"></span>
<script type="text/javascript">
$(function(){
	$('#btnPost').click(function(){
	
		$.ajax({
			url: 'post.php',
			type: 'POST',
			data: $('#formAdd').serialize(),
			success: function(res){
				var json = JSON.parse(res);
				var l = json.data.nama.length;// count input array name
				var isi = '';
				for(var i=0;i<l;i++){ // loop array
					isi += json.data.nama[i] + " ";
// 					console.log(json.data.nama[i] + " - " + json.data.alamat);
				}
				
				$('#pesan').html("<strong>" + isi + "</strong>, benarkah anda tinggal di <strong>" + json.data.alamat + "</strong> ?");
			}
		})
	})
})
</script>
</body>
<html>

terserah mau disimpan dimana aja tuh skrip, yang penting bisa dipake aja :p

2. Buat file post.php

<?php
$res['data'] = $_POST;
echo json_encode($res);

sip dah jadi :D, sok dicoba.
Keren dah insha allah hehehee , tidur ahh…

This entry was posted in php and tagged , , , , . Bookmark the permalink.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.