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>';
Related
Trying to achieve Google invisible recaptcha, but I am not getting any response after verification.
Here is my code:
invisible_recaptcha.php (form)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Recaptcha Demo</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script>
function onSubmit(token) {
document.getElementById("i-recaptcha").submit();
}
</script>
</head>
<body>
<!-- FORM GOES HERE -->
<form id='i-recaptcha' action="process_recaptcha.php" method="post">
<label for="fname">First Name*</label><br>
<input type="text" name="fname" id="fname" required autofocus><br><br>
<label for="lname">Last Name*</label><br>
<input type="text" name="lname" id="lname" required><br><br>
<label for="email">Email Address*</label><br>
<input type="email" name="email" id="email" required><br><br>
<button class="g-recaptcha" data-sitekey="XXXXXXmy_site_keyXXXXXXXXX" data-size="invisible" data-callback="onSubmit">
Submit
</button>
</form>
</body>
</html>
process_recaptcha.php (verify the recaptcha)
<?php
// Checks if form has been submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
function post_captcha($user_response) {
$fields_string = '';
$fields = array(
'secret' => 'XXXXXX_my_secret_key_XXXXXXXXX',
'response' => $user_response
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
//echo $user_response."<br><br><br><br>". $fields_string;exit;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
// Call the function post_captcha
$res = post_captcha($_POST['g-recaptcha-response']);
if (!$res['success']) {
// What happens when the reCAPTCHA is not properly set up
echo 'reCAPTCHA error: Check to make sure your keys match the registered domain and are in the correct locations. You may also want to doublecheck your code for typos or syntax errors.';
} else {
// If CAPTCHA is successful...
// Paste mail function or whatever else you want to happen here!
echo '<br><p>CAPTCHA was completed successfully!</p><br>';
}
} ?>
It always gives me this message:
reCAPTCHA error: Check to make sure your keys match the registered domain and are in the correct locations. You may also want to doublecheck your code for typos or syntax errors.
Please try this One
try {
//Get google capcha details
if ($site_details['google_captcha_secret_key'] != '') {
$site_key = $site_details['google_captcha_secret_key'];
} else {
$site_key = GOOGLE_CAPTCHA_SECRET_KEY;
}
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = ['secret' => $site_key,
'response' => $captcha,
'remoteip' => $this->userIpAddress];
$options = [
'http' => [
'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);
return json_decode($result)->success;
} catch (Exception $e) {
return null;
}
Make sure you double-check your code over for syntax errors. You are missing the left quote around your site key. You also have an extra parenthesis where it says json_decode.
Finally, you don't need to separate it into two PHP files if you are going to use this condition:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
So the php code in process_recaptcha.php can be embedded in invisible_recaptcha.php. You would then have to change the form's action attribute to itself (invisible_recaptcha.php). The condition will check if the form has been submitted yet. If is has, it will process your recaptcha code, if not, it will skip it.
This should be a pretty simple questions but I can't seam to find a simple answer. All of the questions I find deal with same jquery.
I have a php page that accepts for post data, places it in an array, passes the array to an api, and receives success/error from api.
I have an html page with a form. When I submit the form it passes the form data to the php file.
All I would like to do is return the success/error message's variable back to the html file. I don't care if the page reloads, I don't want any fancy features I'm just trying to do a simple test but have forgotten my php 101. any help or direction to references would be appreciated.
Html:
<div style="width: 400px; margin: 150px auto;">
<form action="api3.php" method="post">
<input type="text" placeholder="First Name" name="fname"><br><br>
<input type="text" placeholder="Last Name" name="lname"><br><br>
<input type="email" placeholder="Email" name="email"><br><br>
<input type="text" placeholder="Phone" name="phone"><br><br>
<select name="life"><br><br>
<option value="customer">Customer</option>
<option value="lead">Lead</option>
<option value="subscriber">Subsciber</option>
<option value="opportunity">Opportunity</option>
</select><br><br>
<input type="text" placeholder="Pizza" name="pizza"><br><br>
<input type="submit" value="Submit">
</form>
</div>
PHP:
<?php
$arr = array(
'properties' => array (
array(
'property' => 'email',
'value' => $_POST["email"]
),
array(
'property' => 'firstname',
'value' => $_POST["fname"]
),
array(
'property' => 'lastname',
'value' => $_POST["lname"]
),
array(
'property' => 'phone',
'value' => $_POST["phone"]
),
array(
"property" => "lifecyclestage",
"value" => $_POST["life"]
),
array(
"property" => "pizza",
"value" => $_POST["pizza"]
)
)
);
$post_json = json_encode($arr);
$hapikey = "/";
$endpoint1 = 'http://api.hubapi.com/contacts/v1/contact/createOrUpdate/email/' . $arr['properties'][0]['value'] . '/?hapikey=' . $hapikey;
$endpoint2 = 'http://api.hubapi.com/contacts/v1/lists/5/add?hapikey=' . $hapikey;
$ch = #curl_init();
#curl_setopt($ch, CURLOPT_POST, true);
#curl_setopt($ch, CURLOPT_POSTFIELDS, $post_json);
#curl_setopt($ch, CURLOPT_URL, $endpoint1);
#curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
#curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response1 = #curl_exec($ch);
$status_code1 = #curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_errors1 = curl_error($ch);
if ($status_code1 == 200) {
$vid = json_decode($response1, true);
echo $vid['vid'] . '<br><br><br>';
$arr2 = array(
'vids' => array (
$vid['vid']
)
);
$vids_push = json_encode($arr2);
#curl_setopt($ch, CURLOPT_POSTFIELDS, $vids_push);
#curl_setopt($ch, CURLOPT_URL, $endpoint2);
$response2 = #curl_exec($ch);
$status_code2 = #curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_errors2 = curl_error($ch);
#curl_close($ch);
return $response2;
}
?>
EDIT: I changed my form.html page to .php. I didn't want to share my code because it always seams to complicate things but all I want is to return $response2 back to my form.php page.
First of all the page you have form and want to get response should be with .php
Now for example, I have a page with form at www.example.com/work.php
//Your form here
<form> </form>
submit the form on other .php page that process input and get response from API.
at the end of page you have two methods to return data.
using GET
encode your variables in url and redirect page to work.php
$url = "www.example.com/work.php" + "?status=error&message=This is message";
header('Location: '.$url);
Now on work.php file you need to utilize these parameters we encoded with url using
echo $_GET['status'];
echo $_GET['message'];
// rest of the page will be same.
using SESSION
store variables in session and redirect to work.php without parameters
$_SESSION['status'] = "error";
$_SESSION['message'] = "This is message";
$url = "www.example.com/work.php";
header('Location: '.$url);
Again in work.php file display data from session and rest of code will be same.
How can I post some known queries (hard-coded) together with user input?
For example, if I did not need user input, the query would look like this:
$post = "userid=11&token=abcdef&action=set&name=cf_1&value=UserInput";
But, since I need the value from users, I make something like this:
<form action="submit.php" method="post>
Insert cf_1: <input name='value' type='text'>
<input value="submit" type="submit">
</form>
And the php script:
<?php
$url = someurl;
$post = "userid=11&token=abcdef&action=set&name=cf_1";
$options = array( CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS, $post
);
$ch = curl_init();
curl_setopt_array($ch, $options);
curl_exec($ch);
curl_close($ch);
?>
However, using the above form and php script, the user input couldn't be submitted to the server
$post .= '&value='.$_POST['value'];
Make sure you do the necessary cleaning of the $_POST value, though.
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>
I know this is bad form, but we can't change the hidden input name as it is set by SalesForce. I have a form with an input like this:
<input type="hidden" name="00N5000000XXXXX" value="Demo_Account" />
and my PHP to post to them via cURL
$00N5000000XXXXX = $_POST['00N5000000XXXXX'];
which obviously won't work as it has number for a variable name.
When I change the name to:
$Foo = $_POST['00N5000000XXXXX'];
the back end doesn't work because it is expecting the form to submit a value with a name of 00N5000000XXXXX, not Foo or whatever I want to call it.
Obviously, Im not a PHP developer but need some advice on how to get around this.
Thank you.
You don't have to save it to a variable first:
<?php
$transferPostFields = array(
'00N5000000XXXXX'
);
$postFields = array();
foreach ($_POST as $key => $value) {
if (in_array($key, $transferPostFields)) {
$postFields[$key] = $value;
}
}
$curlHandle = curl_init();
curl_setopt_array($curlHandle, array(
CURLOPT_URL => 'http://api.salesforce.com/whatever/urls/they/use',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($postFields)
));
$output = curl_exec($curlHandle);
echo 'The output we received from SalesForce was: ' . $output;
?>
If you want to transfer all post fields, simply change the top part (anything above $curlHandle = curl_init() to:
$postFields = $_POST;
If you don't need to go past your own server first, then simply change your form:
<form method="post" action="http://api.salesforce.com/whatever/urls/they/use">