Bài 1: Giới thiệu về Trình quản lý quảng cáo

BÀI GIẢNG: jQuery Form Data

1. Giới thiệu về jQuery Form Data

jQuery Form Data giúp thu thập, xử lý dữ liệu biểu mẫu HTML và gửi đi. Nó hỗ trợ:

  • Lấy giá trị từ form
  • Cập nhật giá trị vào form
  • Kiểm tra và xác thực dữ liệu đầu vào
  • Gửi dữ liệu qua AJAX

Sử dụng jQuery giúp thao tác với biểu mẫu nhanh chóng, hiệu quả hơn và tăng trải nghiệm người dùng.


2. Lấy giá trị từ form với .val()

Cú pháp

$(selector).val();

Ví dụ 1: Lấy dữ liệu từ ô input

<input type="text" id="username" placeholder="Nhập tên">
<button id="getName">Lấy tên</button>
<p id="result"></p>
<script>
    $("#getName").click(function() {
        var name = $("#username").val();
        $("#result").text("Tên của bạn: " + name);
    });
</script>

3. Cập nhật giá trị form với .val("giá trị mới")

Cú pháp

$(selector).val("newValue");

Ví dụ 2: Thiết lập giá trị cho ô nhập

<input type="text" id="username" placeholder="Nhập tên">
<button id="setName">Đặt tên mặc định</button>
<script>
    $("#setName").click(function() {
        $("#username").val("Nguyễn Văn A");
    });
</script>

4. Kiểm tra và xác thực dữ liệu đầu vào

Ví dụ 3: Kiểm tra ô input có giá trị hay không

<input type="text" id="email" placeholder="Nhập email">
<button id="checkEmail">Kiểm tra</button>
<p id="emailStatus"></p>
<script>
    $("#checkEmail").click(function() {
        var email = $("#email").val();
        if (email === "") {
            $("#emailStatus").text("Vui lòng nhập email!").css("color", "red");
        } else {
            $("#emailStatus").text("Email hợp lệ").css("color", "green");
        }
    });
</script>

5. Gửi dữ liệu form bằng AJAX với .submit()

Hàm $.ajax() trong jQuery giúp gửi và nhận dữ liệu từ server mà không cần tải lại trang. Dưới đây là giải thích về các tham số quan trọng:

Cú pháp cơ bản

$.ajax({
    url: "server.php",    // URL xử lý dữ liệu
    method: "POST",       // Phương thức gửi (GET, POST, PUT, DELETE)
    data: { key: "value" },  // Dữ liệu gửi đi
    success: function(response) {
        console.log("Thành công:", response);
    },
    error: function(xhr, status, error) {
        console.log("Lỗi:", error);
    }
});

Giải thích các tham số

  • url: Đường dẫn đến file server xử lý dữ liệu.
  • method (hoặc type): Loại yêu cầu HTTP (mặc định là GET).
  • data: Dữ liệu gửi đi, có thể là object { key: value } hoặc FormData.
  • success(response): Hàm callback thực thi khi yêu cầu thành công, nhận phản hồi từ server.
  • error(xhr, status, error): Hàm callback thực thi khi có lỗi.

Ví dụ 4: Gửi dữ liệu form không cần tải lại trang

<form id="loginForm">
    <input type="text" id="username" placeholder="Tên đăng nhập">
    <input type="password" id="password" placeholder="Mật khẩu">
    <button type="submit">Đăng nhập</button>
</form>
<p id="loginStatus"></p>
<script>
    $("#loginForm").submit(function(event) {
        event.preventDefault();
        var username = $("#username").val();
        var password = $("#password").val();
        
        $.ajax({
            url: "login.php",
            method: "POST",
            data: { username: username, password: password },
            success: function(response) {
                $("#loginStatus").text("Đăng nhập thành công!").css("color", "green");
            },
            error: function() {
                $("#loginStatus").text("Đăng nhập thất bại!").css("color", "red");
            }
        });
    });
</script>

6. Kết luận

  • .val() giúp lấy và đặt giá trị của các ô nhập.
  • Có thể kiểm tra dữ liệu trước khi gửi đi.
  • Sử dụng AJAX để gửi form mà không cần tải lại trang.
  • jQuery giúp thao tác với form dễ dàng và nhanh chóng hơn.

Bài tập: Xử lý Form Đăng Ký với jQuery

Yêu cầu:

Tạo một form đăng ký gồm các trường: Họ và Tên, Email, Mật khẩu, Xác nhận mật khẩu. Khi người dùng nhấn nút "Đăng Ký", thực hiện các bước sau:

  1. Lấy dữ liệu (.val()) từ các ô nhập.
  2. Kiểm tra dữ liệu đầu vào:
    • Tất cả các ô nhập không được để trống.
    • Email phải có định dạng hợp lệ.
    • Mật khẩu và Xác nhận mật khẩu phải khớp nhau.
  3. Hiển thị thông báo lỗi nếu có trường nhập sai.
  4. Nếu hợp lệ, đặt lại form (.val("")) và hiển thị thông báo "Đăng ký thành công!". 

Mã HTML + jQuery Mẫu

Bạn hãy sao chép và chạy đoạn mã sau để thực hành:

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Đăng Ký</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        body { font-family: Arial, sans-serif; max-width: 400px; margin: 50px auto; }
        input { width: 100%; padding: 8px; margin: 5px 0; }
        button { width: 100%; padding: 10px; background: blue; color: white; border: none; }
        .error { color: red; font-size: 14px; }
        .success { color: green; font-size: 14px; }
    </style>
</head>
<body>

    <h2>Form Đăng Ký</h2>
    <form id="registerForm">
        <input type="text" id="fullname" placeholder="Họ và Tên">
        <p class="error" id="errorName"></p>

        <input type="email" id="email" placeholder="Email">
        <p class="error" id="errorEmail"></p>

        <input type="password" id="password" placeholder="Mật khẩu">
        <p class="error" id="errorPassword"></p>

        <input type="password" id="confirmPassword" placeholder="Xác nhận mật khẩu">
        <p class="error" id="errorConfirmPassword"></p>

        <button type="submit">Đăng Ký</button>
    </form>

    <p id="message"></p>

    <script>
         //Code js vào đây
    </script>

</body>
</html>

📌 Nộp bài: File html + js hoặc biên soạn trực tiếp tại phần trả lời