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.
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.
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>
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>
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>
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>
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!