11

I need to run some PHP function when a button is clicked. I know this is not supposed to be php's use, rather js should do it, but what my functions are doing in gathering data from a server when the user asks it. Specifically, it gets some user data and writes it to a file, and the user should decide what data will be gathered.
How can I do this? I saw the post Run PHP File On Button Click but I am still not sure how to use it.
I'm learning, so please don't be too harsh

I have tried onclick() and all sorts of things but it didn't lead to anything useful

Menelaos
  • 23,508
  • 18
  • 90
  • 155
Mihai Bujanca
  • 4,089
  • 10
  • 43
  • 84
  • Please describe in more detail, even pseudo code, what you want to do, what kind of button are you thinking about, what did you try, where did you fail, what kind of process do you want to run and why doesn't it work? – markus Apr 11 '13 at 20:06
  • 1
    Look into AJAX, specifically. This is a moderately helpful article, I've found: http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/ – Mike Apr 11 '13 at 20:06
  • @markus For example I have a php function `getvideos()` which returns `url`s to the user's videos and I want to call it when the user clicks a button – Mihai Bujanca Apr 11 '13 at 20:09
  • Why don't you just load the video page when the user clicks that button and show the link there? – markus Apr 11 '13 at 20:10
  • I don't want to load the videos, I want to store the video url in a file – Mihai Bujanca Apr 11 '13 at 20:12
  • So why don't you just server the file with the video url, when the button is clicked? – markus Apr 11 '13 at 20:12
  • Because I don't know the url and it's not only one url. I need to ask for all the urls of all videos. And not only, it was just an example. Same with photos and other like that – Mihai Bujanca Apr 11 '13 at 20:15

6 Answers6

13

A php file is run whenever you access it via an HTTP request be it GET,POST, PUT.

You can use JQuery/Ajax to send a request on a button click, or even just change the URL of the browser to navigate to the php address.

Depending on the data sent in the POST/GET you can have a switch statement running a different function.

Specifying Function via GET

You can utilize the code here: How to call PHP function from string stored in a Variable along with a switch statement to automatically call the appropriate function depending on data sent.

So on PHP side you can have something like this:

<?php

//see http://php.net/manual/en/function.call-user-func-array.php how to use extensively
if(isset($_GET['runFunction']) && function_exists($_GET['runFunction']))
call_user_func($_GET['runFunction']);
else
echo "Function not found or wrong input";

function test()
{
echo("test");
}

function hello()
{
echo("hello");
}

?>

and you can make the simplest get request using the address bar as testing:

http://127.0.0.1/test.php?runFunction=hellodddddd

results in:

Function not found or wrong input

http://127.0.0.1/test.php?runFunction=hello

results in:

hello

Sending the Data

GET Request via JQuery

See: http://api.jquery.com/jQuery.get/

$.get("test.cgi", { name: "John"})
.done(function(data) {
  alert("Data Loaded: " + data);
});

POST Request via JQuery

See: http://api.jquery.com/jQuery.post/

$.post("test.php", { name: "John"} );

GET Request via Javascript location

See: http://www.javascripter.net/faq/buttonli.htm

<input type=button 
value="insert button text here"
onClick="self.location='Your_URL_here.php?name=hello'">

Reading the Data (PHP)

See PHP Turotial for reading post and get: http://www.tizag.com/phpT/postget.php

Useful Links

http://php.net/manual/en/function.call-user-func.php http://php.net/manual/en/function.function-exists.php

Community
  • 1
  • 1
Menelaos
  • 23,508
  • 18
  • 90
  • 155
  • Is it always strictly necessary to have a file like `test.php. Thing is that I have ~20 php functions, and it would be of great help if there is any way to call a function from the same file that has the button. If that is not possible, I will do it as you suggested. – Mihai Bujanca Apr 11 '13 at 20:24
  • It is possible, you can use the function call_user_func($functionName) in order to call a specific function based on a variable from GET/POST. I am updating my post to add an example. – Menelaos Apr 11 '13 at 20:26
  • Any other tips or does it seem ok? :) – Menelaos Apr 11 '13 at 20:37
  • Thank you so much. Quite many new things for someone quite new to web development :) Thanks a lot, you got me out of trouble! – Mihai Bujanca Apr 11 '13 at 20:38
  • Ok, I would suggest for your situation using GET would be the most simple along with an HTML button. If you want to do it more advanced you can have your function in PHP echoing a reply and using the example GET Request via JQuery to display the reply in an alert. – Menelaos Apr 11 '13 at 20:42
  • Ok, now I have a little problem- sorry for that. I don't really know how to put them together. MY functions have no parameter to be passed- so the data field is not needed. However if all my buttons just do `.$post("test.php");`, how can I differentiate them for each button. An idea would be to pass a parameter to a switch and have a value for each of them- that could work. But I am still not really sure how to do it. Sorry again- I'm new to it, as i said – Mihai Bujanca Apr 11 '13 at 23:41
4

If you want to make a server request you should use AJAX, so you can send your desired parameters to the server and it can run whatever php you want with these parameters.

Example with pure javascript:

<input type="text" id="name" value="..."/>
<input type="text" id="location" value="..."/>
<input type="button" onclick="ajaxFunction();" value="Submit" />
<div id="ajaxDiv"></div>
<script type="text/javascript">    
    function ajaxFunction(){
        var ajaxRequest;  // The variable that makes Ajax possible!

        try{
            // Opera 8.0+, Firefox, Safari
            ajaxRequest = new XMLHttpRequest();
        } catch (e){
            // Internet Explorer Browsers
            try{
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try{
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e){
                    // Something went wrong
                    alert("Your browser broke!");
                    return false;
                }
            }
        }
        // Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function(){
            if(ajaxRequest.readyState == 4){
                var ajaxDisplay = document.getElementById('ajaxDiv');
                ajaxDisplay.innerHTML = ajaxRequest.responseText;
            }
        }
        var name = document.getElementById('name').value;
        var location = document.getElementById('location').value;
        var queryString = "?name=" + name + "&location=" + location;
        ajaxRequest.open("POST", "some.php" + queryString, true);
        ajaxRequest.send(null); 
    }
</script>

Example with jQuery Ajax: http://api.jquery.com/jQuery.ajax/

$.ajax({
  type: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
}).done(function( msg ) {
  alert( "Data Saved: " + msg );
});

You can have one file with functions called for example functions.php

functions.php

<?php
  myFunction($Name, $Location) {
      // etc...
  }
  myFunction2() {
  }
  // ... many functions
?>

some.php

<?php include("functions.php");    
$Name = $_POST['name'];
$Location = $_POST['location'];

myFunction($Name, $Location);

// make what you want with these variables...?>
bksi
  • 1,606
  • 1
  • 23
  • 45
  • can I just call a function in the same file, or do I need to make a some.php file? – Mihai Bujanca Apr 11 '13 at 20:11
  • You have to have controller. So in your case some.php is the action controller. It can call other function in your desire. – bksi Apr 11 '13 at 20:12
  • I was asking because I have plenty of functions- around 20, and I wouldn't really like to create 20 php files for each function. If needed, I will – Mihai Bujanca Apr 11 '13 at 20:16
  • However I still can't have two functions `myFunction1($Name, $Location)` `myFunction2($Name, $Location)` And call both functions within the same file with different parameters. Say I want first function to say "Hey," $Name "from" $Location And the second to say "Bye," $Name "from" $Location (i know the syntax is not correct, but you get the idea" First should be called for John, Boston and the second for Jill, London. Without making a file for each of the functions, if possible – Mihai Bujanca Apr 11 '13 at 20:32
  • You can. when you use include("functions.php") in your some.php file you have access to these functions. – bksi Apr 11 '13 at 20:36
3

Use ajax, a simple example,

HTML

<button id="button">Get Data</button>

Javascript

var button = document.getElementById("button");

button.addEventListener("click" ajaxFunction, false);

var ajaxFunction = function () {
    // ajax code here
}

Alternatively look into jquery ajax http://api.jquery.com/jQuery.ajax/

GriffLab
  • 2,076
  • 3
  • 20
  • 21
2
<?php
if (isset($_POST['str'])){
function printme($str){
echo $str;
}

printme("{$_POST['str']}");
}
?>
<form action="<?php $_PHP_SELF ?>" method="POST">
<input type="text" name="str" /> <input type="submit" value="Submit"/>
</form>
Uday Hiwarale
  • 4,028
  • 6
  • 45
  • 48
0

Use an AJAX Request on your PHP file, then display the result on your page, without any reloading.

http://api.jquery.com/load/ This is a simple solution if you don't need any POST data.

piry
  • 150
  • 1
  • 8
0

It depends on what function you want to run. If you need something done on server side, like querying a database or setting something in the session or anything that can not be done on client side, you need AJAX, else you can do it on client-side with JavaScript. Don't make the server work when you can do what you need to do on client side.

jQuery provides an easy way to do ajax : http://api.jquery.com/jQuery.ajax/

Virus721
  • 8,061
  • 12
  • 67
  • 123