database - need a button that calls a php function


I need to have a button that calls a php function to resort displayed data from the db. How the heck do I do this? I just found out that because php is server side this sucks. So any help please?




You can't directly call a PHP function pressing a button for the reason you stated yourself. In order to execute PHP code you need to make a new request to the server. The request could be made to another script or to the same that produced your page by calling it again with some parameter to control its behavior.

Alternatively, you can call a PHP script via Javascript (AJAX) so that you can handle its output and update the page without a full reload.

The second option is neater but more complex, the first one might look less pleasing to the eye, but works regardless of the user's browser having Javascript enabled or not.




It should probably sit inside a form field, something like this:

<form action="YOUR_PHP_SCRIPT.php">
<input type="submit" />

When the submit button is pressed, the action for the form is triggered.

There may be a swathe of other things you'll need to take into consideration from this point onward, but this is a start.




Yeah because PHP is server-side, you have two options. One is to make a button that calls the PHP script and renders a completely new page. The other is to use AJAX (asynchronous javascript and XML) on the page, see for a good way to do that, and only re-render the table that is displaying data.




This is a job for ajax, as others mentioned. If I may elaborate, if you're starting out, I HIGHLY recommend using a javascript library to make your life easier. With prototype, here's what your button might look like:

<input type="button" id="button_foo">Button</input>

Here's what your javascript might look like:

    new Ajax.Request('handler.php',{

This may seem a little daunting at first, but I think basic js has a pretty manageable learning curve when using a library. The above code would take whatever handler.php outputs, and replace the contents of an element with and id of "table_bar" with the returned html.

if you do decide to use prototype, the docs are really helpful and easy to understand, and there is a really excellent book by pragmatic press on the subject that'll have you understanding it very quickly.

Hope that helps!




what Yacoby said, you'll need to use AJAX to make the call to the server, or something like this:

People are also looking for solutions to the problem: php - Escape Json Object in a Json response in a special condition


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.