How To Display Error Messages With Wufoo API V3? - json

I am using the Wufoo API V3 to submit data from a form hosted on my website to my Wufoo account. I followed the example on the [Entries POST API][1] page, and I was able to successfully the data to my account.
I was wondering how I am able to check for error messages, and display the ErrorText for each text input field using PHP?
For example, if someone does not provide their email address in a required email field.
Here is the code I have so far:
<?
function submit() {
$ref = curl_init('https://myname.wufoo.com/api/v3/forms/xxxxxx/entries.json');
curl_setopt($ref, CURLOPT_HTTPHEADER, array('Content-type: multipart/form-data'));
curl_setopt($ref, CURLOPT_POST, true);
curl_setopt($ref, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ref, CURLOPT_POSTFIELDS, getPostParams());
curl_setopt($ref, CURLOPT_USERPWD, 'XXXX-XXXX-XXXX-XXXX');
curl_setopt($ref, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ref, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ref, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ref, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ref, CURLOPT_USERAGENT, 'Wufoo.com');
$response = curl_exec($ref);
echo $response;
}
function getPostParams() {
return array( 'Field4' => "you#company.com");
}
submit();
?>
UPDATE (Nov 12, 2011):
MinisterOfPower,
Thanks for [the reply and advice][2] about the Wufoo PHP API Wrapper. I am now using the API Wrapper and it rocks. I am having some challenges integrating the code you provided with my form.
For example, if I have a form on index.php (see below) with an email required field. How would I be able to set up the API wrapper to display an error next to the appropriate input field after the form is submitted?
Here's the code for index.php:
<? require_once('my-wrapper.php'); ?>
<html>
<head>
<title>Form</title>
</head>
<body>
<form id="form1" name="form1" autocomplete="off" enctype="multipart/form-data" method="post" action="">
<div>
<label id="email" class="icons" for="Field4">Email</label>
<input id="Field4" name="Field4" type="text" class="formreg"/>
</div>
<div>
<label id="name" class="icons" for="Field6">Name</label>
<input id="Field6" name="Field6" type="text" class="formreg"/>
</div>
<input type="submit" name="saveForm" value="Submit" id="submit" class="submit" />
<input type="hidden" id="idstamp" name="idstamp" value="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=" />
</form>
</body>
</html>
Here's the code for my-wrapper.php:
$wrapper = new WufooApiWrapper('XXXX-XXXX-XXXX-XXXX', 'mysubdomain','wufoo.com');
$postArray = array();
foreach ($this->postValues as $value => $key) {
$postArray[] = new WufooSubmitField($key, $value);
}
try {
$result = $wrapper->entryPost('XXXXXX', $postArray);
if (!$result->Success) {
foreach ($result->FieldErrors as $key => $value) {
echo "Error on $key. Error Text: $value <br />";
}
}
} catch (Exception $e) {
//Read the error message.
}
UPDATE (Nov 20, 2011):
I am now able to display the error messages with the help of MinisterofPower's code and the Wufoo API wrapper. I have a couple of follow up questions:
I was wondering how I do set up the form below with PHP so that it posts the entries upon pressing the submit button?
Is it possible to do this using AJAX so the page does not refresh?
Here's the code:
<?
// API
require_once('WufooApiExamples.php');
// Wufoo
$wrapper = new WufooApiWrapper('XXXX-XXXX-XXXX-XXXX', 'mysubdomain','wufoo.com');
// Post Entries
$postArray = array();
foreach ($this->postValues as $key => $value) {
$postArray[] = new WufooSubmitField($key, $value);
}
try {
$result = $wrapper->entryPost('xxxxxx', $postArray);
if (!$result->Success) {
foreach ($result->FieldErrors as $key => $value) {
$fieldError[$value->ID] = $value->ErrorText;
}
}
} catch (Exception $e) {
//Read the error message.
}
// Add Errors
function addErrors($fieldName, $fieldError, $add){
if($fieldError[$fieldName] != ''){
if ($add == 'message') return '<p class="errors">'.$fieldError[$fieldName].'</p>';
else if ($add == 'class') return 'class ="errors"';
}
}
?>
<!--Begin Form-->
<div <? echo addErrors('Field4', $fieldError, 'class') ?>>
<label id="profile" class="icons" for="Field4">Email</label>
<input id="Field4" name="Field4" type="text" class="formreg" tabindex="1"/>
<? echo addErrors('Field4', $fieldError, 'message')?>
</div>
<div <? echo addErrors('Field6', $fieldError, 'class') ?>>
<label id="profile" class="icons" for="Field6">Name</label>
<input id="Field6" name="Field6" type="text" class="formreg" tabindex="1"/>
<? echo addErrors('Field6', $fieldError, 'message')?>
</div>
<!--End Form-->

The process of retrieving the response is outlined in the API docs. Also, the markup for field errors in found the Dealing With Failure section.
Is is worth nothing that Wufoo offers API Wrappers for PHP and many other languages. I highly suggest using one of those since they make the process so much easier.
Using the Wufoo API, you'd search for a Success value of 0 in the response object and then parse the Field Errors node, as shown here:
$wrapper = new WufooApiWrapper($this->apiKey, $this->subdomain, 'wufoo.com');
$postArray = array();
foreach ($this->postValues as $value => $key) {
$postArray[] = new WufooSubmitField($key, $value);
}
try {
$result = $wrapper->entryPost($this->formHash, $postArray);
if (!$result->Success) {
foreach ($result->FieldErros as $key => $value) {
echo "Error on $key. Error Text: $value <br />";
}
}
} catch (Exception $e) {
//Read the error message.
}
A followup question was posted above, so I'll add my answer here.
You asked how to display an error next to the form in question. You could do this with either javascript or php. I'll show you the PHP way only.
Using PHP, you could redirect back to the form with a value in the GET param of the URL, enumerating the error fields and messages. So, for example, you could do this:
for($result->FieldErrors as $name => $value) {
$str.="$name=$value&";
}
if($str) {
$str = '?errors=true&'.$str;
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
header("Location: http://$host$uri/$str");
exit;
}
Then, you'd wrap the above code in this if statement to check for error values on postback, like so:
if($_GET['errors']) {
require_once('my-wrapper.php');
else
//Your HTML HERE
endif
After that, add some PHP conditions which append class names to your fields if they contain errors. For example:
<label id="Field4" class="icons <?php if ($_GET['Field4']) echo 'error'; ?>" for="Field4">Email</label>
Finally, add some CSS to call out the error fields with a color or other indicator.
The other way to do this is with javascript.
Use the same logic as above, but add the following script to your page (grabbed from here and here.)
<script type="text/javascript" charset="utf-8">
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return 'error';
}
}
}
function changeClass (elementID, newClass) {
var element = document.getElementById(elementID);
element.setAttribute("class", newClass); //For Most Browsers
element.setAttribute("className", newClass); //For IE; harmless to other browsers.
}
changeClass('Field4', 'error');
</script>
Then use this markup instead:
<label id="Field4" class="icons" for="Field4">Email</label>
Good luck.
PS: This code was written here in SO, so it will probably contain syntax errors. But you can get the point...

Related

Populating Drop Down List from Previous Drop Down - using AJAX, PDO, jQuery

I'm brand new to using PHP and mySQL so I'm fully aware I've probably made some very 'noob' errors. However, I'm really stuck when it comes to populating my second drop down list from mySQL, when an option has been selected from a previous drop down list.
I've tried all the forums and have tried example scripts, but each time, I continue to get errors despite trying different examples on the internet. Thus hoping why I wish someone could help me out.
I'm trying to build a small film website, whereby someone can select a film, and then select a date & time and etc. I'm using mySQL to populate the drop down lists but get stuck when I want to populate the second dropdown, with it being dependent on the first option select.
I've tried using AJAX but to no avail. Appreciate I'm probably made some very rookie errors here (possible confusion around variables) but if someone could shed some light on where I'm wrong, I would be really grateful.
You have small mistake on getDates.php
<?php
require("Connect.php");
$name = (!empty($_REQUEST["name"])) ? trim($_REQUEST["name"]) : "");
if (!empty($name)) {
$sql = "SELECT Dates FROM Cinema WHERE name = $name";
try {
$stmt = $DB->prepare($sql);
$stmt->bindValue("tn", trim($name));
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo($ex->getMessage());
}
if (count($results) > 0) {
?>
<label>Dates:
<select name="Dates">
<?php foreach ($results as $rs) { ?>
<option value="<?php echo $rs["Dates"]; ?></option>
<?php } ?>
</select>
</label>
<?php
}
}
?>
Try it please and feedback
index.php
<?php
require Connect.php;
?>
<!DOCTYPE html>
<html>
<head>
<title>Films for Family!!</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
function Datesforfilms(sel) {
var name = sel.options[sel.selectedIndex].value;
$("#output1").html("");
$.ajax({
type: "POST",
url: "getDates.php",
data: "name=" + name,
cache: false,
success: function(html) {
$("#output1").html(html);;
}
});
}
</script>
</head>
<body>
<div class="welcome">
<h1>Films for Family</h1>
</div>
<div class="SelectFilm">
<h3> Step 1: </h3>
<p> *Select a film*</p>
<form name="Filmform" method="get">
<select name="Select a Film" onChange="Datesforfilms(this);">
<option value="0">Select a Film</option>
<?php
$sql = "SELECT name FROM company";
$handle = $conn->prepare($sql);
$handle->execute(array($sql));
$res = $handle->fetchAll();
foreach($res as $movie) { ?>
<option value="<?=$movie['name']?>"><?=$movie['name']?></option>
<?php } ?>
</select>
<div id="output1"></div>
</form>
</div>
</body>
</html>
getDates.php
<?php
require("Connect.php");
$name = (!empty($_POST["name"]) ? trim($_POST["name"]) : "");
if (!empty($name)) {
$sql = "SELECT Dates FROM Cinema WHERE name = $name";
try {
$stmt = $DB->prepare($sql);
$stmt->bindValue("tn", trim($name));
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo($ex->getMessage());
}
if (count($results) > 0) {
?>
<label>Dates:
<select name="Dates">
<?php foreach ($results as $rs) { ?>
<option value="<?php echo $rs["Dates"]; ?>"><?php echo $rs["Dates"]; ?></option>
<?php } ?>
</select>
</label>
<? } ?>
<? } ?>

HTML form on submit and javascript not working

I've looked over many threads and can't seem to find a working solution for my problem. I am new to javascript and am looking for assistance in allowing my page to run javascript and submit a form by clicking one submit button.
I am using codeigniter, and am calling a javascript function called uploadEx(); to submit a canvas to a directory. Submitting to the directory works by itself but not as the same button as the submit for the form. If someone could help me make the button share both actions that would be great.
<div>
</div>
<form method="post" accept-charset="utf-8" name="form1">
<input name="hidden_data" id='hidden_data' type="hidden"/>
</form>
<script>
function uploadEx() {
var canvas = document.getElementById("canvasSignature");
var dataURL = canvas.toDataURL("image/png");
document.getElementById('hidden_data').value = dataURL;
var fd = new FormData(document.forms["form1"]);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/inc/img/inspection/upload_data.php', true);
document.forms["form"].submit();
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete + '% uploaded');
//alert('Succesfully uploaded');
}
};
xhr.onload = function() {
};
xhr.send(fd);
};
</script
<div align="center">
<?php if( !function_exists('form_open')): ?>
<?php $this->load->helper('form'); ?>
<?php endif;?>
<form id="form" onClick="uploadEx(); return true;" method="post">
<?php echo form_label('Trailer Number','trlr_num'); ?>
<?php echo form_input(array('name'=>'trlr_num','type'=>'text')); ?>
<?php echo form_label('Seal','seal'); ?>
<?php echo form_input(array('name'=>'serial_num','type'=>'text')); ?>
<?php echo form_fieldset_close(); ?>
<br />
<input type="submit" name="submit" value="submit" content="submit"/>
<?php echo form_close(); ?>
I was able to resolve my problem by using Imran Qarner's suggestion by moving the onsubmit event out of the php code that calls codeigniter.
Have u tried onsubmit event instead of onclick? i think so it will work for you.
moreover what is the functionality of your first <form>.......</form> ?

How do I submit a form without refreshing the current page?

I have a fairly basic email form
<form name="contactform" method="post" action="send_email.php" id="email_form">
<div class="ContactHeaders">Name</div>
<input type="text" name="Name" class="ContactBoxes" id="name"/><br/><br/>
<div class="ContactHeaders">Email</div>
<input type="email" name="Email" class="ContactBoxes"/><br/><br/>
<div class="ContactHeaders">Message</div>
<div style="width:100%">
<textarea name="Message" maxlength="1000"></textarea><br/>
</div>
<div style="width: 100%">
<input type="submit" class="Submitbtn" value="Submit">
</div>
</form>
Here's 'send_email.php'
<?php
ob_start();
include 'navbar.php';
ob_end_clean();
if(isset($_POST['Email'])) {
//declare variables
$Name = $_POST['Name'];
$Email = $_POST['Email'];
$Message = $_POST['Message'];
$complete = 0;
$email_to = "someone#example.com";
$email_subject = "Website Contact";
//check all forms are filled in correctly
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(preg_match($email_exp,$Email)) {
$complete++;
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(preg_match($string_exp,$Name)) {
$complete++;
}
if(strlen($Message) > 20) {
$complete++;
}
//send email if $complete = 4
if ($complete == 3){
if (get_magic_quotes_gpc()) {
$Message = stripslashes($Message);
}
$Message = $Message . "\n\n" . "From " . $Name;
$headers = 'From: '.$Email."\r\n".
'Reply-To: '.$Email."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $Message, $headers);
echo '<script>
alert("Thank you for contacting me. I will be in touch shortly");
top.location="index.php";
</script>';
}
else {
echo '<script>
alert("The form you submitted is invalid. Please ensure the following: \n You have provided a valid email address. \n Your phone number is entered correctly. \n The message box contains at least 20 characters.")
history.go(-1)
</script>';
}
}
?>
So my problem is that when the form submits to the php file, the browser loads the php file, runs the code and returns the result (It's not really a problem but it's something I don't want) It is then up to java to display the alert and go back one (in my code anyway). Is there a way to make it run the code in the background so the form runs the php file without having to go to it (if that makes sense) and return the result in the same window. I've obviously looked around and found loads of things about AJAX but I didn't really understand it and couldn't get it to work for me.
The reason for doing this is a little complicated but would make things much easier as far as user-friendliness goes for my site, as well as looking cleaner (going to a blank page and displaying an alert doesn't look very good).
Thanks in advance for any help you can offer me:)
$('.Submitbtn').click(function(e) {
e.preventDefault();
// do some form validation here
if form is valid { // from validation above
var formData = $('#email_form').serialize();
$.post('send_email.php',{data:formData});
} else {
alert('Form no good - fix it!');
return false;
}
});
Here's something you can start with. This is very basic but supplies the necessary foundation for beginning your AJAX adventure.
50 Excellent AJAX Tutorials

DOMPDF not working

I am trying to take some html from a textarea and convert it to a pdf. I donwnloaded DOMPDF from https://github.com/dompdf/dompdf and wrote the code below. When I click submit I get this error: "Internal Server Error". (my webhost doesn't tell me which line it's one)
(the name of this file is test2.php)
<?php
if (isset($_POST['submit'])) {
$content = $_POST['content'];
if (empty($content)){
$error = 'write something';
}
else {
include_once( 'dompdf/dompdf_config.inc.php' );
$dompdf = new DOMPDF();
$dompdf->load_html($content);
$dompdf->render();
$dompdf->stream('example.pdf');
}
}
?>
<!DOCTYPE html>
<head>
</head>
<body>
<?php
if(isset($error)){
echo $error;
}
?>
<form method="post" action="test2.php">
<textarea name="content" id="content">hello world</textarea><br>
<input type="submit" name="submit" value='submit'>
</form>
</body>
</html>
I was struggled for more than one month to solve this. Finally I solved it. the solution is below.
<?php
require_once 'dompdf/autoload.inc.php';
// reference the Dompdf namespace
use Dompdf\Dompdf;
?>
<html>
<head></head>
<body>
<h1>Sucess</h1>
</body>
</html>
<?php
$html = ob_get_clean();
$dompdf = new DOMPDF();
$dompdf->setPaper('A4', 'portrait');
//$dompdf->setPaper('A4', 'landscape');
$dompdf->load_html($html);
$dompdf->render();
//For view
$dompdf->stream("",array("Attachment" => false));
// for download
//$dompdf->stream("sample.pdf");
?>
I had a similar issue on a client's server when using DOMPDF for a project.
It's possible that you do not have the right level of error reporting configured with your installation of PHP.
At the top of your script place the following; error_reporting(E_ALL);
Example:
error_reporting(E_ALL);
if (isset($_POST['submit'])) {
$content = $_POST['content'];
if (empty($content)){
$error = 'write something';
}
else {
include_once( 'dompdf/dompdf_config.inc.php' );
$dompdf = new DOMPDF();
$dompdf->load_html($content);
$dompdf->render();
$dompdf->stream('example.pdf');
}
}
You should now see a more detailed message about the type of error received.
There could be issues with the HTML markup you are passing to the $dompdf->load_html($content); method or alternatively you might be experiencing memory related issues (exceeding your memory allowance).
Typically these errors will report themselves but again depending on your setup, reporting might be limited.

PHP Mail() Function Issue - Message field not getting sent (WordPress)

I know there are thousands and thousands of ways to utilize the PHP mail() function, but I am fairly new to PHP and could use some pointers to get me set in the right direction. I have a PHP mail function written into my WordPress driven site and it emails all the information (name, email, & phone) except for the message field. I've done my research on here as well as every PHP related site, but I would prefer to understand my specific issue so I can better understand what I'm writing. So with that said...here's the code:
<?php
function spamcheck($field)
{
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_POST['email']))
{
$mailcheck = spamcheck($_POST['email']);
if ($mailcheck==FALSE)
{
$submit_message = "Please input your information again.";
}
else
{
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
mail("emailaddress#gmail.com", "From: $name", "Email: $email", "Phone Number: $phone", "Message: $message");
$submit_message = "Thank you for your message";
}
}
?>
And the HTML...
<form name="message-me" id="contact-form" action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="POST" enctype="multipart/form-data">
<div class="field-group">
<label>Name:</label><input type="text" name="name" id="form_name" />
</div>
<div class="field-group">
<label>Email:</label><input type="text" name="email" id="form_email" />
</div>
<div class="field-group">
<label>Phone:</label><input type="text" name="phone" id="form_phone" />
</div>
<div class="field-group">
<label>Message:</label><textarea rows="4" cols="31" name="message" id="form_message"></textarea>
</div>
<div class="field-group">
<input type="image" src="<?php bloginfo('template_directory'); ?>/images/Send-Message-Arrow.png" width="90" height="72" class="form-button" />
</div>
</form>
Any information would be greatly appreciated. As I mentioned, I'm still learning PHP and I really want to understand what I'm writing - not just blindly copying & pasting code all the time. Thanks!
Your SMTP want to be configured, first check up that
and
//Header Information for mail
$headers = "YOUR HEADERS INFORMATION HERE";
$msg="Email: $email<br/>Phone Number: $phone<br/>Message: $message";
mail("emailaddress#example.com", $subject, $msg, $headers);
Please have look at Documentation.
You need to provide parameters as
mail($to, $subject, $message, $headers);
Here you have provided "to" email address right.
So this might help you:
$message = $_POST['message'];
//Give mail a subject
$subject = "YOUR SUBJECT HERE";
//Header Information for mail
$headers = "YOUR HEADERS INFORMATION HERE";
mail("emailaddress#gmail.com", $subject, $message, $headers);
$submit_message = "Thank you for your message";
Enjoy!
Kindly read this manual with the directives and examples on it and you'll understand well what you are doing. Just take your time to read and understand well then start asking your questions from that point. Right now, you don't seem to understand even how the PHP mail() works. Read then get back so together you'll understand any solutions pointed out to you and you won't just copy and paste the solution without being able to solve it tomorrow.
http://php.net/manual/en/function.mail.php