[javascript] Execute PHP function with onclick

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

This question is related to javascript php ajax onclick

The answer is


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/


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.


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
}

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  
    }
    ?>

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>

Try this it will work fine.

<script>
function echoHello(){
 alert("<?PHP hello(); ?>");
 }
</script>

<?PHP
FUNCTION hello(){
 echo "Call php function on onclick event.";
 }

?>

<button onclick="echoHello()">Say Hello</button>

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".


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>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to onclick

How to use onClick with divs in React.js React prevent event bubbling in nested components on click React onClick function fires on render Run php function on button click Passing string parameter in JavaScript function Simple if else onclick then do? How to call a php script/function on a html button click Change Button color onClick RecyclerView onClick javascript get x and y coordinates on mouse click