Home >Backend Development >PHP Tutorial >How to Dynamically Update DIV Content Using AJAX, PHP, and jQuery via Link Clicks?

How to Dynamically Update DIV Content Using AJAX, PHP, and jQuery via Link Clicks?

Susan Sarandon
Susan SarandonOriginal
2024-10-21 17:38:02582browse

How to Dynamically Update DIV Content Using AJAX, PHP, and jQuery via Link Clicks?

Dynamically Updating DIV Content via AJAX, PHP, and jQuery

Question: How can you dynamically update the content of a DIV element using AJAX, PHP, and jQuery, where each link click retrieves data from the database and replaces the DIV with the fetched summary?

Answer:

Step 1: Create the HTML Structure

  • Include the DIV element that will display the summary:
<code class="html"><div id="summary"></div></code>
  • Add a list of links that trigger the summary retrieval process:
<code class="html"><a href="?id=1" class="movie">Name of movie</a>
<a href="?id=2" class="movie">Name of movie</a></code>

Step 2: Implement the jQuery Script

  • Create a jQuery function to handle the AJAX request and update the DIV:
<code class="javascript"><script>
function getSummary(id) {
  $.ajax({
    type: "GET",
    url: 'Your URL',
    data: "id=" + id, // appears as $_GET['id'] @ your backend side
    success: function(data) {
      // data is your summary
      $('#summary').html(data);
    }
  });
}
</script></code>

Step 3: Add Click Event to Links

  • Add an onclick event to each link, passing the corresponding ID:
<code class="html"><a onclick="getSummary('1')">View Text</a></code>

Step 4: Server-Side PHP

  • In the PHP script at the URL specified in $.ajax(), retrieve the summary based on the received ID:
<code class="php">$id = $_GET['id'];
$summary = fetchSummary($id); // Fetch summary from database</code>
  • Return the fetched summary as a string:
<code class="php">echo $summary;</code>

By clicking the links, the jQuery function will trigger AJAX requests, fetch the summary from the PHP script, and update the DIV with the retrieved content.

The above is the detailed content of How to Dynamically Update DIV Content Using AJAX, PHP, and jQuery via Link Clicks?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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