Jump to content

Next Random Headline via button without reloading


eleven0

Recommended Posts

<?PHP

$quotes = array(
"This is my quote",
"To be or not to be",
"<b>You can</b> <u>use html</u>");

$count = count($quotes);

$random = (rand()%$count);

echo $quotes[$random];

?>

 

I have this script and it shows the array on random. everytime page reloads, it shows something different. I want to do the same thing with a button(like a link) without reloading the page. I pretty much don't know anything about Ajax or javascript.

 

Can someone point me to the right direction? so i can do more search on it. Thanks.

Use a framework, like jQuery or Prototype.

 

Here is a simple jQuery example, not tested thought:

$("#request-new").click(function(){
$.ajax({
	type: "GET",
	url: "./headline.php",
	error: function(xml, status, error){
		alert("Sorry but we encountered an error.");
	},
	success: function(data, status){
		$("#latest-headline").html(data);
	}
});
});

 

Then, all you need is a file called headline.php that has your above code in it. You also need to surround the area where the headline is appearing in a div with an id attribute of latest-headline. And your button or link needs an id attribute of request-new.

 

Like this:

 

<div id="latest-headline">
<!-- You can include the PHP script here to start with, so that a headline gets shown -->
</div>
<a id="request-new">New Random Headline</a>

 

Good luck.

Thanks for the quick reply.

 

That didn't work though.

 

"New Random Headline" is not clickable. Here is what i did;

 

I added the script to my page. I placed following

<script type="text/javascript">
	$("#request-new").click(function(){
   $.ajax({
      type: "GET",
      url: "./headline.php",
      error: function(xml, status, error){
         alert("Sorry but we encountered an error.");
      },
      success: function(data, status){
         $("#latest-headline").html(data);
      }
   });
});</script>

between <head> and </head>.

 

Then;

 

<div id="latest-headline">
<?PHP

$quotes = array(
"This is my quote",
"To be or not to be",
"<b>You can</b> <u>use html</u>");

$count = count($quotes);

$random = (rand()%$count);

echo $quotes[$random];

?>
</div>
<a id="request-new">New Random Headline</a>

 

New Random Headline is not even clickable. What am i doing wrong?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.