Instantly share code, notes, and snippets.

Embed
What would you like to do?
<!DOCTYPE html>
<html lang="id" dir="ltr">
<head>
<meta charset="utf-8">
<title>AJAX Submit Form</title>
</head>
<body>
<form action="kirim-proses.php" method="post" id="formulir">
<input type="text" name="nama" placeholder="Nama Lengkap"><br>
<input type="email" name="email" placeholder="Email"><br>
<input type="number" name="usia" placeholder="Usia"><br>
<button type="submit">Kirim</button>
</form>
</body>
</html>
$(document).ready(function(){
// jika terjadi event submit pada form
$('#formulir').submit(function(e) {
// mencegah agar halaman tidak pindah halaman / refresh
e.preventDefault()
// ambil data
var data = $(this).serialize()
// ambil method dari method di form
var method = $(this).attr('method')
// ke mana data akan dikirim
// diambil dari action di form
var action = $(this).attr('action')
// memulai kirim ajax
$.ajax({
url: action,
data: data,
method: method,
beforeSend: function() {
// lakukan sesuatu sebelum data dikirim
// misalkan memulai loading
},
success: function(data) {
// lakukan sesuatu jika data sudah terkirim
}
})
})
})
<!DOCTYPE html>
<html lang="id" dir="ltr">
<head>
<meta charset="utf-8">
<title>AJAX Submit Form</title>
</head>
<body>
<form action="kirim-proses.php" method="post" id="formulir">
<input type="text" name="nama" placeholder="Nama Lengkap"><br>
<input type="email" name="email" placeholder="Email"><br>
<input type="number" name="usia" placeholder="Usia"><br>
<button type="submit">Kirim</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// jika terjadi event submit pada form
$('#formulir').submit(function(e) {
// mencegah agar halaman tidak pindah halaman / refresh
e.preventDefault()
// ambil data
var data = $(this).serialize()
// ambil method dari method di form
var method = $(this).attr('method')
// ke mana data akan dikirim
// diambil dari action di form
var action = $(this).attr('action')
// memulai kirim ajax
$.ajax({
url: action,
data: data,
method: method,
beforeSend: function() {
// lakukan sesuatu sebelum data dikirim
// misalkan memulai loading
},
success: function(data) {
// lakukan sesuatu jika data sudah terkirim
}
})
})
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment