stevey
stevey

Reputation: 1167

Run a php function when click on a button

I have a php script page with a form like this:

<form method="post" action="clientmanager.php">
<input type="text" name="code_client" id="code_client" />
<input type="submit" value="Save" />
</form>

In my file "clientmanager.php", I have a function for example "addClient()". I want to click the button and only call the function "addClient()" in the file "clientmanager.php" instead of call the whole file "clientmanager.php", So how could I do?? Thx!!!!

Upvotes: 0

Views: 3363

Answers (2)

iWizard
iWizard

Reputation: 7094

You can do that over jquery (ajax).

  1. Call jquery library in head

  2. Call clientmanager.php over this code:

my_form.php

....
<script type="text/javascript" src="jquery.js"></script>
...

<form method="post" action="">
<input type="text" name="code_client" id="code_client" />
<input id="my_button" type="button" value="Save" />
</form>


<div id="response_div"></div>


<script type="text/javascript">

    $(document).ready(function(){

        $("#my_button").click(function(){


                $.post("clientmanager.php", {code_client: $('#code_client').val()}, function(data){

                    if(data.length >0) {

                        $('#response_div').html(data);

                    }//end if
                });


        });

    });

</script>

clientmanager.php

<?php

echo $_POST['code_client'];

?>

Upvotes: 0

Jeroen
Jeroen

Reputation: 13257

Add this to the top of the file:

if (isset ($_POST ['code_client'])) addClient();

However, you should consider using a different setup - processing forms like this is considered bad practice. Maybe create a separate file, use OOP, MVC, a framework, anything other than this.

Upvotes: 1

Related Questions