javascript – Execute PHP function with onclick

javascript – Execute PHP function with onclick

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 someones browser (excluding NodeJS).

Im 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 theyre in the same file. This gives you a level of security, Should I run this script for this user or not?.

If you dont 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/

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
}

javascript – Execute PHP function with onclick

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/

Leave a Reply

Your email address will not be published.