user1086516
user1086516

Reputation: 877

How to POST to another page without user interaction?

So I have a situation where a user submits some data through forms, then clicks a submit button which directs to a separate .php page where processing is done. After the processing is done I need to go to another .php page and send along with it a POST variable I already know the value of.

In html I would make a form with input(s) and a submit button. How do you do that in php without having a user click a submit button ?

Upvotes: 0

Views: 4501

Answers (5)

aiman9000
aiman9000

Reputation: 55

The simplest way I can think of is to put the input from the previous page in a form with hidden input type.

For example:

<?php
$post_username = $_POST['username'];
?>

<form id="form1" action="page2.php" method="post">
<input type="hidden" id="hidden_username" value="<?php echo $post_username; ?>" />
</form>

<script>
document.getElementById("form1").submit();
</script>

Upvotes: 2

user1086516
user1086516

Reputation: 877

Amadan was on to something.

Just stuck this HTML add the end of my php:

<html>
<form id="form" action="webAddressYouWantToRedirectTo.php" method="POST">
<input type="hidden" name="expectedPOSTVarNameOnTheOtherPage" value="<?php echo $varYouMadePreviouslyInProcessing ?>">
</form>
<script>
document.getElementById("form").submit();
</script>
</html>

Upvotes: 0

wangXL
wangXL

Reputation: 66

A useful way is to use the CURL method.

$url = "test.php";
$post_data = array(
    "data1"=>$value1,
    ....
);
$ch = curl_init();

curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
//we are doing a POST request
curl_setopt($ch,CURLOPT_POST,1);
//adding the post variables to the request
curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);

$output = curl_exec($ch);
curl_close($ch);

echo $output;//or do something else with the output

Upvotes: 0

Abraham K
Abraham K

Reputation: 634

$.ajax({
  type: "POST",
  url: "YOUR PHP",
  data: { PARAMS }
}).done(function( msg ) {
    if(SUCCESS)
    {
$.ajax({
  type: "POST",
  url: "ANOTHER PAGE",
  data: { PARAM }
})
  .done(function( msg ) {
//Process Here
  });

You can post arguments in between if you use Json or Xml. Hope it helps !

Upvotes: 0

Alex
Alex

Reputation: 4774

    $url = 'http://server.com/path';
$data = array('key1' => 'value1', 'key2' => 'value2');

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    ),
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

var_dump($result);

Code taken from here, another question which may provide you with some useful answers.

Upvotes: 0

Related Questions