Home  >  Article  >  Backend Development  >  How to Dynamically Update DIV Content Using jQuery, Ajax, and PHP?

How to Dynamically Update DIV Content Using jQuery, Ajax, and PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-21 16:15:30973browse

How to Dynamically Update DIV Content Using jQuery, Ajax, and PHP?

Dynamically Updating DIV Content via jQuery, Ajax, and PHP

Consider a scenario where you have a web page with a DIV containing dynamic content from a database:

<div id="summary">Here is a summary of movie</div>

Additionally, there's a list of links:

<a href="?id=1" class="movie">Name of movie</a>
<a href="?id=2" class="movie">Name of movie</a>
..

When a user clicks on a link:

  1. Ajax Request with GET Data: The page sends an Ajax request using the link's URL to pass data via GET to a PHP file (typically the same page).
  2. PHP Response with String: The PHP file processes the request and returns a string containing the summary text.
  3. DIV Content Update: Using jQuery, the DIV's #summary element is updated with the returned string.

To implement this functionality:

<code class="javascript">function getSummary(id) {
  $.ajax({
    type: "GET",
    url: 'Your URL',
    data: "id=" + id, // accessible as $_GET['id'] in PHP
    success: function(data) {
      $('#summary').html(data);
    }
  });
}</code>

In the HTML, add an onclick event to each link:

<code class="html"><a onclick="getSummary('1')">View Text</a>
<div id="#summary">This text will be replaced when the link is clicked.</div></code>

The above is the detailed content of How to Dynamically Update DIV Content Using jQuery, Ajax, and PHP?. 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