Home > Database > Mysql Tutorial > body text

How Can I Dynamically Update a Div\'s Content with AJAX Without Page Refresh?

Mary-Kate Olsen
Release: 2024-11-24 14:33:53
Original
730 people have browsed it

How Can I Dynamically Update a Div's Content with AJAX Without Page Refresh?

HTML - Change Page Contents Dynamically Without Refreshing

Challenge:

You have data retrieved from a database and displayed in a div. When a link is clicked, you want to update the div's contents without refreshing the page.

Solution:

Leveraging AJAX, you can bypass page refreshes and update the div's content seamlessly. Here's how it works:

Client-Side (HTML and JavaScript):

  • Create links with event handlers that call JavaScript functions.
  • In those JavaScript functions, use jQuery's load() method to send a request to a PHP script with parameters (e.g., $('#myStyle').load('data.php?id=' id);).

Server-Side (PHP):

  • Create a separate PHP file that handles the AJAX request.
  • Fetch the data from the database using the parameter received from the AJAX request.
  • Return the updated content to the browser.

Example:

<a href="#" onClick="recp('1')" > One   </a>
<a href="#" onClick="recp('2')" > Two   </a>
<a href="#" onClick="recp('3')" > Three </a>

<div>
Copy after login
function recp(id) {
  $('#myStyle').load('data.php?id=' + id);
}
Copy after login
// In data.php
$id = $_GET['id'];
$results = mysql_query("SELECT para FROM content WHERE  para_ID='$id'");   
if( mysql_num_rows($results) > 0 )
{
   $row = mysql_fetch_array( $results );
   echo $row['para'];
}
Copy after login

By following these steps, you can update the div's contents dynamically without causing the entire page to refresh, making your website more responsive and user-friendly.

The above is the detailed content of How Can I Dynamically Update a Div\'s Content with AJAX Without Page Refresh?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template