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!
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>
HTML
<a href="?list_me">list me</a>
PHP
<?php
if (isset($_GET['list_me'])) listMe();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With