You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Bootstrap Modal提交表单后显示注册成功提示?

Let's fix this step by step—you want to submit the form inside a Bootstrap Modal, show the success/error message in the same modal, and actually save the data to the database. Here's what's wrong with your current code and how to fix it:

Key Issues in Your Current Code

  1. Missing Fields in HTML: Your PHP references fields like alamat, telepon, and asalSekolah that aren't present in your form—this causes Undefined index errors and fails the database insert.
  2. Modal Closes On Submit: Your JS closes the modal immediately after submission, so you can't see any success/error message inside it.
  3. SQL Injection Risk: You're directly inserting user input into your SQL query, which is a security hazard.
  4. No Error Handling: There's no fallback if the AJAX request fails.

Fixed Complete Code

1. Updated HTML (Modal with Result Area)

We'll add a hidden result section to display messages without closing the modal, and include the missing fields your PHP expects:

<div class="modal fade" id="daftarModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h3>Daftar</h3>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body">
        <!-- Registration Form -->
        <form method="post" action="#" id="daftarForm">
          <div class="form-group row">
            <label for="forEmail" class="col-sm-2">Email</label>
            <div class="col-sm-10">
              <input type="email" class="form-control" id="forEmail" name="email" required>
            </div>
          </div>
          <div class="form-group row">
            <label for="forNama" class="col-sm-2">Nama</label>
            <div class="col-sm-10">
              <input type="text" class="form-control" id="forNama" name="nama" required>
            </div>
          </div>
          <div class="form-group row">
            <label class="col-sm-2">Jenis Kelamin</label>
            <div class="col-sm-10">
              <div class="radioBtn">
                <div class="form-check form-check-inline">
                  <input type="radio" class="form-check-input" name="j_kel" id="forLaki-Laki" value="Laki-Laki" required>
                  <label for="forLaki-Laki" class="form-check-label"> Laki-Laki </label>
                </div>
                <div class="form-check form-check-inline">
                  <input type="radio" class="form-check-input" name="j_kel" id="forPerempuan" value="Perempuan" required>
                  <label for="forPerempuan" class="form-check-label"> Perempuan </label>
                </div>
              </div>
            </div>
          </div>
          <div class="form-group row">
            <label class="col-sm-2">Paket</label>
            <div class="col-sm-10">
              <div class="checkBtn">
                <div class="form-check form-check-inline">
                  <input type="checkbox" class="form-check-input" name="paket[]" id="forA" value="A">
                  <label for="forA" class="form-check-label"> Paket A </label>
                </div>
                <div class="form-check form-check-inline">
                  <input type="checkbox" class="form-check-input" name="paket[]" id="forB" value="B">
                  <label for="forB" class="form-check-label"> Paket B </label>
                </div>
                <div class="form-check form-check-inline">
                  <input type="checkbox" class="form-check-input" name="paket[]" id="forC" value="C">
                  <label for="forC" class="form-check-label"> Paket C </label>
                </div>
                <div class="form-check form-check-inline">
                  <input type="checkbox" class="form-check-input" name="paket[]" id="forD" value="D">
                  <label for="forD" class="form-check-label"> Paket Daaa </label>
                </div>
              </div>
            </div>
          </div>
          <!-- Missing fields from your PHP -->
          <div class="form-group row">
            <label for="forAlamat" class="col-sm-2">Alamat</label>
            <div class="col-sm-10">
              <textarea class="form-control" id="forAlamat" name="alamat"></textarea>
            </div>
          </div>
          <div class="form-group row">
            <label for="forTelepon" class="col-sm-2">Telepon</label>
            <div class="col-sm-10">
              <input type="tel" class="form-control" id="forTelepon" name="telepon">
            </div>
          </div>
          <div class="form-group row">
            <label for="forAsalSekolah" class="col-sm-2">Asal Sekolah</label>
            <div class="col-sm-10">
              <input type="text" class="form-control" id="forAsalSekolah" name="asalSekolah">
            </div>
          </div>
          <div class="form-group row">
            <div class="col-sm-2"></div>
            <div class="col-sm-10">
              <input type="submit" name="submit" class="btn btn-success" value="Daftar">
            </div>
          </div>
        </form>
        <!-- Hidden Result Area -->
        <div id="daftarResult" class="d-none text-center py-4">
          <h4 id="resultMessage"></h4>
          <button type="button" class="btn btn-primary mt-3" onclick="resetDaftarModal()">Kembali ke Form</button>
        </div>
      </div>
    </div>
  </div>
</div>

2. Updated JavaScript (Show Message in Modal)

We'll stop closing the modal, switch between form and result views, and add error handling:

$(document).ready(function(){
  $('#daftarForm').on('submit', function(event) {
    event.preventDefault();
    // Disable submit button to prevent duplicate submissions
    $('input[type="submit"]').prop('disabled', true);
    
    $.ajax({
      url: "daftarForm.php",
      method: "POST",
      data: $(this).serialize(),
      success: function(data) {
        // Hide form, show result
        $('#daftarForm').addClass('d-none');
        $('#daftarResult').removeClass('d-none');
        $('#resultMessage').html(data);
        $('#daftarForm')[0].reset();
      },
      error: function() {
        $('#resultMessage').html('<span class="text-danger">Terjadi kesalahan, silakan coba lagi.</span>');
        $('#daftarForm').addClass('d-none');
        $('#daftarResult').removeClass('d-none');
      },
      complete: function() {
        // Re-enable submit button
        $('input[type="submit"]').prop('disabled', false);
      }
    });
  });
});

// Reset modal back to form view
function resetDaftarModal() {
  $('#daftarResult').addClass('d-none');
  $('#daftarForm').removeClass('d-none');
}

3. Fixed PHP (Secure Database Insert)

We'll use prepared statements to avoid SQL injection, handle missing fields, and return clear messages:

<?php
// Replace with your database credentials
$koneksi = mysqli_connect("localhost", "your_username", "your_password", "your_database");
if (!$koneksi) {
  die("Koneksi gagal: " . mysqli_connect_error());
}

$output = '';
if (!empty($_POST)) {
  // Get form data (set defaults for optional fields)
  $email = isset($_POST["email"]) ? $_POST["email"] : '';
  $nama = isset($_POST["nama"]) ? $_POST["nama"] : '';
  $j_kel = isset($_POST["j_kel"]) ? $_POST["j_kel"] : '';
  $alamat = isset($_POST["alamat"]) ? $_POST["alamat"] : '';
  $telepon = isset($_POST["telepon"]) ? $_POST["telepon"] : '';
  $asalSekolah = isset($_POST["asalSekolah"]) ? $_POST["asalSekolah"] : '';
  $paketArray = isset($_POST['paket']) ? implode(',', $_POST['paket']) : '';

  // Use prepared statement to prevent SQL injection
  $sql = "INSERT INTO `peserta` (`email`, `nama`, `j_kel`, `alamat`, `no_hp`, `asal_sekolah`, `paket`) VALUES (?, ?, ?, ?, ?, ?, ?)";
  $stmt = mysqli_prepare($koneksi, $sql);
  mysqli_stmt_bind_param($stmt, "sssssss", $email, $nama, $j_kel, $alamat, $telepon, $asalSekolah, $paketArray);

  if (mysqli_stmt_execute($stmt)) {
    $output = '<span class="text-success">Pendaftaran Berhasil!</span>';
  } else {
    $output = '<span class="text-danger">Pendaftaran Gagal: ' . mysqli_error($koneksi) . '</span>';
  }
  mysqli_stmt_close($stmt);
}
mysqli_close($koneksi);
echo $output;
?>

Key Improvements Explained

  • Modal Message Display: We use Bootstrap's d-none class to toggle between the form and result section instead of closing the modal.
  • Secure Database Insert: Prepared statements eliminate SQL injection risks and handle user input safely.
  • Error Handling: The JS catches AJAX failures, and PHP returns detailed error messages for debugging.
  • Prevent Duplicate Submissions: The submit button is disabled during the request to stop users from clicking multiple times.

内容的提问来源于stack exchange,提问作者Sabri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:10:51