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 ?
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>
$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.
$.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 !
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
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>
Related
This question already has answers here:
how to remember input data in the forms even after refresh page?
(10 answers)
Closed 4 years ago.
So i got this form:
<form action="send.php" method="post">
Dogecoin-address: <input type="text" name="address"/><br>
<input type="submit" name="Submit" value="Submit">
</form>
<?php
// starting the session
session_start();
if (isset($_POST['address'])) {
$_SESSION['address'] = $_POST['Submit'];
}
?>
i want to keep"address"data here: when i reload this:
$url = 'https://faucethub.io/api/v1/send?
api_key=4b21af7e916403216ffb11e523f912bc¤cy=DOGE&amount=1&to='.
$_POST['address'];
$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);
if ($result === FALSE) { /* Handle error */ }
var_dump($result);
?>
when the user submit his "address" i want his "address"remain/save on the second code when he refreshes!
how is this possible by using $_SESSION?OR by using cookies?or any other way?
i'm new to php and i don't know how to use it
Change your $_POST value to address instead of Submit. This way your address is stored inside the $_SESSION['address'] variable.
You can access the address by using $_SESSION['address'].
I'm totally new to php. I'm trying to echo the value of an input field into a an array but it doesn't seem to work.e.g echo the value of hidden-input as the value for origin in the array. How can I achieve this?
<form method="post">
<!-- Set type -> Hidden, if you want to make that input field hidden.
You really should use better "names" for the input fields -->
// I populate the value with jQuery //
<input id="hidden-input" type="hidden" name="from" value="">
</form>
<?php
$params = array(
'origin' => $_post['from'],
'destination' => um_user('postal_zip_code'),
'sensor' => 'true',
'units' => 'imperial'
);
$params_string='';
// Join parameters into URL string
foreach($params as $var => $val){
$params_string .= '&' . $var . '=' . urlencode($val);
}
// Request URL
$url = "http://maps.googleapis.com/maps/api/directions/json?".ltrim($params_string, '&');
// Make our API request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($curl);
curl_close($curl);
// Parse the JSON response
$directions = json_decode($return);
//echo"<pre>";
//print_r($directions);
// Show the total distance
echo '<p><strong>Total distance:</strong> ' . $directions->routes[0]->legs[0]->distance->text . '</p>';
?>
<div id class="distance"></div>
The jQuery that inserts the value looks like below and it works perfectly. It inserts it as supposed but the php doesn't pass it to the array
$(document).ready(function() {
var someName = $('.um-field-postal_zip_code .um-field-value').text();
$("input#hidden-input").attr("value", someName);
});
<form method="post">
<!-- Set type -> Hidden, if you want to make that input field hidden.
You really should use better "names" for the input fields -->
<input id="hidden-input" type="hidden" name="from" value="">
</form>
<?php
$params = array(
'origin' => $_POST['from'], // <- Now it should be empty, because nothing is inside
'destination' => um_user('postal_zip_code'),
'sensor' => 'true', // If you write 'false' it's still true, because the string is filled. Please use correct bools like true / false without the quotes // 'sensor' => true
'units' => 'imperial'
);
?>
You also need something to "send" or "activate" the form.
<input type="submit" name="sendForm" value="Send Form"/>
So the input form looks like:
<form method="post">
<!-- Set type -> Hidden, if you want to make that input field hidden.
You really should use better "names" for the input fields -->
<input id="hidden-input" type="hidden" name="from" value="">
<input type="submit" name="sendForm" value="Send Form"/>
</form>
Let me know, if you need more help!
html
<form method="post" action="yourpage.php">
<input id="hidden-input" name="from" value="">
<input type="submit" value="Submit" name="submit_button">
</form>
php
<?php
//if your form is submitted fill the array
if(isset($_POST['submit_button'])){
$params = array(
'origin' => $_POST['from'],
'destination' => 'postal_zip_code',
'sensor' => 'true',
'units' => 'imperial'
);
//print array
foreach($params as $index=>$value){
print $index." :".$value;
}
}
?>
You can not fetch data from form without refresh of page. Actually you are trying to fetch data from hidden input which is coming from jquery.
First remove form html and make ajax call
You need to set ajax
$(document).ready(function() {
var someName = $('.um-field-postal_zip_code .um-field-value').text();
if(!someName==''){//check somename is blank or not
//make ajax call
$.ajax({url: "url of your php code",
data : 'someName',
type : 'post',
success: function(result){
}});
}
});
In php file fetch data using $_post
echo $data = $_post['data'];//this is your origin
Now continue with your code
$params = array(
'origin' => $data,
'destination' => um_user('postal_zip_code'),
'sensor' => 'true',
'units' => 'imperial'
);
$params_string='';
// Join parameters into URL string
foreach($params as $var => $val){
$params_string .= '&' . $var . '=' . urlencode($val);
}
// Request URL
$url = "http://maps.googleapis.com/maps/api/directions/json?".ltrim($params_string, '&');
// Make our API request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($curl);
curl_close($curl);
// Parse the JSON response
$directions = json_decode($return);
//echo"<pre>";
//print_r($directions);
// Show the total distance
echo '<p><strong>Total distance:</strong> ' . $directions->routes[0]->legs[0]->distance->text . '</p>';
I need to post a json to a method in codeigniter 2.2.0, that post was made in a view with a jquery-ajax, like this:
function envia_mail_ajax(numero, form_data, ruta){
var iddiv="#mail_"+numero;
window.setTimeout(
function(){
$.ajax({
url: "<?php site_url('emailmasivo'); ?>/" +ruta+ "/" +numero,
cache: false,
type: 'POST',
data: form_data,
dataType: "json",
success: function(html){
$( iddiv ).append(html.mensaje+"\n"+'<br />');
}
});
}, 600);
}
and it was used like this (within a loop over i):
envia_mail_ajax(i,
{para:correos_e[i],id_masivos:id_masivos_e[i],id_mat_referencia:id_mat_referencia_e[i],
id_tipouser:id_tipouser_e[i],nombre:nombres_e[i], sexo:sexos_e[i], matricula:matriculas_e[i], passa:passa_e[i],id_cuenta:cuenta_id},
"<?php echo $r_ajax; ?>");
now, I´m writing all that in such a way that no view will be needed, in order to make it possible to run it from the terminal´s commands line, essentially, this is telling me to POST to the controller´s method "<?php echo site_url('emailmasivo'); ?>/" +ruta+ "/" +numero the data in form_data; to do this I wrote a method based in a lecture I found here POST json to PHP, my method is:
function procesaInfo($Arreglo, $numero){
$url = $Arreglo['r_ajax'];
$ch = curl_init(echo site_url('emailmasivo') . $url . "/" . $numero);
$jsonData = array(
'para' => $Arreglo['lista_mails']['correos_e'][$numero],
'id_masivos' => $Arreglo['lista_mails']['id_masivos_e'][$numero],
'id_mat_referencia' => $Arreglo['lista_mails']['id_mat_referencia_e'][$numero],
'id_tipouser' => $Arreglo['lista_mails']['id_tipouser_e'][$numero],
'nombre' => $Arreglo['lista_mails']['nombres_e'][$numero],
'sexo' => $Arreglo['lista_mails']['sexos_e'][$numero],
'matricula' => $Arreglo['lista_mails']['matriculas_e'][$numero],
'matriculas_e' => $Arreglo['lista_mails']['passa_e'][$numero],
//'id_cuenta' => $Arreglo['lista_mails']['cuenta_id'][$numero]
'id_cuenta' => $Arreglo['id_cuenta']
);
$jsonDataEncoded = json_encode($jsonData);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
}
the problem is that when I try to use that method like this:
function proceso_envia($nuevoArreglo){
$hola = "hola";
//echo $cuenta_id = $nuevoArreglo['id_cuenta'].PHP_EOL;
//print_r($nuevoArreglo['lista_mails']['correos_e']);
if(count($nuevoArreglo['lista_mails']['correos_e']) != 0){
$j = 0;
for($i = $nuevoArreglo['ini'] ; $i < count($nuevoArreglo['lista_mails']['correos_e']) ; $i++){
if($nuevoArreglo['lista_mails']['correos_e'][$i] != NULL){
$j = $j+1;
sleep(1);
echo "si llega!".PHP_EOL;
$this->procesaInfo($nuevoArreglo, $i);
}
}
}
}
it seems that no data are being POST to my method, and worst, not even the method is being reached, how do I know? well, I used an echo "I´m here!"; at the very beginning of the proceso_envia function, and nothing was displayed... am I doing it right? how do I post correctly data to a CI method in a controller? thanx i.a. for your help!
What I am trying to achieve is:
I have a web site to which I have full source code access. The pages in this web site has been created using velocity templates and I have a page with the following form.
<h3>form data</h3>
<form action="$portalPath/test" method="post">
<input type="text" name="text" value="$!self.getTextFromFormData()" />
<input type="submit" />
</form>
Now from another application written in php, I want to make an http request to this page and get a file downloaded. (Which is an html file). To do that, I wrote following code from the other web application :
$url = 'http://localhost/portal/default/test';
$data = array('filename.html');
$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);
But the result shows the html source of the template I access(i.e. test) and not the html file I want to download. What I want to do is to make an http request to auto enter the file name to the form and make the form auto submit the request and process it and get the required html file downloaded as the result. I don't know if this is possible or if possible whether this is the correct way. If this can be done using curl, that's better. Any idea will be highly appreciated.
See: how can I post an external form using PHP?
So, from the referenced URL:
<?php
$url = 'http://localhost/portal/default/test';
$fields = array(
'text'=>urlencode($value_for_field_text),
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
// Initialize curl
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post
$result = curl_exec($ch);
// Results of post in $result
?>
I have an online gateway which requires an HTML form to be submitted with hidden fields. I need to do this via a PHP script without any HTML forms (I have the data for the hidden fields in a DB)
To do this sending data via GET:
header('Location: http://www.provider.com/process.jsp?id=12345&name=John');
And to do this sending data via POST?
You can't do this using PHP.
As others have said, you could use cURL - but then the PHP code becomes the client rather than the browser.
If you must use POST, then the only way to do it would be to generate the populated form using PHP and use the window.onload hook to call javascript to submit the form.
here is the workaround sample.
function redirect_post($url, array $data)
{
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function closethisasap() {
document.forms["redirectpost"].submit();
}
</script>
</head>
<body onload="closethisasap();">
<form name="redirectpost" method="post" action="<? echo $url; ?>">
<?php
if ( !is_null($data) ) {
foreach ($data as $k => $v) {
echo '<input type="hidden" name="' . $k . '" value="' . $v . '"> ';
}
}
?>
</form>
</body>
</html>
<?php
exit;
}
A better and neater solution would be to use $_SESSION:
Using the session:
$_SESSION['POST'] = $_POST;
and for the redirect header request use:
header('Location: http://www.provider.com/process.jsp?id=12345&name=John', true, 307;)
307 is the http_response_code you can use for the redirection request with submitted POST values.
Another solution if you would like to avoid a curl call and have the browser redirect like normal and mimic a POST call:
save the post and do a temporary redirect:
function post_redirect($url) {
$_SESSION['post_data'] = $_POST;
header('Location: ' . $url);
}
Then always check for the session variable post_data:
if (isset($_SESSION['post_data'])) {
$_POST = $_SESSION['post_data'];
$_SERVER['REQUEST_METHOD'] = 'POST';
unset($_SESSION['post_data']);
}
There will be some missing components such as the apache_request_headers() will not show a POST Content header, etc..
It would involve the cURL PHP extension.
$ch = curl_init('http://www.provider.com/process.jsp');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "id=12345&name=John");
curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1); // RETURN THE CONTENTS OF THE CALL
$resp = curl_exec($ch);
/**
* Redirect with POST data.
*
* #param string $url URL.
* #param array $post_data POST data. Example: array('foo' => 'var', 'id' => 123)
* #param array $headers Optional. Extra headers to send.
*/
public function redirect_post($url, array $data, array $headers = null) {
$params = array(
'http' => array(
'method' => 'POST',
'content' => http_build_query($data)
)
);
if (!is_null($headers)) {
$params['http']['header'] = '';
foreach ($headers as $k => $v) {
$params['http']['header'] .= "$k: $v\n";
}
}
$ctx = stream_context_create($params);
$fp = #fopen($url, 'rb', false, $ctx);
if ($fp) {
echo #stream_get_contents($fp);
die();
} else {
// Error
throw new Exception("Error loading '$url', $php_errormsg");
}
}
Use curl for this. Google for "curl php post" and you'll find this: http://www.askapache.com/htaccess/sending-post-form-data-with-php-curl.html.
Note that you could also use an array for the CURLOPT_POSTFIELDS option. From php.net docs:
The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with # and use the full path. This can either be passed as a urlencoded string like 'para1=val1¶2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data.
Your going to need CURL for that task I'm afraid. Nice easy way to do it here: http://davidwalsh.name/execute-http-post-php-curl
Hope that helps
Alternatively, setting a session variable before the redirect and test it in the destination url, can solve this problem for me.
You have to open a socket to the site with fsockopen and simulate a HTTP-Post-Request.
Google will show you many snippets how to simulate the request.
I used the following code to capture POST data that was submitted from form.php and then concatenate it onto a URL to send it BACK to the form for validation corrections. Works like a charm, and in effect converts POST data into GET data.
foreach($_POST as $key => $value) {
$urlArray[] = $key."=".$value;
}
$urlString = implode("&", $urlArray);
echo "Please <a href='form.php?".$urlString."'>go back</a>";
An old post but here is how I handled it. Using newms87's method:
if($action == "redemption")
{
if($redemptionId != "")
{
$results = json_decode($rewards->redeemPoints($redemptionId));
if($results->success == true)
{
$redirectLocation = $GLOBALS['BASE_URL'] . 'rewards.phtml?a=redemptionComplete';
// put results in session and redirect back to same page passing an action paraameter
$_SESSION['post_data'] = json_encode($results);
header("Location:" . $redirectLocation);
exit();
}
}
}
elseif($action == "redemptionComplete")
{
// if data is in session pull it and unset it.
if(isset($_SESSION['post_data']))
{
$results = json_decode($_SESSION['post_data']);
unset($_SESSION['post_data']);
}
// if you got here, you completed the redemption and reloaded the confirmation page. So redirect back to rewards.phtml page.
else
{
$redirectLocation = $GLOBALS['BASE_URL'] . 'rewards.phtml';
header("Location:" . $redirectLocation);
}
}
Yes, you can do this in PHP e.g. in
Silex or Symfony3
using subrequest
$postParams = array(
'email' => $request->get('email'),
'agree_terms' => $request->get('agree_terms'),
);
$subRequest = Request::create('/register', 'POST', $postParams);
return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);
A workaround wich works perfectly :
In the source page,, start opening a session and assign as many values as you might want.
Then do the relocation with "header" :
<!DOCTYPE html>
<html>
<head>
<?php
session_start();
$_SESSION['val1'] = val1;
...
$_SESSION['valn'] = valn;
header('Location: http//Page-to-redirect-to');
?>
</head>
</html>
And then, in the targe page :
<!DOCTYPE html>
<?php
session_start();
?>
<html>
...
<body>
<?php
if (isset($_SESSION['val1']) && ... && isset($_SESSION['valn'])) {
YOUR CODE HERE based on $_SESSION['val1']...$_SESSION['valn'] values
}
?>
</body>
</html>
No need of Javascript nor JQuery..
Good luck !