Home  >  Article  >  Backend Development  >  How Can I Alter HTML Page Content Dynamically Without Refreshing the Page Using AJAX?

How Can I Alter HTML Page Content Dynamically Without Refreshing the Page Using AJAX?

Barbara Streisand
Barbara StreisandOriginal
2024-10-22 11:16:30935browse

How Can I Alter HTML Page Content Dynamically Without Refreshing the Page Using AJAX?

Change HTML Page Contents Without Reloading Using AJAX

You want to update the content of a DIV element without refreshing the page when a link is clicked. Here's how you can achieve this using PHP and AJAX:

PHP Configuration:

  • Create a PHP script (e.g., data.php) that connects to your database and retrieves the data based on the parameter id.

HTML Markup:

  • Create a DIV element with an identifier (e.g., myStyle).
  • Add links with onClick handlers that call a JavaScript function with the id as an argument.

JavaScript with jQuery:

  • Include the jQuery library.
  • Define a recp function that uses AJAX to load the data from data.php into the myStyle DIV.

Example Code:

HTML:

<code class="html"><script type="text/javascript">
  function recp(id) {
    $('#myStyle').load('data.php?id=' + id);
  }
</script>

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

<div id='myStyle'>
</div></code>

PHP:

<code class="php"><?php
  require ('myConnect.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'];
  }
?></code>

Once you have implemented this solution, clicking on the links will update the content of the myStyle DIV without reloading the page.

The above is the detailed content of How Can I Alter HTML Page Content Dynamically Without Refreshing the Page Using AJAX?. 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