Danh Mục Bài Viết
Ok, tiếp tục thôi nào! Ở Topic 5 chúng ta đã thực hiện thành công thêm ảnh vào database và show ra giao diện rồi đúng không? nhưng mình còn trăn trở một điều. Mình ko muốn phải đến lúc vào product_list.php mới xem được ảnh. Mình muốn được thấy ảnh ngay lúc upload luôn. Đấy đấy! hình bóng Ajax lại xuất hiện rồi đấy. Let’s Go thôi nào:
Đầu tiên các bạn qua bên file product_list.php
lấy cái link của Ajax bê qua product_add.php
nhé.
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<title>Add Product</title>
</head>
Nhớ là mình đã tạo TOPIC6 nhé!
Nếu mình đi theo hướng này thì cái form của mình sẽ không cần có thêm thuộc tính enctype="multipart/form-data
" nữa.
Tuy nhiên mình sẽ thêm vào nó một thẻ div để hiện ảnh sau khi upload và một thẻ input type = “hiden”
để lưu cái đường dẫn của file ảnh.
Bây giờ mình sẽ comment toàn bộ form cũ và tạo một form mới đồng thời thêm đoạn code Ajax/Jquery sau vào file product_add.php
<body>
<!-- <form action="" method="post" enctype="multipart/form-data">
<input type="text" placeholder="product_name" name="product_name"> <br>
<input type="text" placeholder="product_price" name="product_price"> <br>
<input type="file" name="file" id="upload_file"> <br>
<button style="cursor: pointer;" type="submit">Add</button>
</form> -->
<form method="post" action="">
<input type="text" placeholder="product_name" name="product_name"> <br>
<input type="text" placeholder="product_price" name="product_price"> <br>
<input type="file" name="file" id="upload_file"> <br>
<input type="hidden" value="" id="product-image" name="product_image">
`<div id="product-img">
</div>
<button style="cursor: pointer;" type="submit">Add</button>
</form>
<script>
$('#upload_file').on('change',()=>{
$file = $('#upload_file');
var formdata = new FormData();
formdata.append('file',$file[0].files[0])
$.ajax({
url: 'product_ajax.php',
data:formdata,
dataType: 'JSON',
method: 'POST',
processData: false,
contentType:false,
success: function(res) {
if(res.success = true) {
$("#product-img").html('<img src="'+res.fileurl+'" style="width: 100px; height: 100px" alt=""> <br>')
$("#product-image").val(res.fileurl)
}
}
})
})
</script>
</body>
Đồng thời mình sẽ tạo thêm 1 file product_ajax.php
trong thư mục view với nội dung sau:
<?php
$base_url = 'C:\xampp\htdocs';
include_once ($base_url.'\TOPIC5\class\ProductClass.php');
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$file = $_FILES;
$file_path = 'upload/';
move_uploaded_file($file['file']['tmp_name'],$file_path.$file['file']['name']);
$fileurl = $file_path.$file['file']['name'];
$data = json_encode([
'success' => true,
'fileurl' => $fileurl
]);
echo $data;
}
Rồi, để mình giải thích một chút về nội dung code bên trên nhé:
1, Mình dùng Jquery lắng nghe sự kiện onchange của input type=”file”
có cái id là upload_file.
2, Sau khi bắt được sự kiện mình sẽ lấy data chính là file vừa upload để truyền qua cho product_ajax.php
xử lý bên đó.
3, Vì Data ở dạng file nó là một object nên chúng ta cần phải thực hiện truyền qua bằng cách append data vào Formdata.
4, product_ajax.php sau khi xử lý thành công sẽ trả về một data dưới dạng Json với nội dung:
‘success’ => true
và đường dẫn fileurl
5, Sau khi nhận được data json như trên Ajax sẽ xử lý:
if(res.success = true)
{$("#product-img").html('<img src="'+res.fileurl+'" style="width: 100px; height: 100px" alt=""> <br>')$("#product-image").val(res.fileurl)}
Bây giờ chúng ta sẽ thử kiểm tra kết quả nhé!
Các bạn để ý 2 chỗ mình bôi đỏ nhé. Đó là 2 sự kiện trả về của Ajax
Tiếp theo để insert dữ liệu mình sẽ sửa lại một chút đối với file product_add.php như sau
<?php
$base_url = 'C:\xampp\htdocs';
include_once ($base_url.'\TOPIC6\class\ProductClass.php');
$ProductClass = new ProductClass;
?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$data = $_POST;
$fileurl = $_POST['product_image'];
$insert_product = $ProductClass -> insert_product($data,$fileurl);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<title>Add Product</title>
</head>
<body>
<!-- <form action="" method="post" enctype="multipart/form-data">
<input type="text" placeholder="product_name" name="product_name"> <br>
<input type="text" placeholder="product_price" name="product_price"> <br>
<input type="file" name="file" id="upload_file"> <br>
<button style="cursor: pointer;" type="submit">Add</button>
</form> -->
<form method="post" action="">
<input type="text" placeholder="product_name" name="product_name"> <br>
<input type="text" placeholder="product_price" name="product_price"> <br>
<input type="file" name="file" id="upload_file"> <br>
<input type="hidden" value="" id="product-image" name="product_image">
`<div id="product-img">
</div>
<button style="cursor: pointer;" type="submit">Add</button>
</form>
<script>
$('#upload_file').on('change',()=>{
$file = $('#upload_file');
var formdata = new FormData();
formdata.append('file',$file[0].files[0])
$.ajax({
url: 'product_ajax.php',
data:formdata,
dataType: 'JSON',
method: 'POST',
processData: false,
contentType:false,
success: function(res) {
if(res.success = true) {
$("#product-img").html('<img src="'+res.fileurl+'" style="width: 100px; height: 100px" alt=""> <br>')
$("#product-image").val(res.fileurl)
}
}
})
})
</script>
</body>
</html>
Còn vì sao mình sửa như trên thì sẽ là HOMEWORK của các bạn nhé!
OK rồi các bản quay ra và kiểm tra thành quả thôi nào! Nhớ đừng quên để lại ý kiến phía dưới nhé
Banker To Coder
Hi All,
Nguyên đây! MinaCode là website mình tạo ra với mong muốn chia sẻ chút kiến thức liên quan đến lập trình FullStack.
Ngôn ngữ lập trình chủ yếu được sử dụng là Htm, Css, Javascript, Php cùng một số thư viện như Jquery, Fontawesome... Phía Frontend và Farmework Laravel phía Backend.
Mình chưa bao giờ tham gia bất cứ một trường lớp nào về lập trình. Tất cả kiến thức mình chia sẻ đều là trên tình thần tự học. Do đó:
+ MinaCode phù hợp với những tay ngang, xem lập trình như là một kỹ năng bổ trợ trong công việc hay là một kênh kiếm thêm thu nhập từ những very mini projects.
+ MinaCode không phù hợp với những bạn đang được đào tạo bài bản, chính quy.
Mình tin rằng, Trong tương lai không xa. Lập trình sẽ trở nên một kỹ năng không thể thiếu đối với các bạn trẻ.
Cuối cùng thì Ngôn ngữ lập trình không quan trọng bằng Tư duy lập trình. Mình chúc các bạn sẽ có được những kiến thức bổ ích với MinaCode.
--Ngô Sỹ Nguyên--