40

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?

chustar
  • 12,225
  • 24
  • 81
  • 119

10 Answers10

96

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

Parrots
  • 26,658
  • 14
  • 59
  • 78
  • 6
    you should prob also return false from the function, so the HREF isn't followed. – Roy Rico Aug 15 '09 at 00:12
  • 5
    2 years later, now i realize what makes this such a good answer! – chustar Feb 28 '11 at 09:14
  • 2
    @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();" and how can I pass it to the php page? Thanks – nasty Oct 01 '12 at 02:30
  • 1
    @nasty store it in the session variable, or pass it as part of the url. – Will Brickner Apr 18 '16 at 02:29
10

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

CrazyMatt
  • 501
  • 1
  • 4
  • 12
Roy Rico
  • 3,683
  • 6
  • 35
  • 36
  • 1
    No reason to downvote the guy just because he didn't use jQuery. Someone should probably edit the post to fix the link though. – Justin Poliey Aug 15 '09 at 00:12
  • Thanks justin, fixed the link. I just added the link to jquery, but not the actual code just in case it wasn't an option. Not everyone gets to use Jquery, no matter how much they want to (stupid legal contracts!) – Roy Rico Aug 15 '09 at 00:15
  • 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 – Parrots Aug 15 '09 at 00:55
8

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>
acenturyandabit
  • 1,188
  • 10
  • 24
5

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

AlexMorley-Finch
  • 6,785
  • 15
  • 68
  • 103
4

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.

Tyler Carter
  • 60,743
  • 20
  • 130
  • 150
2

Well you said without redirecting. Well its a javascript code:

<a href="JavaScript:void(0);" onclick="function()">Whatever!</a>

<script type="text/javascript">
function confirm_delete() {
    var delete_confirmed=confirm("Are you sure you want to delete this file?");

    if (delete_confirmed==true) {
       // the php code :) can't expose mine ^_^
    } else { 
       // this one returns the user if he/she clicks no :)
       document.location.href = 'whatever.php';
    }
}
</script>

give it a try :) hope you like it

Benoit Garret
  • 14,027
  • 4
  • 59
  • 64
Louie Jay Jayme
  • 169
  • 3
  • 13
  • 2
    by the way this one whatever – Louie Jay Jayme Oct 17 '12 at 15:31
2

There is the only better way is AJAX as everyone is suggest in their posts. The alternative is using IFrames like below:

<iframe name="f1" id="f1"> </iframe>

<a href='yourpage.php' target='f1'>Click </a>

Now you will get the output in IFrame (you can place IFrame wherever you need in the page or event hide it and the result from the script).

Hope for non Ajax solution this is better.

user7116
  • 63,008
  • 17
  • 141
  • 172
AjayR
  • 4,169
  • 4
  • 44
  • 78
0

either send the user to another page which does it

<a href="exec.php">Execute PHP</a>

or do it with ajax

<script type="text/javascript">
// <![CDATA[
    document.getElementById('link').onclick = function() {
        // call script via ajax...
        return false;
    }
// ]]>
</script>
...
<a href="#" id="link">Execute PHP</a>
Tom
  • 6,947
  • 7
  • 46
  • 76
0
<a href='javascript:void(0)' id='yourId'>Click Me</a>

$(document).ready(function() {       
    $("#yourId").click(function() {
       $.get("yourpage.php");
       return false;;
    });
});
-1

This should work as well

<a href="#" onclick="callFunction();">Submit</a>

<script type="text/javascript">

function callFunction()
{
  <?php require("functions.php");  ?>
}
</script>

Thanks,

cowtipper

Jon
  • 2,932
  • 2
  • 23
  • 30
John
  • 619
  • 2
  • 9
  • 24