How can one effectively handle database queries in PHP when using AJAX to retrieve and display data on the same page?
When using AJAX to retrieve and display data on the same page in PHP, it is important to handle database queries efficiently to ensure optimal performance. One effective way to do this is by creating a separate PHP file for handling database queries and then making AJAX calls to this file to retrieve the data. This helps in separating the concerns of data retrieval and presentation, making the code more organized and maintainable.
// db_query.php
<?php
// Include database connection
include 'db_connection.php';
// Perform database query
$query = "SELECT * FROM table_name";
$result = mysqli_query($conn, $query);
// Fetch data and return as JSON
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($data);
// Close database connection
mysqli_close($conn);
?>
// index.php
<!DOCTYPE html>
<html>
<head>
<title>Display Data with AJAX</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id="data"></div>
<script>
$(document).ready(function(){
$.ajax({
url: 'db_query.php',
type: 'GET',
dataType: 'json',
success: function(data){
// Display data on the page
$('#data').html(JSON.stringify(data));
},
error: function(){
console.log('Error fetching data');
}
});
});
</script>
</body>
</html>
Keywords
Related Questions
- What are the limitations in controlling when and how the web server sends a response to the client in PHP?
- How can PHP be started in a verbose/debug mode to identify which PHP script and line is causing a segmentation fault?
- What are common functions or methods in PHP that can be used to clear the screen in a CLI application?