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?

10 Answers 10

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

4
  • 6
    you should prob also return false from the function, so the HREF isn't followed.
    – Roy Rico
    Aug 15, 2009 at 0:12
  • 5
    2 years later, now i realize what makes this such a good answer!
    – chustar
    Feb 28, 2011 at 9: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(<?php echo $id ?>);" and how can I pass it to the php page? Thanks
    – nasty
    Oct 1, 2012 at 2:30
  • 1
    @nasty store it in the session variable, or pass it as part of the url. Apr 18, 2016 at 2: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

3
  • 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. Aug 15, 2009 at 0: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, 2009 at 0: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, 2009 at 0: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>
3
  • 6
    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 Jul 31, 2018 at 4:33
  • 1
    i guess you're something then :) hahaha Jul 31, 2018 at 8:55
  • 2
    in hindsight, +1. I've realised how much of a redundant dependency jQ is, especially seeing how far the web standard has come. Feb 12, 2019 at 9:38
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

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.

5
  • 1
    "You cant run PHP when a user clicks on a link unless you use AJAX." Eh?
    – Al.
    Aug 15, 2009 at 0:17
  • Exactly what I said. Unless you request a new page, you can't run PHP. Aug 15, 2009 at 0:23
  • 1
    PHP is only ran when pages are requested. Aug 15, 2009 at 0:23
  • 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.
    – ceejayoz
    Aug 15, 2009 at 0:27
  • 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. Aug 15, 2009 at 0:49
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.

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

1
  • 2
    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 :) Oct 17, 2012 at 15:31
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>
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

1
  • 2
    How could a php require() be triggered from a javascript click? Jul 31, 2014 at 20:39

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.