Create Ajax applications using PHP and jQuery

WBOY
Release: 2023-05-11 15:24:01
Original
594 people have browsed it

With the continuous development of web applications, Ajax has become a powerful tool that can communicate with the server without page refresh. Using Ajax, you can improve the performance and usability of web applications and improve user experience.

This article will introduce how to create Ajax applications using PHP and jQuery. We will create a simple query page where users can enter keywords and send them to the server using Ajax technology. The server will search the database and return relevant results, which will be displayed dynamically on the web page without reloading.

Before you start, please make sure you have installed PHP and jQuery. We will use PHP to process query requests and jQuery to send Ajax requests and process returned results.

Step 1: Create an HTML file

First, we need to create an HTML file as our query page. Below is a basic HTML file template, which includes a text box and a button.

<!DOCTYPE html>
<html>
<head>
  <title>Ajax Search</title>
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <script>
    //Ajax代码将放在这里
  </script>
</head>
<body>
  <h1>Ajax Search</h1>
  <input type="text" id="keyword" name="keyword" placeholder="Enter Keyword">
  <button id="search">Search</button>

  <div id="results">
    <!-- 结果将在这里动态显示 -->
  </div>

</body>
</html>
Copy after login

Step 2: Create a PHP file

Next, we need to create a PHP file to process query requests. The following is a sample code that handles a query request:

<?php
//连接到数据库
$db = mysqli_connect('localhost', 'username', 'password', 'database_name');

//检查连接是否成功
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  exit();
}

//从查询字符串中获取关键字
$keyword = $_GET['keyword'];

//构建查询
$sql = "SELECT * FROM products WHERE name LIKE '%".$keyword."%'";
$result = mysqli_query($db, $sql);

//检查查询是否成功
if (!$result) {
  echo 'Could not run query: ' . mysqli_error($db);
  exit();
}

//将结果转换为JSON格式并输出
$rows = array();
while($row = mysqli_fetch_assoc($result)) {
    $rows[] = $row;
}
echo json_encode($rows);

//关闭连接
mysqli_close($db);
?>
Copy after login

This code will query for products containing keywords and convert the results into JSON format. Next, we'll use jQuery to send Ajax requests and handle the returned results.

Step Three: Write Ajax Code

Now, we can combine the above code to create a complete Ajax application. Here is our jQuery code:

$(document).ready(function() {
    $('#search').click(function() {
        var keyword = $('#keyword').val();
    
        // 发送Ajax请求
        $.ajax({
            url: 'search.php',
            dataType: 'json',
            data: {
                keyword: keyword
            },
            success: function(data) {
                // 处理返回的结果
                var results = '';
                $.each(data, function(index, value) {
                    results += '<div>';
                    results += '<h3>' + value['name'] + '</h3>';
                    results += '<p>' + value['description'] + '</p>';
                    results += '<p>Price: ' + value['price'] + '</p>';
                    results += '</div>';
                });
    
                $('#results').html(results);
            },
            error: function(jqxhr, textStatus, error) {
                // 处理错误
                var err = textStatus + ", " + error;
                console.log( "Request Failed: " + err );
            }
        });
    });
});
Copy after login

This code includes a click event that will get the keyword when the user clicks the search button and send a request using Ajax. The request will be sent to the search.php file, which will query the database and return the results in JSON format. Once the result is successfully received, we will use jQuery to dynamically create the HTML of the result and display it on the page.

We regularly use jQuery's $.ajax method to handle asynchronous requests, which gives you a lot of advanced control and allows you to handle all types of data in a very easy way.

What should be noted here is the success and error callback functions of ajax in jQuery. Success represents a successful callback, and error represents an exception callback. So, when the server returns data successfully, the data will be passed to the success callback function, and then our business logic code will process the returned data. When an exception occurs in the request, for example, the server is brute-forced and returns a 403 status code, our code will receive the exception from the error callback function and perform related processing, such as displaying exception information to the user.

Step Four: Test the Application

Now, we can test our application. Open the HTML file, enter a keyword and click the search button. You should see relevant results appear dynamically on the page without reloading.

If you encounter problems, you can check the console log for any error messages, or view the PHP code to make sure it is working correctly.

Conclusion

Using PHP and jQuery, we can easily create powerful Ajax applications. Ajax makes web applications faster and more responsive, which improves user experience. Now you can create your own Ajax applications utilizing PHP and jQuery and improve the performance and usability of your web applications.

The above is the detailed content of Create Ajax applications using PHP and jQuery. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!