How do I run PHP code when a user clicks on a link?

258,974

Solution 1

Yeah, you'd need to have a javascript function triggered by an onclick that does an AJAX load of a page and then returns false, that way they won't be redirected in the browser. You could use the following in jQuery, if that's acceptable for your project:

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

You could also do a post-back if you need to use form values (use the $.post() method).

Solution 2

As others have suggested, use JavaScript to make an AJAX call.

<a href="#" onclick="myJsFunction()">whatever</a>

<script>
function myJsFunction() {
     // use ajax to make a call to your PHP script
     // for more examples, using Jquery. see the link below
     return false; // this is so the browser doesn't follow the link
}

http://docs.jquery.com/Ajax/jQuery.ajax

Solution 3

If you haven't yet installed jquery (because you're just a beginner or something), use this bit of code:

<a href="#" onclick="thisfunction()">link</a>

<script type="text/javascript">
function thisfunction(){
    var x = new XMLHttpRequest();
    x.open("GET","function.php",true);
    x.send();
    return false;
}
</script>

Solution 4

I know this post is old but I just wanted to add my answer!

You said to log a user out WITHOUT directing... this method DOES redirect but it returns the user to the page they were on! here's my implementation:

// every page with logout button
<?php
        // get the full url of current page
        $page = $_SERVER['PHP_SELF'];
        // find position of the last '/'
        $file_name_begin_pos = strripos($page, "/");
        // get substring from position to end 
        $file_name = substr($page, ++$fileNamePos);
    }
?>

// the logout link in your html
<a href="logout.php?redirect_to=<?=$file_name?>">Log Out</a>

// logout.php page
<?php
    session_start();
    $_SESSION = array();
    session_destroy();
    $page = "index.php";
    if(isset($_GET["redirect_to"])){
        $file = $_GET["redirect_to"];
        if ($file == "user.php"){
            // if redirect to is a restricted page, redirect to index
            $file = "index.php";
        }
    }
    header("Location: $file");
?>

and there we go!

the code that gets the file name from the full url isn't bug proof. for example if query strings are involved with un-escaped '/' in them, it will fail.

However there are many scripts out there to get the filename from url!

Happy Coding!

Alex

Solution 5

You cant run PHP when a user clicks on a link without leaving the page unless you use AJAX. PHP is a serverside scripting language, meaning the second that the browser sees the page, there is no PHP in it.

Unlike Javascript, PHP is ran completely on the server, and browser wouldn't know how to interpret it if it bit them on the rear. The only way to invoke PHP code is to make a Page request, by either refreshing the page, or using javascript to go fetch a page.

In an AJAX Solution, basically the page uses javascript to send a page request to another page on your domain. Javascript then gets whatever you decide to echo in the response, and it can parse it and do what it wants from there. When you are creating the response, you can also do any backend stuff like updating databases.

Share:
258,974
chustar
Author by

chustar

I just hit 1500 reputation! - Wait, no I didn't... - Haha, yes I did!

Updated on June 19, 2021

Comments

  • chustar
    chustar almost 3 years

    I want to have a page run some PHP code when a user clicks on a link, without redirecting them. Is this possible with

    <a href=""></a>
    

    or with the javascript onclick event?

  • Roy Rico
    Roy Rico almost 15 years
    you should prob also return false from the function, so the HREF isn't followed.
  • Justin Poliey
    Justin Poliey almost 15 years
    No reason to downvote the guy just because he didn't use jQuery. Someone should probably edit the post to fix the link though.
  • Al.
    Al. almost 15 years
    "You cant run PHP when a user clicks on a link unless you use AJAX." Eh?
  • rpiaggio
    rpiaggio almost 15 years
    Exactly what I said. Unless you request a new page, you can't run PHP.
  • rpiaggio
    rpiaggio almost 15 years
    PHP is only ran when pages are requested.
  • ceejayoz
    ceejayoz almost 15 years
    Yes, but you can request a PHP page without AJAX. AJAX just lets you request it without leaving the page you're on. Your wording makes it sound like AJAX is required for all uses of PHP.
  • rpiaggio
    rpiaggio almost 15 years
    Ok, I fixed the wording. I thought it was a given that he was trying to not leave the page, but I guess some people don't feel like thinking.
  • Parrots
    Parrots almost 15 years
    You should at least add the non-jquery AJAX code example within your function, as it is you're just documenting the onclick functionality of javascript, which he already knew about :P
  • chustar
    chustar about 13 years
    2 years later, now i realize what makes this such a good answer!
  • nasty
    nasty over 11 years
    @Parrots : if I want to pass an ID to somepage.php, how could I achieve this? Lets say I change the "a" link to onclick="doSomething(<?php echo $id ?>);" and how can I pass it to the php page? Thanks
  • Louie Jay Jayme
    Louie Jay Jayme over 11 years
    by the way this one <a href="#" onclick="myJsFunction()">whatever</a> <script> function myJsFunction() { // use ajax to make a call to your PHP script // for more examples, using Jquery. see the link below return false; // this is so the browser doesn't follow the link } <-- refreshes the whole page so the one i gave does not :)
  • billrichards
    billrichards almost 10 years
    How could a php require() be triggered from a javascript click?
  • Will Brickner
    Will Brickner about 8 years
    @nasty store it in the session variable, or pass it as part of the url.
  • mathmaniac88
    mathmaniac88 almost 6 years
    How are you a beginner if you don't use jquery? I like to use Javascript and its not like its because I'm dumb
  • acenturyanabit
    acenturyanabit almost 6 years
    i guess you're something then :) hahaha
  • acenturyanabit
    acenturyanabit over 5 years
    in hindsight, +1. I've realised how much of a redundant dependency jQ is, especially seeing how far the web standard has come.