AJAX là cách duy nhất cho phép giao tiếp phía máy khách với phía máy chủ. Bạn có thể gửi các yêu cầu AJAX dễ dàng hơn bằng cách sử dụng các thư viện hoặc framework có sẵn trên JavaScript. Trong bài viết này, tôi sẽ hướng dẫn cho bạn cách bạn cách để gửi các yêu cầu GET và POST AJAX bằng JavaScript và xử lý yêu cầu bằng PHP, cụ thể hện là sử dụng XMLHttpRequest để giao tiếp với máy chủ. Bắt đầu nào.
Tạo bảng dữ liệu
Đầu tiên, bạn hãy tạo một bảng dẽ liệu có tên employee và thêm vào đó 1 số bản ghi, với cấu trúc như sau:
CREATE TABLE `employee` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `emp_name` varchar(80) NOT NULL, `salary` varchar(20) NOT NULL, `email` varchar(80) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Cấu hình
Tại file config.php
để kết nối đến cơ sở dữ liệu của bạn
Code hoàn chỉnh như sau:
<?php $host = "localhost"; /* Host name */ $user = "root"; /* User */ $password = ""; /* Password */ $dbname = "tutorial"; /* Database name */ $con = mysqli_connect($host, $user, $password,$dbname); // Check connection if (!$con) { die("Connection failed: " . mysqli_connect_error()); }
Xem thêm: upload nhiều file sử dụng Php và JavaScript
HTML
Tạo 3 phần tử input để nhập cho các trường: name, salary, và email. Ở dưới cùng thêm 1 Button với sự kiện onclick gọi vào chức năng insertNewEmployee()
.
Các bản ghi sẽ được liệt kê vào bảng <table id='emptTable'>
sử dụng JavaScript và AJAX.
Completed Code
<div> Name: <input type="text" id='txt_name'> <br> Salary: <input type="text" id='txt_salary'> <br> Email: <input type="text" id='txt_email'> <br> <input type="button" id="btn_submit" value="Submit" onclick="insertNewEmployee();"> </div> <table id='empTable' border='1'> <thead> <tr> <th>Name</th> <th>Salary</th> <th>Email</th> </tr> </thead> <tbody></tbody> </table>
PHP
Tạo file 'ajaxfile.php'
để xử lý các yêu cầu AJAX.
Ví dụ như tôi muốn sử lý cả các yêu cầu về phương thức GET và POST trong cùng 1 file, thì tôi sẽ gán cả 2 vào biến $request
.
Phương thức GET(Tìm nạp các bản ghi)
Kiểm tra xem $_GET['request']
có được đặt hay không nếu được đặt thì gán $_GET['request']
cho biến $request
.
Nếu $request == 1
thì tìm nạp tất cả các bản ghi từ bảng employee
và gán vào biến $employeeData
. Lặp lại các bản ghi đã tìm nạp.
Khởi tạo mảng $response
với các key: id, emp_name, salary, và email.
Trả về mảng $response
với định dạng JSON.
Phương thức POST(chèn các bản ghi)
Nếu $request == 2
thì đọc các giá trị POTS bằng cách sử dụng json_decode(file_get_contents("php://input"))
.
Gán các giá trị cho các biến và chuẩn bị câu lệnh INSERT.
Nếu truy vấn INSERT được thực thi thành công thì trả về 1ngược lại 0.
Code như sau:
<?php include "config.php"; $request = 2; // Read $_GET value if(isset($_GET['request'])){ $request = $_GET['request']; } // Fetch records if($request == 1){ // Select record $sql = "SELECT * FROM employee"; $employeeData = mysqli_query($con,$sql); $response = array(); while($row = mysqli_fetch_assoc($employeeData)){ $response[] = array( "id" => $row['id'], "emp_name" => $row['emp_name'], "salary" => $row['salary'], "email" => $row['email'], ); } echo json_encode($response); exit; } // Insert record if($request == 2){ // Read POST data $data = json_decode(file_get_contents("php://input")); $name = $data->name; $salary = $data->salary; $email = $data->email; // Insert record $sql = "insert into employee(emp_name,salary,email) values('".$name."',".$salary.",'".$email."')"; if(mysqli_query($con,$sql)){ echo 1; }else{ echo 0; } exit; }
JavaScript
Sử dụng đối tượng XMLHttpRequest
để gửi cấc yêu cầu AJAX.
.open() – Các phương thức nhận 3 tham số –
- Phương thức yêu cầu – GET hoặc POST.
- Đường dẫn tệp AJAX. Truyền tham số với URL theo yêu cầu GET –
ajaxfile.php?name=yogesh&city=bhopal
. - Đây là một tham số tùy chọn nhận giá trị Boolean
true
orfalse
. Giá trị mặc định làtrue
. Chuyểntrue
cho không đồng bộ vàfalse
cho các yêu cầu đồng bộ.
.setRequestHeader() – Phương thức này được sử dụng để thiết lập Content-Type
. Mặc định, content-type được set là'application/x-www-form-urlencoded'
. Bạn có thể thay đổi giá trị của nó ví dụ như – application/json
, multipart/form-data
.
.onreadystatechange – Thuộc tính này gọi theo yêu cầu thay đổi trạng thái. Chỉ định một chức năng ẩn danh để xử lý phản hồi. Nếu this.readyState == 4 && this.status == 200
có nghĩa là phản hồi của máy chủ đã sẵn sàng để xử lý.
.send() – Phương thức này gửi yêu cầu AJAX. Nó cũng được sử dụng để gửi dữ liệu.
- Cú pháp GET –
var xhttp = new XMLHttpRequest(); xhttp.open("GET", "ajaxfile.php?request=1", true); xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // Response var response = this.responseText; } }; xhttp.send();
Cú pháp trên với jQuery
$.ajax({ url: 'ajaxfile.php?request=1', type: 'get', success: function(response){ } });
- Cú pháp POST–
application/x-www-form-urlencoded; charset=UTF-8
is a default Content-Type but you can use any other type e.g. – application/json
, multipart/form-data
, etc.
var xhttp = new XMLHttpRequest(); xhttp.open("POST", "ajaxfile.php", true); xhttp.setRequestHeader("Content-Type", "application/json"); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // Response var response = this.responseText; } }; var data = {name:'yogesh',salary: 35000,email: 'yogesh@makitweb.com'}; xhttp.send(JSON.stringify(data));
Cú pháp trên với jQuery
$.ajax({ url: 'ajaxfile.php', type: 'post', data: {name:'yogesh',salary: 35000,email: 'yogesh@makitweb.com'}, success: function(response){ } });
Tạo 2 function như sau–
- loadEmployees() – Hàm này gọi trên trang được tải thành công.
Tạo đối tượng của XMLHttpRequest
. Chỉ định yêu cầu GET và đường dẫn tệp AJAX với tham số ('ajaxfile.php?request=1'
) trong phương thức .open()
. Set Content-type
à xử lý phản hồi của máy chủ với thuộc tính onreadystatechange
Phân tích cú pháp this.responseText
thành đối tượng JSON và chọn <table id='empTable'> <tbody>
và làm trống nó.
Lặp lại các response
để đọc các giá trị. Tạo một phần tử hàng trong bảng mới và gán giá trị phản hồi trong ô.
Gửi yêu cầu bằng phương thức send()
- insertNewEmployee() – THàm này gọi khi nhấp vào nút Gửi.
Đọc các giá trị từ các hộp văn bản và gán chúng trong các biến. Nếu các biến không trống thì hãy tạo một đối tượng JSON data
. Khởi tại đối tượng data
với các giá trị hộp văn bản.
Tạo đối tượngXMLHttpRequest
và chỉ định yêu cầu POST và đường dẫn tệp AJAX ('ajaxfile.php'
) trong phương thức .open()
. Set Content-type
là 'application/json'
và xử lý phản ứng máy chủ với thuộc tính onreadystatechange
Chỉ định this.responseText
trong response
. Nếu response == 1
thì thông báo 1 tin nhắn và gọi loadEmployees()
để tìm nạp các bản ghi.
Code hoàn chỉnh:
loadEmployees(); // Load records with GET request function loadEmployees() { var xhttp = new XMLHttpRequest(); // Set GET method and ajax file path with parameter xhttp.open("GET", "ajaxfile.php?request=1", true); // Content-type xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // call on request changes state xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // Parse this.responseText to JSON object var response = JSON.parse(this.responseText); // Select <table id='empTable'> <tbody> var empTable = document.getElementById("empTable").getElementsByTagName("tbody")[0]; // Empty the table <tbody> empTable.innerHTML = ""; // Loop on response object for (var key in response) { if (response.hasOwnProperty(key)) { var val = response[key]; // insert new row var NewRow = empTable.insertRow(0); var name_cell = NewRow.insertCell(0); var username_cell = NewRow.insertCell(1); var email_cell = NewRow.insertCell(2); name_cell.innerHTML = val['emp_name']; username_cell.innerHTML = val['salary']; email_cell.innerHTML = val['email']; } } } }; // Send request xhttp.send(); } // Insert new record with POST request function insertNewEmployee() { var name = document.getElementById('txt_name').value; var salary = document.getElementById('txt_salary').value; var email = document.getElementById('txt_email').value; if(name != '' && salary !='' && email != ''){ var data = {name: name,salary: salary,email: email}; var xhttp = new XMLHttpRequest(); // Set POST method and ajax file path xhttp.open("POST", "ajaxfile.php", true); // call on request changes state xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var response = this.responseText; if(response == 1){ alert("Insert successfully."); loadEmployees(); } } }; // Content-type xhttp.setRequestHeader("Content-Type", "application/json"); // Send request with data xhttp.send(JSON.stringify(data)); } }
DEMO
Video demo của project
Bạn có thể tại Source Code của bài hướng dẫn này tại đây