March 16, 2012

Refresh single page PHP element using button

Question by Michael C

I have a single page quote generator, it works by holding the quotes in a 2D array and generating a random number to pull from the matching value in the array using PHP every time that the page is refreshed, I want to change this and make it so that only the element is changed when you press a button, reducing the http requests to the server.

I have tried various “onClick” methods but they never seem to work, I’m assuming that this is something that I should use Javascript (Or any js libraries) for. The function that I want to run when the button is pressed is this:

  <?php 
    $max = max(array_map('count', $arrCSV));
    $num = rand(0,$max);
    $quote = $arrCSV[0][$num] . "." ;
    echo $quote;
  ?>

Any help is much, much appreciated.

Answer by Starx

Like, @Dr.Kameleon, this cannot be done with PHP alone.

Using jQuery, you can reload an element like this

$("#yourdiv").load("the/page/from/where/it/should/be/updated.php");

Attach it to the click event of the button

$("button").click(function() {
    $("#yourdiv").load("the/page/from/where/it/should/be/updated.php"); 
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!