Refresh div tag with out refresing the whole page

Hello everybody,

I have the following test script and I’m trying to get the div tag refreshed when the button is clicked.
Im not passing any arguments. In this example I just want the random number generated when i click the button…

What am i missing?


<html>
	<head>
		<script src="http://code.jquery.com/jquery-latest.js"></script>
	 	<script>
	 	$(document).ready(function() {
	 	      $("#btn_click").click(function(event){
	 	          $('#div1').html();
	 	      });
	 	   });
 		</script> 		  		
  		<style>body{ font-size: 12px; font-family: Arial; }</style>			
	</head>
	
<body>
	<br />
	<div id="div1" style="border:solid 1px red; width: 100px;">	
		<?php  echo rand(10,100); ?>		
	</div>	
	<br /><br />
	
	<div id="div2" style="border:solid 1px green; width: 100px;">
		<button type="button" id="btn_click" /> click me!</button>
	</div>	
</body>
</html>


Hi there,

The only way this is going to work like you want is to stick the PHP function in a separate script and when someone clicks the button, fire off a AJAX request, have the script return a random number and stick it in the <div>.

However, wouldn’t it just be better to use JavaScript to generate the random number?

Here’s an example:

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Generate random number</title>
  </head>

  <body>
    <div id="div1" style="border:solid 1px red; width: 100px;"></div>
    <br /><br />
    <div id="div2" style="border:solid 1px green; width: 100px;">
    <button type="button" id="btn_click" /> click me!</button>
    </div>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script>
      $("#btn_click").click(function(){
        $('#div1').html(10 + Math.floor(Math.random()*91));
      });

      $("#btn_click").trigger("click");
    </script>
  </body>
</html>