Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post variable with onclick?

Tags:

html

php

How can I $_POST information from one page to another by clicking a link? No forms or submit boxes, just if the end user clicks on a link, it will post pertinent information in the opened link.

Pseudocode, but:

//On first page
<a href="./page.php" onclick="post" value="var">Click me!</a>
...
//On the page the above links to
$variable = $_POST["var"];

Something that I considered is the following, which although less than pretty, works. I'd like it so it's a post and not a get.

//On first page
<a href="./page.php?var=<?php echo $variable; ?>">Click me!</a>
...
//On second page
$variable = $_GET["var"];
like image 579
gator Avatar asked Nov 19 '25 01:11

gator


2 Answers

Try this :

<a href="link.php" class="post">submit content using link</a>

 <script type="text/javascript">
            jQuery(document).ready(function($){
                $(".post").on("click",function(){
                    $.ajax({
                        url: "http://www.yourwebsite.com/page.php",
                        type: "POST",
                        data: { name: "John", location: "Boston" },
                        success: function(response){
                              //do action  
                        },
                        error: function(){
                              // do action
                        }
                    });
                });
            });
        </script>

Reference Link

like image 100
Surinder ツ Avatar answered Nov 20 '25 15:11

Surinder ツ


Not sure why you don't do this:

//On first page

<a href="./page.php?var=value">Click me!</a>

... //On the page the above links to

$variable = $_GET['var'];

UPDATE:

As per your above comment:

GET displays the information in the URL, whereas with POST it does not. I do not wish an end user to just edit the URL with whatever value they wish. @popnoodles, when the user would click the hyperlink, it would direct to a new page. – riista

You are trying to do this for security reasons, as such neither approach is a good way to do it using GET or AJAX is both unsafe as both can be tampered with. You need to re-think what you are trying to protect and how you can check if the data submitted is valid.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!