114

I am searching for a simple solution to call a PHP function only when a-tag is clicked.

PHP:

function removeday() { ... }

HTML:

<a href="" onclick="removeday()" class="deletebtn">Delete</a>

UPDATE: the html and PHP code are in the same PHP file

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
Mike
  • 3,200
  • 5
  • 22
  • 33
  • 8
    HTML runs Javascript functions, which run on the client. PHP runs on the server. You need to learn about AJAX. – Barmar Oct 11 '13 at 16:34
  • but why AJAX? the whole code is in the same PHP file. – Mike Oct 11 '13 at 16:42
  • 3
    Why AJAX? Well, in order to find out that, you can simply run any php script and see the code of its execution. Again - **Ajax is the only way you can do that**. – Yang Oct 11 '13 at 17:30
  • 4
    The checked answer will work out to looking like a button if you use `Delete` where the action is caught and runs the removeday() function similar to `if($action == 'removeday'){ removeday(); }`. I know this is late, but I figure it could still help someone with this issue. C§ – CSS Oct 04 '15 at 02:36

9 Answers9

173

First, understand that you have three languages working together:

  • PHP: It only runs by the server and responds to requests like clicking on a link (GET) or submitting a form (POST).

  • HTML & JavaScript: It only runs in someone's browser (excluding NodeJS).

I'm assuming your file looks something like:

<!DOCTYPE HTML>
<html>
<?php
  function runMyFunction() {
    echo 'I just ran a php function';
  }

  if (isset($_GET['hello'])) {
    runMyFunction();
  }
?>

Hello there!
<a href='index.php?hello=true'>Run PHP Function</a>
</html>

Because PHP only responds to requests (GET, POST, PUT, PATCH, and DELETE via $_REQUEST), this is how you have to run a PHP function even though they're in the same file. This gives you a level of security, "Should I run this script for this user or not?".

If you don't want to refresh the page, you can make a request to PHP without refreshing via a method called Asynchronous JavaScript and XML (AJAX).

That is something you can look up on YouTube though. Just search "jquery ajax"

I recommend Laravel to anyone new to start off right: http://laravel.com/

Marta
  • 23
  • 1
  • 10
Michael J. Calkins
  • 32,082
  • 15
  • 62
  • 91
  • 5
    Just to mention, I'm assuming you're fairly new to PHP I'd like to recommend http://laravel.com/ as a framework. Personally I would have loved to skip the entire 'learning generic php' and go straight to a powerful framework. This is the one I use now as well. – Michael J. Calkins Oct 11 '13 at 19:50
  • 6
    Man, thank you so much, your answer doesn't just helped me with this doubt, but it also made me understand php so much better! Thank you again! – Feel The Noise Jan 14 '14 at 12:26
  • Thanks I am looking for this . How can I implement this with wordpress – Firefog Nov 26 '15 at 14:56
  • 2
    Thank you i'll start concentrate on laravel because of your mention. – Mohamed Abulnasr May 10 '17 at 12:56
  • 3
    `If you don't want to refresh the page, you can make a request to PHP without refreshing via a method called Asynchronous JavaScript and XML (AJAX).` Well he did include `onclick` in the question, so it's pretty clear the goal is to perform an action without refreshing. ¬_¬ – Synetech Sep 17 '18 at 15:47
45

In javascript, make an ajax function,

function myAjax() {
      $.ajax({
           type: "POST",
           url: 'your_url/ajax.php',
           data:{action:'call_this'},
           success:function(html) {
             alert(html);
           }

      });
 }

Then call from html,

<a href="" onclick="myAjax()" class="deletebtn">Delete</a>

And in your ajax.php,

if($_POST['action'] == 'call_this') {
  // call removeday() here
}
Anshad Vattapoyil
  • 23,145
  • 18
  • 84
  • 132
  • Just to clarify: `type` should be used in jQuery earlier than 1.9.0, while `method` is an alias and should be used on newer versions. – alejnavab Jan 11 '17 at 02:22
  • 1
    The same solution also provided in Vanilla JavaScript helps beginners much better. I say this as a more experienced user of JavaScript who was once a complete beginner but proficient with PHP. – Ken Ingram Apr 07 '19 at 04:35
13

It can be done and with rather simple php if this is your button

<input type="submit" name="submit>

and this is your php code

if(isset($_POST["submit"])) { php code here }

the code get's called when submit get's posted which happens when the button is clicked.

Vamps
  • 167
  • 1
  • 5
11

You will have to do this via AJAX. I HEAVILY reccommend you use jQuery to make this easier for you....

$("#idOfElement").on('click', function(){

    $.ajax({
       url: 'pathToPhpFile.php',
       dataType: 'json',
       success: function(data){
            //data returned from php
       }
    });
)};

http://api.jquery.com/jQuery.ajax/

A.O.
  • 3,733
  • 6
  • 30
  • 49
  • 1
    why AJAX? it would be the same PHP file (I updated my question) – Mike Oct 11 '13 at 16:40
  • 3
    Because of what @Barmar explained, it doesn't work like that. You'll want to place the php in a separate file, then reference that file in your AJAX request. – A.O. Oct 11 '13 at 16:43
  • 1
    The "url:" parameter references external php file, how can I reference php function in the same file? – Joe Doe Dec 15 '14 at 18:56
  • 2
    @JoeDoe you cannot, place the function in an external file – A.O. Dec 16 '14 at 18:34
4

Solution without page reload

<?php
  function removeday() { echo 'Day removed'; }

  if (isset($_GET['remove'])) { return removeday(); }
?>


<!DOCTYPE html><html><title>Days</title><body>

  <a href="" onclick="removeday(event)" class="deletebtn">Delete</a>

  <script>
  async function removeday(e) {
    e.preventDefault(); 
    document.body.innerHTML+= '<br>'+ await(await fetch('?remove=1')).text();
  }
  </script>

</body></html>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
2

This is the easiest possible way. If form is posted via post, do php function. Note that if you want to perform function asynchronously (without the need to reload the page), then you'll need AJAX.

<form method="post">
    <button name="test">test</button>
</form>

    <?php
    if(isset($_POST['test'])){
      //do php stuff  
    }
    ?>
csandreas1
  • 2,026
  • 1
  • 26
  • 48
  • `Note that if you want to perform function asynchronously (without the need to reload the page), then you'll need AJAX.` Well the `onclick` would indicate that's exactly what he wants. ¬_¬ – Synetech Sep 17 '18 at 15:39
2

Here´s an alternative with AJAX but no jQuery, just regular JavaScript:

Add this to first/main php page, where you want to call the action from, but change it from a potential a tag (hyperlink) to a button element, so it does not get clicked by any bots or malicious apps (or whatever).

<head>
<script>
  // function invoking ajax with pure javascript, no jquery required.
  function myFunction(value_myfunction) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("results").innerHTML += this.responseText; 
        // note '+=', adds result to the existing paragraph, remove the '+' to replace.
      }
    };
    xmlhttp.open("GET", "ajax-php-page.php?sendValue=" + value_myfunction, true);
    xmlhttp.send();
  }

</script>
</head>

<body>

  <?php $sendingValue = "thevalue"; // value to send to ajax php page. ?> 

  <!-- using button instead of hyperlink (a) -->
  <button type="button" onclick="value_myfunction('<?php echo $sendingValue; ?>');">Click to send value</button>

  <h4>Responses from ajax-php-page.php:</h4>
  <p id="results"></p> <!-- the ajax javascript enters returned GET values here -->

</body>

When the button is clicked, onclick uses the the head´s javascript function to send $sendingValue via ajax to another php-page, like many examples before this one. The other page, ajax-php-page.php, checks for the GET value and returns with print_r:

<?php

  $incoming = $_GET['sendValue'];

  if( isset( $incoming ) ) {
    print_r("ajax-php-page.php recieved this: " . "$incoming" . "<br>");
  } else {
    print_r("The request didn´t pass correctly through the GET...");
  }

?>

The response from print_r is then returned and displayed with

document.getElementById("results").innerHTML += this.responseText;

The += populates and adds to existing html elements, removing the + just updates and replaces the existing contents of the html p element "results".

andiOak
  • 356
  • 3
  • 9
1

Try to do something like this:

<!--Include jQuery-->
<script type="text/javascript" src="jquery.min.js"></script> 

<script type="text/javascript"> 
function doSomething() { 
    $.get("somepage.php"); 
    return false; 
} 
</script>

<a href="#" onclick="doSomething();">Click Me!</a>
Mystical
  • 2,505
  • 2
  • 24
  • 43
Simpel
  • 103
  • 1
  • 1
  • 7
-4

Try this it will work fine. This will work without form tags and button tag.

<div onclick="window.location='?hello=true';">
<?php
    if(isset($_GET['hello'])) {
        hello();
    }
    function hello()
    {
        echo "hello world";
    }
 ?>
Jitesh Prajapati
  • 2,533
  • 4
  • 29
  • 51
Vidya
  • 382
  • 1
  • 6
  • 17
  • 2
    That doesn't work (even if you clean it up), but moreover, it _can't_ work. The PHP code is pre-processed when loaded; it is not run at runtime. – Synetech Sep 17 '18 at 15:43
  • Either you didn't read the question or you didn't test your code as this would not work. – Mr PizzaGuy Jan 24 '20 at 01:57