views:

30

answers:

1

I've got a simple website using plain HTML/CSS to display and PHP/MySQL for data storage.

Now I'd like to add a toggle button similar to facebooks "like" button.

How can I act on the user pressing the button (add database record for this item, change button text) without leaving the page?

I thought this question would have been asked and diskussied to no end, but all solutions I found require some other frameworks than plain PHP as background.

+3  A: 

You'll need to do it with javascript. Read up on "AJAX form posting".

A high level view:

  • user clicks on button
  • you capture the click via an onclick handler in javascript, and use it to call a javascript function
  • said function does a remote url request via XmlHttpRequest to a target page
  • that target page takes in the parameters passed via POST or GET and performs actions with them (eg add database record), and prints out any response required
  • the javascript function reads the response and acts accordingly (eg change button text)

and all this happens without refreshing the page.

You can do all this with pure low level javascript code, but plenty of libraries already abstract it while solving various issues with browser compatibilities. I'd suggest the jQuery javascript library. It provides an easy way to do exactly what you require, and good documentation.

Fanis
+1 for suggesting using jquery and not reinventing the wheel.
Mr Shunz