I’ve got a simple PHP script which reads specific phrases from a text file and displays one at random on the web page. In order to display another random phrase the whole page has to be refreshed at present. My question is – Is there a way to update just the area of the page which contains the phrase, displaying a new phrase each time a button is clicked? Currently the PHP below is contained in a h1 tag which has been styled using CSS. I then include a comment underneath it telling the user to refresh the page to show another random phrase. Ideally I would like this comment to be changed to a button so the user does not have to refresh the whole page each time.
Here is the simple PHP used to display a random phrase:
$str = file_get_contents('words.txt'); //Take the contents from the file to the variable
$result = explode(',',$str); //Split it by ','
echo $result[array_rand($result)]; //Return a random entry from the array.
Any help would be greatly appreciated.
Cheers, Tom
Example I used to get started learning PHP/AJX, excerpt from Using jQuery…
Create a php script to receive http requests and fetch data from the database
Client example
Output:
this element will be accessed by jquery and this text replaced