html – How do I execute a PHP function in an onclick event? – Education Career Blog

I have some HTML files, and what I want to do, is put something like the following, inside the <head> section of the html document:

<script href="myphpfile.php" />

and then somewhere on my page, I want to call a PHP function from an onclick event, like so:

<a onclick="performPhpFunction();" href="javascript:void(0);">Do something</a>

How can I do this?

I don’t know why, but when searching for a solution tonight, I cannot seem to find one, and I have seen this many times, but forgot how it was done, and now I don’t remember which websites I saw it on.

,

You can load the PHP File over AJAX with JS

jQuery

$("#link").click(function(){
      $.ajax({
           url: "myphpfile.php"
      });
});

,

Umm….PHP doesn’t work this way. PHP is server-side. You cannot directly call PHP functions from an onclick hander. That only can call javascript (which is client-code) code. What you can do is call the PHP function via an AJAX GET call.

,

You can’t call PHP functions from javascript directly. You can either use AJAX to call back to a PHP page that does what you want, like Rocket and Fincha have said or you can get PHP to output the javascript, and change it based on what the user sends to you.

To do the latter; in the PHP file you’ll need a line like

<?php

header('Content-type: text/javascript');

?>

And that has to be BEFORE you output anything.

Then below that you generate the javascript, as you would any javascript file, but you can use server side data and include it in your file.

function AJavascriptFunction()
{
    alert(<?= $_GET'getvar' ?>);
}

Then in your html or PHP page you can do

<a onclick="AJavascriptFunction();" href="javascript:void(0);">Do something</a>

I do not recommend this. Use AJAX

Leave a Comment