Web08 Ajax
Web08 Ajax
• Introduce
• AJAX's work
• XMLHttpRequest object
• PHP & jQuery Ajax
• The illustrative examples
Server
Trang web
New
Submit page
Reload
Server
javascript
Update
Response
Trang web
• Advantages:
– Content updates do not need to reload the entire
page.
– Reduce server processing work.
– Easy to learn and use.
• Disadvantages:
– Functions Back and Bookmark (Favorites) browser is
disabled.
– Force to use JavaScript → There are security related
issues.
Time
Time
• $(selector).load(URL,data,callback);
• $.get(URL,callback);
• $.post(URL,data,callback);
• $.ajax(args);
Trong đó:
– url: trang xử lý
– type: một trong hai phương thức POST/GET
– dataType: kiểu dữ liệu trả về: json, xml, script hoặc text
– async: true/false
– success : là hàm xử lý kết quả trả về
– error: hàm xử lý lỗi
HienLTH – KhietLTN Web Design 15
EG1: Get the hour
Table: hoa
$(document).ready(function(e) {
$("#cboLoaiHoa").change(function(e) {
$.ajax({
url: "LayHoa.php?MaLoai=" + $(this).val(),
type:"GET",
success: function(data){
$("#txtDSHoa").html(data);
}
});
});
});
<?php
include("DataProvider.php");
$ma = $_REQUEST['MaLoai'];
$kq = DataProvider::ExecuteQuery("SELECT * FROM hoa WHERE MaLoai = '{$ma}'");
echo "<table border='1'>
<tr>
<td>Tên hoa</td><td>Đơn giá</td>
</tr>";
while($r = mysqli_fetch_array($kq))
{
echo "<tr>
<td>{$r['TenHoa']}</td><td>{$r['GiaBan']}</td>
</tr>";
}
echo "</table>";
?>
• http://www.w3schools.com/ajax
• http://api.jquery.com/jquery.ajax
• http://labs.jonsuh.com/jquery-ajax-php-
json/