Simple Ajax Script that will display data from another page, using PHP

Simple Ajax Script that will display data from another page, using PHP

Be sure to include this code before tag ends.

2
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

The ajax script:

Create a php page called “generate_random_name.php” and just put there a simple echo.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 
<?php echo 'x'; ?>
 
<a href="#" id="ajax-test" onclick="fetch_result();">Generate random name</a>
<div id="variable"></div>
 
<script>
$("#ajax-test").submit(function(event) {
 
      /* stop form from submitting normally */
      event.preventDefault();
	  });
 
function fetch_result()
{
 $.ajax({
 type: 'GET',
 url: 'generate_random_name.php',
 success: function (response) {
  document.getElementById("variable").innerHTML=response; 
 }
 });
}
</script>

Add a comment: