Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger PHP function by clicking HTML link

Tags:

html

function

php

Is it possible to trigger a PHP function by just clicking a link? Or should I stick with the form submit method? If clicking the link will work, where should the link refer to?

Here is a sample code:

<?php
    session_start();
    function listMe($username){
        $username = mysql_real_escape_string($username);
        $query = mysql_query("INSERT INTO List (Usernames) VALUES ('$username')") or die(mysql_error());
    }
?>

<html>
    <head>
        <title>SAMPLE</title>
    </head>
    <body>
        <a href="**__???___**">Add my username to the list</a>
        <?php 
            listMe($_SESSION['Username']); 
        ?>
    </body>
</html>

Maybe someone can point me in the right direction. Thanks!

like image 727
fart-y-goer Avatar asked Nov 30 '22 15:11

fart-y-goer


2 Answers

You can do this by means of loading the entire page over again by the use of form submission, or by loading specific page contents directly into the page without needing to go from page to page. The second method is called "AJAX" (Asynchoronous Javascript and XML). Here are two examples, one of each specified.

Form submission approach

form.php

<?php
function get_users(){
}
if(isset($_GET['get_users']))
{
    get_users();
}
?>
...
<form method="get">
    <input type="hidden" name="get_users">
    <input type="submit">
</form>

AJAX approach

ajax_file.php

<?php
function call_me(){
    // your php code
}
call_me();
?>

form.html

<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
    var xmlhttp;
    if (window.XMLHttpRequest)
    {
        xmlhttp = new XMLHttpRequest();
    }
    else
    {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function()
    {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            // do something if the page loaded successfully
        }
    }
    xmlhttp.open("GET","ajax_file.php",true);
    xmlhttp.send();
}
</script>
</head>
<body>
<a href="#" onclick="loadXMLDoc()">click to call function</a>
</body>
</html>
like image 173
Zack Zatkin-Gold Avatar answered Dec 09 '22 18:12

Zack Zatkin-Gold


HTML

<a href="?list_me">list me</a>

PHP

<?php
if (isset($_GET['list_me'])) listMe();
like image 43
powerbuoy Avatar answered Dec 09 '22 17:12

powerbuoy