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

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

Patricia Arquette
Release: 2024-10-21 16:20:02
Original
996 people have browsed it

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

Modifying DIV Content Using Ajax, PHP, and jQuery

In web development, it's often necessary to update portions of a page without reloading the entire page. This can be achieved using Ajax, PHP, and jQuery.

Problem Statement

A page contains a DIV element holding database-sourced text and a list of hyperlinks. The objective is to load the summary (text) associated with a particular link into the DIV upon clicking that link.

Solution

HTML:

Create the DIV and link elements as described:

<code class="html"><div id="summary">Here is summary of movie</div>

<a href="?id=1" class="movie">Name of movie</a>
<a href="?id=2" class="movie">Name of movie</a></code>
Copy after login

JavaScript (jQuery):

Handle the click event on the links:

<code class="javascript"><script>
function getSummary(id) {
  $.ajax({
    type: "GET",
    url: 'your_php_url',
    data: "id=" + id,
    success: function(data) {
      $('#summary').html(data);
    }
  });
}
</script></code>
Copy after login

PHP:

Handle the GET request in a PHP file:

<code class="php">// get the ID from the request
$id = $_GET['id'];

// fetch the summary from the database
$summary = get_summary($id);

// return the summary as a string
echo $summary;</code>
Copy after login

Event Binding:

Add the onclick event attribute to the links to call the getSummary function:

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

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

source:php
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