views:

43

answers:

3

Hi,

I want to post values to a page through a hyperlink in another page. Is it possible to do that?

Let's say I have a page results.php which has the starting line,

<?php 
if(isset($_POST['posted_value']))
{
echo "expected value"; 
// do something with the data
}
else
{
echo "no the value expected";
}

If from another page say link.php I place a hyperlink like this:

<a href="results.php?posted_value=1"> , will this be accepetd by the results page?

If instead if I replace the above starting line with

if(isset($_REQUEST['posted_value'])), will this work?

I believe the above hyperlink evaluates to GET, but since the only visibility difference between GET and POST that is you can see parameters in the address bar with GET

But, is there any other way to place a hyperlink which can post values to a page? or can we use jquery in the place of hyperlink to POST the values?

Can anyone please suggest me something on this please?

Thanks.

A: 

You can't make a POST request using a hyperlink. This will always issue a GET request. You need to use javascript to do that. With jQuery is very easy using $.post or $.ajax method.

Sample code:

html:

<a id="MyLink" href="#">Link</a>

javascript:

$(function() {

    $("MyLink").click(function () {
      $.post("test.php", { name: "John", time: "2pm" } );
    });
});

Of course you can do everything in html code, but it isn't recommended:

<a href='#' onclick='$.post("test.php", { name: "John", time: "2pm" } )'>Link</a>
kgiannakakis
not sure how to output a hyperlink with jquery to POST values
JPro
is there any real difference if I place this `.click` javascript code in the `head` region or in the `body`?
JPro
It is better to put it in the head section. In this case I don't think it will make a difference though.
kgiannakakis
A: 

You can see the query string (and consequently $_GET) whether the request type is GET or POST. POST passes additional parameters to the script's standard input which are parsed to generate $_POST and $_FILES. Clicking a hyperlink generates a GET request unless you override it using JavaScript by simulating submission of a POST form.

Ignacio Vazquez-Abrams
A: 

Your assumptions are correct. Hyperlinks cannot POST to a PHP script, only pass parameters as GET. You can use the $.ajax method in jQuery as kgiannakakis suggested, which will POST to a PHP script, but then you would only change parts of a page and not the entire page.

Another solution is to use a form and button - you can style it as link if you like.

<style>
.formlink {
    display: inline;
}
.formlink input.submit {
    display: inline;
    background: transparent none;
    border: 0;
    color: blue;
}
</style>

<form class="formlink" method="post" action="script.php">
    <input type="hidden" name="posted_value" value="1" />
    <input type="submit" value="Post 1" class="submit" />
</form>
DisgruntledGoat