Sending a message to the server and changing text on a page when a button is pressed
Archive - Originally posted on "The Horse's Mouth" - 2014-05-23 15:43:11 - Graham EllisScenario ...
* I wish to provide a button on my page that signals when it's pressed back to the server
* I wish the server to log the button press (a vote, perhaps) but not refresh the page
* I wish to change the text on the page to give visual feedback that the button has been pressed
Easy enough, but hard to find all in one example.
I've just added a "like" facility on to the First Great Western Coffee Shop forum.
Here's the HTML for each "like" button" (shown over multiple lines to make it easier to read):
[<a href=/coffeeshop/lyke.php?id=154834
onClick='document.getElementById("txt154834").innerHTML="yum!";'>
<span id='txt154834'>like</span></a>]
The reference number in the example is the message number that the like button is attached to; this HTML is generated by a modified PHP forum script so that the receiving lyke.php knows [i]what[/i] the user has liked. It uses the forum cookie to identify [i]who[/i] is doing the liking, and registers all likes in a MySQL database to stop users registering lots of votes for the same post.
In order to prevent the browser redrawing the page, the lyke.php includes the following header:
header("HTTP/1.1: 204 No Content");
And (as that might suggest) there is no content. the onClick Javascipt changes the work "like" into "yum!" to indicate that the button was pressed.