Tom
Tom

Reputation: 137

Update Specific Area of Web Page Without Re-loading Entire Page

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

Upvotes: 0

Views: 872

Answers (3)

GDP
GDP

Reputation: 8178

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

//--------------------------------------------------------------------------
// Example php script for fetching data from mysql database
//--------------------------------------------------------------------------
$host = "localhost";
$user = "root";
$pass = "root";

$databaseName = "ajax01";
$tableName = "variables";

//--------------------------------------------------------------------------
// 1) Connect to mysql database
//--------------------------------------------------------------------------
include 'DB.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);

//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$result = mysql_query("SELECT * FROM $tableName");          //query
$array = mysql_fetch_row($result);                          //fetch result    

//--------------------------------------------------------------------------
// 3) echo result as json 
//--------------------------------------------------------------------------
  echo json_encode($array);

Client example

Output:

this element will be accessed by jquery and this text replaced

<script id="source" language="javascript" type="text/javascript">

$(function () 
{
  //-----------------------------------------------------------------------
  // 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
  //-----------------------------------------------------------------------
  $.ajax({                                      
    url: 'api.php',                  //the script to call to get data          
    data: "",                        //you can insert url argumnets here to pass to api.php
                                     //for example "id=5&parent=6"
    dataType: 'json',                //data format      
    success: function(data)          //on recieve of reply
    {
      var id = data[0];              //get id
      var vname = data[1];           //get name
      //--------------------------------------------------------------------
      // 3) Update html content
      //--------------------------------------------------------------------
      $('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
      //recommend reading up on jquery selectors they are awesome 
      // http://api.jquery.com/category/selectors/
    } 
  });
}); 

</script>
</body>

Upvotes: 1

Oliver
Oliver

Reputation: 2864

With jQuery this is quite easy:

html:

<div id="random"></div>
<input type="button" id="update" />

javascript:

<script>
$("#update").on("click", function() {
    $.ajax({
        url: "/randomwords.php",
        success: function(data) { $("#random").html(data); }
    });
});
</script>

randomwords.php is your snippet from above without anything else.

Upvotes: 0

Moin Zaman
Moin Zaman

Reputation: 25465

Two ways I can think of:

  1. Load in a bunch of them each refresh, let's say 10, but show only 1 of those. On clicking a a button cycle through the other 9.
  2. Use AJAX and actually load in a new phrase each button click.

Upvotes: 1

Related Questions