Looking for tips on Handling and hiding an HTML form - php

I'd like to be able to submit a form, Handle it with Javascript and then PHP + make an API call and then present a thank you message or show the array of errors with the API.
So far I have been able to make that call successfully, with a thank you, but have been unable to hide the form afterwards.
http://www.wilsonkeenan.com/learningphp/DoDirectPayment.php
Any thoughts on what I'm doing wrong? Any guidance would be much appreciated.
<?php
if (isset($_POST['submitted'])){
session_start();
require_once 'CallerService.php';
/**
* Get required parameters from the web form for the request
*/
$paymentType =urlencode( $_POST['paymentType']);
$firstName =urlencode( $_POST['firstName']);
$lastName =urlencode( $_POST['lastName']);
$creditCardType =urlencode( $_POST['creditCardType']);
$creditCardNumber = urlencode($_POST['creditCardNumber']);
$expDateMonth =urlencode( $_POST['expDateMonth']);
// Month must be padded with leading zero
$padDateMonth = str_pad($expDateMonth, 2, '0', STR_PAD_LEFT);
$expDateYear =urlencode( $_POST['expDateYear']);
$cvv2Number = urlencode($_POST['cvv2Number']);
$address1 = urlencode($_POST['address1']);
$address2 = urlencode($_POST['address2']);
$city = urlencode($_POST['city']);
$state =urlencode( $_POST['state']);
$zip = urlencode($_POST['zip']);
$countrycode = urlencode($_POST['countrycode']);
$amount = urlencode($_POST['amount']);
//$currencyCode=urlencode($_POST['currency']);
$currencyCode="USD";
$paymentType=urlencode($_POST['paymentType']);
/* Construct the request string that will be sent to PayPal.
The variable $nvpstr contains all the variables and is a
name value pair string with & as a delimiter */
$nvpstr="&PAYMENTACTION=$paymentType&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber&EXPDATE=". $padDateMonth.$expDateYear."&CVV2=$cvv2Number&FIRSTNAME=$firstName&LASTNAME=$lastName&STREET=$address1&CITY=$city&STATE=$state".
"&ZIP=$zip&COUNTRYCODE=$countrycode&CURRENCYCODE=$currencyCode";
/* Make the API call to PayPal, using API signature.
The API response is stored in an associative array called $resArray */
$resArray=hash_call("doDirectPayment",$nvpstr);
/* Display the API response back to the browser.
If the response from PayPal was a success, display the response parameters'
If the response was an error, display the errors received using APIError.php.
*/
$ack = strtoupper($resArray["ACK"]);
if($ack!="SUCCESS") {
$_SESSION['reshash']=$resArray;
$location = "APIError.php";
header("Location: $location");
} elseif ($ack =="SUCCESS") {
echo '<h1>Thank you</h1>';
}
}
else {
// Display Form
}
?>
<form method="POST" id="donate" action="" name="DoDirectPaymentForm">
<!--Payment type is <?=$paymentType?><br> -->
<input type=hidden name=paymentType value="<?php echo $paymentType?>" >
<fieldset>
<div>
<label class="label">First Name:</label>
<input type=text size=36 maxlength=32 name=firstName class="required" value=John>
</div>
</div>
<input type="hidden" name="submitted" value="1">
<input type=Submit value=Submit>
</div>

your else bracket is closed before the form, try this:
else { /*Display Form*/ ?>
<form method="POST" id="donate" action="" name="DoDirectPaymentForm">
<!--Payment type is <?=$paymentType?><br> -->
<input type=hidden name=paymentType value="<?php echo $paymentType?>" >
<fieldset>
<div>
<label class="label">First Name:</label>
<input type=text size=36 maxlength=32 name=firstName class="required" value=John>
</div>
</div>
<input type="hidden" name="submitted" value="1">
<input type=Submit value=Submit>
</div>
<?php } ?>

Like FatherStorm said, jQuery is a much cleaner way to do this. Look into the ajax call. It's very easy to use.
But if you don't want to for some reason, you can use session vars to decide whether or not to display the form.
if($ack == 'SUCCESS')
$_SESSION['success'] = true;
else
{
//bunch of processing here for whatever your api returns
$_SESSION['success'] = false;
}
if($_SESSION['success']): ?>
Thank You
<?php else: ?>
<form>...</form>
<?php endif; ?>

I'm assuming you're using classic Javascript and not a library like jQuery.
so let's assume that your form is in a DIV with the ID of myForm so in classic javascript
document.getElementById('myForm').style.display='none';
in jQuery it would be $('#myForm').hide();
Consider jQuery.
now, to handle multiple possible results in the Javascript, you're going to want your AJAX page to echo a JSON encoded string, and not just the rraw result text so it won't be echo"Congratulations"; it would be more like
echo json_encode(array('result'=>'success','html'=>'Congratulations'));
and on the javascript side (in jQuery again cause it's faster)
//the data I need to submit to my page here, I'm assuming all form elements have ID's the same as their name.... it will submit like a form POST and return the result expecting it to be in JSON format.
$.getJSON("handleAjax.php", { paymentType: $('#paymentType').val(), name: $('#name').val(),[...more_fields_here...]}, function(data){
alert( data.html);
if(data.result=='success'){
$('#myForm').hide();
}
});
also, when you find yourself including file fragments like this, actually use includes... like
if(Condition){
include('/templates/paymentForm.phtml');
}else{
include('/templates/paymentThanks.phtml');
}

Related

Manually Send Data PHP method post

i'm brazilian i does a website simple to sent a simple users data, but to do a test i want sent manually newer data in a link without need complete manual form if it run then i can use directly by my app to save all users data.
see my idea:
mywebsite.com/savedata?method=post&usernamesave=Nome&Misael&userxp=34&userid=35&userlevel=31&usermail=crod%40gmail.com&userprog1=1&userprog2=2&userprog3=23&userprog4=25&userprog5=25&userprog6=25&userprog7=100&userprog8=100&proceed=
if i can change this data from my app and using hrefs i can do this and save a simple data without a complex data connection, it's possible ?
<a href="mywebsite.com/simplepost?method=post&joao&6y"> << type of exeple.
But when i use this and press enterkey the data isn't saved into a textfile, why ?
i using this in php :
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
if ($_SERVER["REQUEST_METHOD"] == "POST") {
/*Php 5.6.2 Code By : Michael S. author*/
//globais
$username = $_POST['usernamesave'];
$userxp = $_POST['userxp'];
$userid = $_POST['userid'];
}
If i got you right you want to save data using a post method. If this is what you want to accomplish, then you don't have to pass the variables in URL. This is the main difference between POST and GET method.
Now for data saving, i will assume that you all ready created a database and a table to save your information on it, so let's jump to the form and how to handle them.
<?php
/*
* First form one will be the POST method.
*/
if(isset($_POST)){
echo "post method where used from a form to send this variables";
var_dump($_POST);
}
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="username">Username: </label>
<input type="text" name= "username">
<label for="age">Age: </label>
<input type="number" name="age"/>
<input type="submit" value="Submit">
</form>
When you click on submit the information will be sent and can be handled after.
In get method it's different you will see the variables inside the URL after hitting submit, and the same way you can send data to other pages.
<?php
/*
* Second form one will be the GET method
* Check the url.
*/
if(isset($_GET)){
echo "get method where made from a form with this variables";
var_dump($_GET);
}
?>
<form method="GET" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="username">Username: </label>
<input type="text" name= "username">
<label for="age">Age: </label>
<input type="number" name="age"/>
<input type="submit" value="Submit">
</form>
Now in the url you should see something like
example.com/index.php?username=WaredNsour&age=24
I believe you are using the GET method to send information but in your PHP code, you are using the POST method to fetch them.
Try this :
if ($_SERVER["REQUEST_METHOD"] == "GET") {
/*Php 5.6.2 Code By : Michael S. author*/
//globais
$username = $_GET['usernamesave'];
$userxp = $_GET['userxp'];
$userid = $_GET['userid'];
}
In the code of your page that is processing the variables being sent, try the following (temporarily) as a test to see if variables are being sent/seen. If they are, they will be printed out.
<p>Post vars:
<?php var_dump($_POST) ?>
</p>
If nothing displays, try:
<p>Request vars:
<?php var_dump($_REQUEST) ?>
</p>
Note: in the url you posted you have: &Misael& if Misael is part of the username you should not use the & in front of it. http sees &s as separators for the variables. It will see Misael as a variable name, like: ...&Misael=something&.... If it is a space, use %20.

PHP: Refresh page on invalid form submit

How can I refresh a page with a form on submission pending the outcome of the submitted data and display a result.
e.g I have a page with a form:
<form action="" method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
The engine that handles the form is external, but required in the page:
require_once 'form_engine.php';
form_engine.php checks the input,
$success = "true";
$errorMessage = " ";
$name = $_POST['name'];
if ( $name == '') {
$errorMessage = 'Please enter your name';
$success = false;
}
else (if $success = true) {
// do something with the data
}
The form page contains the result:
<form action="" method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
<p><?php echo $errorMessage; ?></p>
Will the error message get displayed after the form is submitted incorrectly? Or do I have to use a session to store it?
You need something like this:
if (!isset($_POST['name']))
instead of
if ( $name == 'name')
UPDATE
Try this, it should give you the idea:
<?php
$errorMessage = false;
if (isset($_POST['submit'])) {
if (!isset($_POST['name']) || $_POST['name']=='') {
$errorMessage = 'Please enter your name';
}
else {
// do something with the data
echo "Success!!";
}
}
?>
<form method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="submit" name="submit" />
</form>
<p><?php if ($errorMessage) echo $errorMessage; ?></p>
Note: leaving out the action attribute will just submit the form to the current page
Note 2: The PHP here could very well be stored in another page. Using require() is the same as putting the code directly into the page.
You can use redirect on php side:
header('Location: www.mysite.com/index.php');
You seem to be a little confused in terms of the exact process that occurs in terms of rendering a page, as do some of those commenting. You do not need to use sessions to solve this problem. There is no need to store anything server-side between page requests because the user's browser with retain everything that you need, at least for this situation. My guess is the others took you mentioning an "external engine" and thought that the form would be submitting away to a different site/page.
form loops
Below is a diagram showing a typical form request loop:
You do not have to do this, as coding is as much about personal preference to anything else, but typically people will design their form to submit back to the same URI that generated it — as you seem to be doing in your example, by leaving the action attribute blank. By doing this, as long as you embed everything you wish to pass back to the server side within the form — each time the user submits — that information will be resent and be available in PHP.
Obviously you need to be wary of what information might constitute as sensitive, as this data should only ever be written into markup if your requests are protected by HTTPS/SSL. You should also filter/escape any user input to prevent markup injection into your site. You can prevent many problems by using htmlentities, however this can cause issues depending on the values you are trying to capture from the user. Because you are using double quoted HTML attributes (the right way to do them ;) I have not set the ENT_QUOTES option.
back to the point
So in the above loop the user will be shown the form for the first time, and after any subsequent submit, which means that each time your PHP notices that there is an error you can just add your message into the page flow. The trick with this kind of system is what exactly do you do once the form is fully complete. To get out of the loop most people will use a header location call:
<?php
require_once 'form_engine.php';
$name = !empty($_POST['name']) ? trim($_POST['name']) : '';
$name = htmlentities($name);
if ( $success ) {
header('location: next-step.php');
exit;
}
?>
<form action="" method="post">
<input type="name" value="<?php echo $name; ?>" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
<?php
if ( $errorMessage ) {
echo "<p>$errorMessage</p>";
}
?>
form engine repairs
You should also rectify your form_engine.php as per my comments above and Shekhar Joshi's answer, although I would keep the header code outside of your engine logic, and leave that decision to the code that requires in the engine — as the above does.
may be, you are looking for this! the header() method.
$success = true;
$errorMessage = " ";
$name = $_POST['name'];
if(isset($_POST['name'])) {
if ( $_POST['name'] == '') {
$errorMessage = 'Please enter your name';
$success = false;
header('Location: www.something.com/some.php');
}
else if ($success == true) {
// do something with the data
}
}

php form validation issues - cannot print to header

I have a php form that saves the info to my database and sends an email upon completion. however it will not validate the fields to see if they are null, instead it prints both the set and not set options. Any ideas as to why this could be happening? It worked perfectly before i added the form field validation to it.
As a side note it works in FF and Chrome due to the html 5 aria-required, but not in IE
html
<form id="contact" name="contact" action="register1.php" method="post">
<label for='Cname'>Camper Name</label>
<input type="text" name="Cname" maxlength="50" value="" required aria-required=true />
<input type="hidden" id="action" name="action" value="submitform" />
<input type="submit" id="submit" name="submit" value="Continue to Camp Selction"/>
</form>
php
<?php
//include the connection file
require_once('connection.php');
//save the data on the DB and send the email
if(isset($_POST['action']) && $_POST['action'] == 'submitform')
{
//recieve the variables
$Cname = $_POST['Cname'];
//form validation (this is where it all breaks)
if (isset($Cname)) {
echo "This var is set so I will print.";
}
else {
echo '<script type="text/javascript">alert("please enter the required fields");</script>';
}
//save the data on the DB (this part works fine)
<?php
$Cname = isset($_POST['Cname']) ? $_POST['Cname'] : null;
if (isset($Cname)) {
echo "This var is set so I will print.";
}
// OR
if (isset($_POST['Cname'])) {
// Perform your database action here...
}
?>
Consider using PHP's empty function
PHP.Net Manual Empty()
You can update your code to the following:
if(!empty($Cname)) {
echo "This var is set so I will print.";
}
Do you just need an "exit()" in the else?

POST without redirect with PHP

I have a simple form for a mailing list that I found at http://www.notonebit.com/projects/mailing-list/
The problem is when I click submit all I want it to do is display a message under the current form saying "Thanks for subscribing" without any redirect. Instead, it directs me to a completely new page.
<form method="POST" action="mlml/process.php">
<input type="text" name="address" id="email" maxlength="30" size="23">
<input type="submit" value="" id="submit"name="submit" >
</form>
You will need AJAX to post the data to your server. The best solution is to implement the regular posting, so that will at least work. Then, you can hook into that using Javascript. That way, posting will work (with a refresh) when someone doesn't have Javascript.
If found a good article on posting forms with AJAX using JQuery .
In addition, you can choose to post the data to the same url. The JQuery library will add the HTTP_X_REQUESTED_WITH header, of which you can check the value in your server side script. That will allow you to post to the same url but return a different value (entire page, or just a specific response, depending on being an AJAX request or not).
So you can actually get the url from your form and won't need to code it in your Javascript too. That allows you to write a more maintanable script, and may even lead to a generic form handling method that you can reuse for all forms you want to post using Ajax.
Quite simple with jQuery:
<form id="mail_subscribe">
<input type="text" name="address" id="email" maxlength="30" size="23">
<input type="hidden" name="action" value="subscribe" />
<input type="submit" value="" id="submit"name="submit" >
</form>
<p style="display: none;" id="notification">Thank You!</p>
<script>
$('#mail_subscribe').submit(function() {
var post_data = $('#mail_subscribe').serialize();
$.post('mlml/process.php', post_data, function(data) {
$('#notification').show();
});
});
</script>
and in your process.php:
<?php
if(isset($_POST['action'])) {
switch($_POST['action']) {
case 'subscribe' :
$email_address = $_POST['address'];
//do some db stuff...
//if you echo out something, it will be available in the data-argument of the
//ajax-post-callback-function and can be displayed on the html-site
break;
}
}
?>
It redirects to a different page because of your action attribute.
Try:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<input type="text" name="address" id="email" maxlength="30" size="23" />
<input type="submit" value="" id="submit" name="submit" />
</form>
<?php if (isset($_POST['submit'])) : ?>
<p>Thank you for subscribing!</p>
<?php endif; ?>
The page will show your "Thank You" message after the user clicks your submit button.
Also, since I don't know the name of the page your code is on, I inserted a superglobal variable that will insert the the filename of the currently executing script, relative to the document root. So, this page will submit to itself.
You have to use AJAX. But that requires JavaScript to be active at the users Brwoser.
In my opinion it's the only way to do without redirect.
to send a form request without redirecting is impossible in php but there is a way you can work around it.
<form method="post" action="http://yoururl.com/recv.php" target="_self">
<input type="text" name="somedata" id="somedata" />
<input type="submit" name="submit" value="Submit!" />
</form>
then for the php page its sending to have it do something but DO NOT echo back a result, instead simply redirect using
header( 'Location: http://yourotherurl.com/formpage' );
if you want it to send back a success message simply do
$success = "true";
header( 'Location: http://yourotherurl.com/formpage?success='.$success);
and on the formpage add
$success = $_GET['success'];
if($success == "true"){ echo 'Your success message'; } else { echo
'Your failure message';
Return and print the contents of another page on the current page.
index.php
<html>
<body>
<p>index.php</p>
<form name="form1" method="post" action="">
Name: <input type="text" name="search">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$_POST['search'];
include 'test.php';
}
?>
</body>
</html>
test.php
<?php
echo 'test.php <br/>';
echo 'data posted is: ' . $_POST['search'];
?>
Result:
Just an idea that might work for you assuming you have no control over the page you are posting to:
Create your own "proxy php target" for action and then reply with the message you want. The data that was posted to your php file can then be forwarded with http_post_data (Perform POST request with pre-encoded data). You might need to parse it a bit.
ENGLISH Version
It seems that no one has solved this problem without javascript or ajax
You can also do the following.
Save a php file with the functions and then send them to the index of your page
Example
INDEX.PHP
<div>
<?php include 'tools/edit.php';?>
<form method="post">
<input type="submit" name="disable" value="Disable" />
<input type="submit" name="enable" value="Enable" />
</form>
</div>
Tools.php (It can be any name, note that it is kept in a folder lame tools)
<?php
if(isset($_POST['enable'])) {
echo "Enable";
} else {
}
if(isset($_POST['disable'])) {
echo "Disable";
} else {
}
?>
Use
form onsubmit="takeActions();return false;"
function takeAction(){
var value1 = document.getElementById('name').innerHTML;
// make an AJAX call and send all the values to it
// Once , you are done with AJAX, time to say Thanks :)
document.getElementById('reqDiv').innerHTML = "Thank You for subscribing";
}

Avoid code re-use when handling form validation

I am generating form and handling the submit event in the same file.
If user has not entered the title, I want to display the form again and include an error message (e.g. "You forgot the title.").
That means that I have to duplicate code twice - once to diplay empty form and second to display form with body and ask user to enter title:
<?php if(strlen(strip_tags($_POST['posttitle'])) == 0):
// Display the form with question body that user has entered so far and ask user to enter title.
?>
<label for="title"><b>Title:</label><br/>
<input type="text" name="posttitle" id="posttitle" />
<?php endif;?>
<?php elseif ( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action']) && $_POST['action'] == 'post') : ?>
<!-- Everything ok - insert post to DB -->
<?php else :
// just display form here (again ouch!)
<label for="title"><b>Title:</label><br/>
<input type="text" name="posttitle" id="posttitle" />
?>
I would do it like this:
If REQUEST_METHOD is POST I will validate the input and collect messages in an array ($errors in my code).
Then I would just print the form and if there was an error the code will print it.
<?php
$errors = array();
function print_value_for($attr) {
if (isset($_POST[$attr]))
echo $_POST[$attr];
}
function print_error_for($attr) {
global $errors;
if (isset($errors[$attr]))
echo $errors[$attr];
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// do validation here and add messages to $errors
// like $errors['posttitle'] = "The title you entered is bad bad bad";
if (empty($errors)) {
// update database and redirect user
}
}
?>
<!-- display the form and print errors if needed -->
<form>
<?php print_error_for('posttitle'); ?>
<input name="posttitle" type="text" value="<?php print_value_for('posttitle') ?>">
<?php print_error_for('postauthor'); ?>
<input name="postauthor" type="text" value="<?php print_value_for('posttitle') ?>">
<?php print_error_for('postbody'); ?>
<textarea name="postbody">
<?php print_value_for('posttitle') ?>
</textarea>
<input type="submit">
</form>
PS. Consider using MVC to separate code and templates.
Here is a quick way to do that.
<form>
<input type="text" name="title" value="<?php echo $_REQUEST['title']; ?>"/>
<input type="text" name="field_a" value="<?php echo $_REQUEST['field_a']; ?>"/>
....
</form>
But I can also advise you to display a var called $title which is the result of a check on $_REQUEST['title].
You could use an output buffer to grab the form and then assign it to a variable like so:
<?php
ob_start();
include('path/to/your/form');
$form = ob_get_flush();
// then later you can just go
print $form;
?>
Hope this helps
When you display the form, use the possibly empty $_POST values as default field values for both the title and question body. If either is empty, the form will display the second time with the other already filled in:
<?php
$message = "";
if (empty($_POST['title'])) $message .= " Please enter a title.";
if (empty($_POST['body'])) $message .= " Please enter a body.";
?>
<form action='me.php'>
<input name='title' type='text' value='<?php if (!empty($_POST['title'])) echo htmlentities($_POST['title'], ENT_QUOTES); ?>' />
<textarea name='body'><?php if (!empty($_POST['body'])) echo $_POST['body']; ?></textarea>
</form>
Read this MVC
Your can write form in view, handler in controller, and business logic in model

Categories