Submit form với ajax trong php
Lượt xem: 1531
1. Thêm nội dung HTML
1.1 Trước tiên các bạn tạo Modal với nội dung như sau:
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<form method="POST">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle"> Add new Customer</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true"> ×</span>
</button>
</div>
<div class="modal-body">
<div class="message"> </div>
<div id="email-group" class="form-group">
<label for="txtEmail"> Email address</label>
<input type="email" class="form-control" id="txtEmail" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted"> We'll never share your email with anyone else.</small>
</div>
<div id="password-group" class="form-group">
<label for="txtPassword"> Password</label>
<input type="password" class="form-control" id="txtPassword" placeholder="Password">
</div>
<div class="form-group">
<label for="txtPhone"> Phone</label>
<input type="text" class="form-control" id="txtPhone" placeholder="Enter Your Phone">
</div>
<div class="form-group">
<label for="txtName"> Name</label>
<input type="text" class="form-control" id="txtName" placeholder="Enter Your Phone">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal"> Close</button>
<button type="submit" class="btn btn-primary"> Save changes</button>
</div>
</form>
</div>
</div>
</div>
Các bạn tham khảo thêm phần load modal
1.2 Các bạn bổ sung cho mình button show modal (hay chính là button add customer) như sau:
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">
Add Customer
</button>
2. Thêm file customerprocessing.php trong folder ajax
Bổ sung file customerprocessing để đón dữ liệu từ ajax và lưu xuống database
<?php
header('Content-Type: text/html; charset=utf-8');
include "../class.database.php";
$errors = [];
$data = [];
if (empty($_POST['email'])) {
$errors['email'] = 'Email is required.';
}
if (empty($_POST['password'])) {
$errors['password'] = 'Password is required.';
}
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$customer_name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$password = $_POST['password'];
if(!empty($email) && !empty($password)) {
// check email da ton tai
$result = mysqli_query($conn, "SELECT * from Customers where email='$email '");
$row = mysqli_fetch_assoc($result);
if($row) {
$data['message'] = 'Email da ton tai!';
$data['success'] = false;
$data['errors'] = $errors;
}else {
/* Prepare an insert statement */
$stmt = mysqli_prepare($conn, "INSERT INTO Customers (CustomerName, email, password, Phone) VALUES (?,?,?,?)");
/* Bind variables to parameters */
mysqli_stmt_bind_param($stmt,'ssss', $customer_name, $email, $password, $phone);
/* Execute the statement */
mysqli_stmt_execute($stmt);
/// printf("%d row inserted.\n", mysqli_stmt_affected_rows($stmt));
$data['success'] = true;
$data['message'] = 'Success!';
}
}
}
echo json_encode($data);
3. Bổ sung file customer.js trong folder js
Thêm file customer.js với nội dung sau:
$(document).ready(function () {
$("form").submit(function (event) {
$(".form-group").removeClass("has-error");
$(".help-block").remove();
var formData = {
password: $("#txtEmail").val(),
email: $("#txtEmail").val(),
phone: $("#txtPhone").val(),
name: $("#txtName").val(),
};
$.ajax({
type: "POST",
url: "/loginphp/ajax/customerprocessing.php",
data: formData,
dataType: "json",
encode: true,
}).done(function (data) {
console.log(data);
if (!data.success) {
if (data.errors.email) {
$("#email-group").addClass("has-error");
$("#email-group").append(
'<div class="help-block">' + data.errors.email + "</div>"
);
}
if (data.errors.name) {
$("#password-group").addClass("has-error");
$("#password-group").append(
'<div class="help-block">' + data.errors.name + "</div>"
);
}
}
$(".message").html(
'<div class="alert alert-success">' + data.message + "</div>"
);
});
event.preventDefault();
});
});
4. Cuối cùng việc hết sức quan trọng là include file customer.js vào file customer.php
<script src="js/customer.js"></script>
Lưu ý là file customer.js phải đặt sau phần include thư viện jquery nhé các bạn.
Video thao tác cùng dandev