AJAX – Hoạt động cơ sở dữ liệu

Để minh họa rõ ràng việc truy cập thông tin từ cơ sở dữ liệu bằng AJAX dễ dàng như thế nào. Chúng tôi sẽ xây dựng các truy vấn MySQL. Và hiển thị kết quả trên “ajax.html”. Nhưng trước khi chúng tôi tiến hành, hãy để chúng tôi làm công việc sau. Tạo bảng bằng lệnh sau :

LƯU Ý – Chúng tôi giả định rằng bạn có đủ đặc quyền để thực hiện các hoạt động MySQL sau đây.

CREATE TABLE 'ajax_example' (
   'name' varchar(50) NOT NULL,
   'age' int(11) NOT NULL,
   'sex' varchar(1) NOT NULL,
   'wpm' int(11) NOT NULL,
   PRIMARY KEY  ('name')
) 

Bây giờ hãy nhập dữ liệu sau vào bảng này bằng cách sử dụng các câu lệnh SQL sau:

INSERT INTO 'ajax_example' VALUES ('Jerry', 120, 'm', 20);
INSERT INTO 'ajax_example' VALUES ('Regis', 75, 'm', 44);
INSERT INTO 'ajax_example' VALUES ('Frank', 45, 'm', 87);
INSERT INTO 'ajax_example' VALUES ('Jill', 22, 'f', 72);
INSERT INTO 'ajax_example' VALUES ('Tracy', 27, 'f', 0);
INSERT INTO 'ajax_example' VALUES ('Julie', 35, 'f', 90);

Tệp HTML phía client

Bây giờ, hãy để chúng tôi tạo tệp HTML phía client có tên là ajax.html và nó sẽ có nôi dung sau:

<html>
   <body>
      <script language = "javascript" type = "text/javascript">
         <!-- 
         //Browser Support Code
         function ajaxFunction() {
            var ajaxRequest;  // The variable that makes Ajax possible!
            try {        
               // Opera 8.0+, Firefox, Safari
               ajaxRequest = new XMLHttpRequest();
            } catch (e) {
               
               // Internet Explorer Browsers
               try {
                  ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
               } catch (e) {
                  
                  try {
                     ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                  } catch (e) {
                     // Something went wrong
                     alert("Your browser broke!");
                     return false;
                  }
               }
            }
            // Create a function that will receive data
            // sent from the server and will update
            // div section in the same page.
            ajaxRequest.onreadystatechange = function() {
            
               if(ajaxRequest.readyState == 4) {
                  var ajaxDisplay = document.getElementById('ajaxDiv');
                  ajaxDisplay.innerHTML = ajaxRequest.responseText;
               }
            }
            // Now get the value from user and pass it to
            // server script.
            var age = document.getElementById('age').value;
            var wpm = document.getElementById('wpm').value;
            var sex = document.getElementById('sex').value;
            var queryString = "?age = " + age ;
            queryString +=  "&wpm = " + wpm + "&sex = " + sex;
            ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
            ajaxRequest.send(null); 
         }
         //-->
      </script>
      <form name = 'myForm'>
         Max Age: <input type = 'text' id = 'age' /> <br />
         Max WPM: <input type = 'text' id = 'wpm' /> <br />
         Sex: 
         <select id = 'sex'>
            <option value = "m">m</option>
            <option value = "f">f</option>
         </select>
         <input type = 'button' onclick = 'ajaxFunction()' value = 'Query MySQL'/>
      </form>
      <div id = 'ajaxDiv'>Your result will display here</div>
   </body>
</html>

LƯU Ý – Cách truyền các biến trong truy vấn theo tiêu chuẩn HTTP và có formA.

URL?variable1 = value1;&variable2 = value2;

Tệp PHP phía máy chủ

Tập lệnh phía client của bạn đã sẵn sàng. Bây giờ, chúng tôi phải viết tập lệnh phía máy chủ của mình. Tập lệnh này sẽ tìm nạp Age , WPM và SEX vào cơ sở dữ liệu. Và sẽ gửi lại cho Client. Đặt đoạn mã sau vào tệp “ajax-example.php“.

<?php
$dbhost = "localhost";
$dbuser = "dbusername";
$dbpass = "dbpassword";
$dbname = "dbname";
	
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
	
//Select Database
mysql_select_db($dbname) or die(mysql_error());
	
// Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
	
// Escape User Input to help prevent SQL Injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
	
//build query
$query = "SELECT * FROM ajax_example WHERE sex = '$sex'";

if(is_numeric($age))
   $query .= " AND age <= $age";

if(is_numeric($wpm))
   $query .= " AND wpm <= $wpm";
	
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());

//Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";

// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)) {
   $display_string .= "<tr>";
   $display_string .= "<td>$row[name]</td>";
   $display_string .= "<td>$row[age]</td>";
   $display_string .= "<td>$row[sex]</td>";
   $display_string .= "<td>$row[wpm]</td>";
   $display_string .= "</tr>";
}

echo "Query: " . $query . "<br />";
$display_string .= "</table>";

echo $display_string;
?>

Bây giờ, hãy thử bằng cách nhập một giá trị hợp lệ (ví dụ: 120) vào Max Age hoặc bất kỳ hộp nào khác và sau đó nhấp vào nút Truy vấn MySQL. Bạn sẽ thấy kết quả hiện ra màn hình

Nếu bạn hoàn thành tốt bài học này thì bạn đã biết cách sử dụng song song MySQL, PHP, HTML và Javascript để viết các ứng dụng AJAX. Để sử dụng trình soạn thảo mã nguồn, hãy tham khảo Sublime Text 3