Error messages for dynamic input fields using PHP - php

I have created dynamic add/remove input fields. I want to pass certain validations for it. If the user keeps it blank, a message should get displayed after submitting the form. I want PHP validations to be displayed.
<div class="panel panel-default">
<div class="panel-heading"><center><b>Allocation of Funds</b></center></div>
<div class="panel-body">
<div class="row">
<div class="col-md-5"><label>Allocation Items <b style="color:#FF0000;">*</b></label></div>
<div class="col-md-5"><label>Amount <b style="color:#FF0000;">*</b></label></div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" name="allocate_items[]" placeholder=""></div>
</div>
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" name="allocate_amount[]" placeholder=""></div>
</div>
<div class="col-md-2">
<button type="button" class="btn btn-success" id="add-allocation-fields"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Add</button>
</div>
</div>
<div id="fund-allocation-fields"></div>
<p class="help-block"><i>Total amount must be equal to the goal amount.</i></p>
</div>
</div>
<script type="text/javascript">
var i = 0;
jQuery(document).ready(function($) {
//fadeout selected item and remove
$(document).on('click', '#remove-allocation-fields', function(event) {
event.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).parent().empty();
return false;
});
});
var rows = '<div class="fund-fields"><div class="row"><div class="col-md-5"><div class="form-group"><input type="text" class="form-control" name="allocate_items[]" placeholder=""></div></div><div class="col-md-5"><div class="form-group"><input type="text" class="form-control" name="allocate_amount[]" placeholder=""></div></div><div class="col-md-2"><button type="button" class="btn btn-danger" id="remove-allocation-fields"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> Remove</button></div></div><div class="clear"></div></div>';
//add input
$('#add-allocation-fields').click(function() {
$(rows).fadeIn("slow").appendTo('#fund-allocation-fields');
i++;
return false;
});
});
</script>
Thanks in advance!

Store one input value in a session variable or global session and compare it against required input value using a conditional statement. It's that simple.
like,
if(isset($_SESSION['A']) && empty(trim($_POST['RequiredField']))){
echo 'required field can\'t be empty';
}

I found the answer...
<?php
$errors = array();
if (isset($_POST['error_test'])) {
$allocate_items = $_POST['allocate_items'];
foreach ( $allocate_items as $key => $allocate_item ) {
if ( empty($allocate_item[$key])) {
$errors[$key] = '<p>Allocate Item field is required</p>';
}
}
if ( ! empty( $errors ) ) {
foreach ($errors as $key => $value) {
echo $value;
}
}
}
?>

Related

Insert multiple values in row php

I can`t find a solution for this formular, so i am asking you guys how i can solve this: (1)I have this formular:
<form id="formRetur" action="" method="POST" novalidate="novalidate">
<div id="mail-status" style="color: black;text-align: center;"></div>
<h3><strong>
Detalii client
</strong></h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nume_prenume" id="nume_prenume" placeholder="Nume Prenume">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nr_tlf" id="nr_tlf" placeholder="Numar telefon">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="adresa_email" id="adresa_email" placeholder="Adresa email">
</div>
</div>
</div>
<h3><strong>
Detalii comanda
</strong></h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nr_comanda" id="nr_comanda" placeholder="Numar comanda">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="data_comanda" id="data_comanda" placeholder="Data comanda">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nr_factura" id="nr_factura" placeholder="Numar factura">
</div>
</div>
</div>
<h3><strong>
Detalii produse
</strong></h3>
<div class="row">
<i class="fa fa-plus" aria-hidden="true" style="position: absolute;z-index:999;"></i>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="den_prod" id="den_prod" placeholder="Denumire produs">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="culoare_prod" id="culoare_prod" placeholder="Culoare produs">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="cantitate" id="cantitate" placeholder="Cantitate">
</div>
</div>
</div>
<div class="maimulte">
</div>
<h3><strong>
Motiv retur
</strong></h3>
<div class="row">
<div class="col-md-12">
<textarea name="motiv" id="motiv" class="form-control" cols="30" rows="10"></textarea>
</div>
</div>
<div class="row">
<div class="col-md-12" style="margin-top:10px;margin-bottom:10px;"><div class="g-recaptcha" data-sitekey="<?php echo SITE_KEY; ?>"></div> </div>
<div class="col-md-12">
<button type="submit" id="send-message" class="btn btn-default">Trimite </button>
</div>
<div id="loader-icon" style="display:none;"><img src="images/loader.gif"></div>
</div>
</form>
I use ajax to insert data in DB, but i have an option where you can add more products when user press + adding +1 row with 3 fields name,color, qty and i want to insert also these in db, here is my ajax:
<script>
$(document).ready(function (e){
$("#formRetur").on('submit',(function(e){
e.preventDefault();
$("#mail-status").hide();
$('#send-message').hide();
$('#loader-icon').show();
$.ajax({
url: "valid_retur.php",
type: "POST",
dataType:'json',
data: {
"nume_prenume":$('input[name="nume_prenume"]').val(),
"nr_tlf":$('input[name="nr_tlf"]').val(),
"adresa_email":$('input[name="adresa_email"]').val(),
"nr_comanda":$('input[name="nr_comanda"]').val(),
"data_comanda":$('input[name="data_comanda"]').val(),
"nr_factura":$('input[name="nr_factura"]').val(),
"den_prod":$('input[name="den_prod"]').val(),
"culoare_prod":$('input[name="culoare_prod"]').val(),
"cantitate":$('input[name="cantitate"]').val(),
"motiv":$('textarea[name="motiv"]').val(),
"g-recaptcha-response":$('textarea[id="g-recaptcha-response"]').val()},
success: function(response){
// $( '#frmContact' ).each(function(){
// this.reset();
// });
$("#mail-status").show();
$('#loader-icon').hide();
if(response.type == "error") {
$('#send-message').show();
$("#mail-status").attr("class","alert alert-danger");
} else if(response.type == "message"){
// grecaptcha.reset();
$('#send-message').show();
$("#mail-status").attr("class","alert alert-success");
}
$("#mail-status").html(response.text);
},
error: function(){}
});
}));
});
</script>
Here is my db:enter image description here
And there is my php file who insert in db with values from ajax:
<?php
if($_POST)
{
include('config.php');
$nume_prenume = filter_var($_POST["nume_prenume"], FILTER_SANITIZE_STRING);
$nr_tlf = filter_var($_POST["nr_tlf"], FILTER_SANITIZE_STRING);
$adresa_email = filter_var($_POST["adresa_email"], FILTER_SANITIZE_STRING);
$nr_comanda = filter_var($_POST["nr_comanda"], FILTER_SANITIZE_STRING);
$data_comanda = filter_var($_POST["data_comanda"], FILTER_SANITIZE_STRING);
$nr_factura = filter_var($_POST["nr_factura"], FILTER_SANITIZE_STRING);
$den_prod = filter_var($_POST["den_prod"], FILTER_SANITIZE_STRING);
$culoare_prod = filter_var($_POST["culoare_prod"], FILTER_SANITIZE_STRING);
$cantitate = filter_var($_POST["cantitate"], FILTER_SANITIZE_STRING);
$motiv = filter_var($_POST["motiv"], FILTER_SANITIZE_STRING);
if(empty($nume_prenume)) {
$empty[] = "<b>nume_prenume</b>";
}
if(empty($nr_tlf)) {
$empty[] = "<b>nr_tlf</b>";
}
if(empty($adresa_email)) {
$empty[] = "<b>adresa_email</b>";
}
if(empty($nr_comanda)) {
$empty[] = "<b>nr_comanda</b>";
}
if(empty($data_comanda)) {
$empty[] = "<b>data_comanda</b>";
}
if(empty($den_prod)) {
$empty[] = "<b>data_comanda</b>";
}
if(empty($culoare_prod)) {
$empty[] = "<b>data_comanda</b>";
}
if(!empty($empty)) {
$output = json_encode(array('type'=>'error', 'text' => implode(", ",$empty) . ' obligatoriu!'));
die($output);
}
// if(!filter_var($email2, FILTER_VALIDATE_EMAIL)){ //email validation
// $output = json_encode(array('type'=>'error', 'text' => '<b>'.$email2.'</b> is an invalid Email, please correct it.'));
// die($output);
// }
//reCAPTCHA validation
if (isset($_POST['g-recaptcha-response'])) {
require('component/recaptcha/src/autoload.php');
$recaptcha = new \ReCaptcha\ReCaptcha(SECRET_KEY, new \ReCaptcha\RequestMethod\SocketPost());
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$resp->isSuccess()) {
$output = json_encode(array('type'=>'error', 'text' => '<b>Captcha</b> Validation Required!'));
die($output);
}
}
// bag in db
$sql0 = "INSERT INTO retur (nume_prenume, nr_tlf, email, nr_comanda, data_comanda, nr_factura, den_prod, culoare_prod, cantitate_prod, motiv_retur)
VALUES ('$nume_prenume', '$nr_tlf', '$adresa_email', '$nr_comanda', '$data_comanda', '$nr_factura', '$den_prod', '$culoare_prod', '$cantitate', '$motiv')";
mysqli_query($conn, $sql0);
}
So basically this is a formular for returns products and if he have more products to return i added that jquery to add more fields and i want to be inserted in databased then i will fetch data and display it in my CMS.
1.You don't have to write that much code in ajax. You can easily use serialize():
Reduce you ajax code with below code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#your_form_id");
$("#Your_submit_id").click(function(){
$.ajax({
type:"POST",
url:"URL",
data:form.serialize(),
success: function(response){
console.log(response);
}
});
});
});
</script>
2.To add multiple product:
-You have to create every input field as array for product info like:
<input type="text" name="prod_name[]">
This array statement store you every product info index wise. If you
used normal variable then it will post only you last product
details.
In Php code you have to take the count of posted
product title & use for loop to get the every product information.
for($i=0;$i<count($prod_name);$i++)
{
//Insert/fetch All Values like : $prod_name[$i]
}
-When you click on add, just create clone of the prev available div.

Assigning a unique id on different modal content PHP

I have a table which is being populated by book information using a while loop to fetch and display the results. The table consist of Book information and an Action Column which handles some functions like adding of quantity and deduction of quantity , etc..
Each button on the Action Column is using a modal to show the needed contents
like text boxes.
So my main problem right now is the contents of the modal only works on the first data of the table. I don't know if I'm missing something here or im doing it wrong. Any help would be great! (Im using ajax to insert data)
I can update this post if you need the php code on binding data on the table.
HTML code for the modal
<!-- ADD STOCK QUANTITY -->
<div class="modal fade" id="addqty<?php echo $bookisbn;?>" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content ">
<div class="modal-header">
<h3 style="text-align: center;">Add Stock/s
</h3>
</div>
<div class="modal-body">
<!-- <form role="form" id="add_stock_form" name="add_stock_form"> -->
<div class="row clearfix">
<div class="col-md-12">
<div class="form-group form-float">
<div class="form-line">
<label for="book_isbn1" class="form-label">Book ISBN
</label>
<input type="text" class="form-control text-center" id="book_isbn_as" name="book_isbn_as" value="<?php echo $bookisbn;?>" readonly>
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12">
<div class="form-group form-float">
<div class="form-line">
<input type="hidden" class="form-control" id="book_title_as" name="book_title_as" value="<?php echo $booktitle;?>" readonly>
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-md-6">
<div class="form-group form-float">
<div class="form-line">
<input type="number" class="form-control text-center" id="currentstock_as" name="currentstock_as" value="<?php echo $bookquantity;?>" readonly>
<label for="currentstock" class="form-label">Current Stock/s
</label>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group form-float">
<div class="form-line">
<input min="0" class="form-control text-center" type="text" id="book_quantity_as" name="book_quantity_as" onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57" required>
<label for="book_quantity_as" class="form-label">Enter Stock
</label>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="btn_add_stock" name="btn_add_stock" class="btn btn-success waves-effect">
<i class="material-icons">add
</i> ADD
</button>
<button type="button" class="btn btn-danger waves-effect" data-dismiss="modal">
<i class="material-icons">clear
</i> CLOSE
</button>
</div>
</div>
</div>
</div>
<!-- END OF ADD STOCK QUANTITY -->
Ajax Script
// //add quantity
$(document).on("click", "#btn_add_stock", function() {
var getbookisbn = $("#book_isbn_as").val();
var getbooktitle = $("#book_title_as").val();
var getbookquantity = $("#book_quantity_as").val();
var getcurrentquantity = $("#current_stock_as").val();
var whatprocess = "ADDBOOKQUANTITY";
if (validationaddquantity == 1) {
$.ajax({
url: "adminfunctions.php",
method: "POST",
data: {
getbookisbn: getbookisbn,
getbooktitle: getbooktitle,
getbookquantity: getbookquantity,
whatprocess: whatprocess
},
success: function(data) {
var getdata = data.trim();
if (getdata == "SUCCESS") {
swal({
title: 'Success!',
text: 'Quantity Added',
type: 'success',
confirmButtonClass: "btn btn-success",
buttonsStyling: false
}).then(function() {
/////REFRESH DATATABLE
$("#datatables").load(window.location + " #datatables");
$('#book_quantity_as').val("");
});
} else if (getdata == "ERROR") {
swal({
title: 'Sorry...',
text: "You cannot perform that action right now",
type: 'error',
confirmButtonClass: "btn btn-danger",
buttonsStyling: false
}).then(function() {
fetch_data();
});
} else {
swal({
title: 'Sorry for the inconvenience!',
text: "There's a problem. Please contact the technical support for any concerns and questions.!",
type: 'error',
confirmButtonClass: "btn btn-danger",
buttonsStyling: false
}).catch(swal.noop)
}
},
error: function(jqXHR, exception) {
console.log(jqXHR);
}
});
} else if (validationaddquantity != 1) {
swal({
title: 'Oops..!',
text: 'You must enter a value to proceed',
type: 'warning',
confirmButtonClass: "btn btn-success",
buttonsStyling: false
}).catch(swal.noop)
}
});
on.show.bs.modal function trigger call you must re-assign value your row data (via ajax or get by td value on a table then post )to modal element input (i see is hidden input).
So every time call a modal your content data is shown based on click row table.
Maybe can solve ur problem..

Live check availability inside dynamic form

I have 2 forms, static and dynamic form. Dynamic is optional, depends on user if they want to submit more than one inputs. The insertion process works fine. Then, I have a function to check the availability for the input that user want to insert. The thing is, the live check availability only works in static form. How I want to call back the live check availability function inside the dynamic form? Your help is truly appreciate :)
index.php
//static form
<form action="" method="post" enctype="multipart/form-data">
<div class="field_wrapper">
<div class="row">
<div class="col-md-1">
<a rel="tooltip" title="Add" class="btn btn-info btn-icon add_button" href="javascript:void(0);"><i class="ti-plus"></i></a>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="control-label pull-left">Category<star>*</star>
</label>
<input class="form-control" type="text" name="cat[]" id="cat" title="This field needed" required="true" placeholder="Student"/><span id="usercheck3" class="help-block pull-left"></span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input class="btn btn-warning btn-fill btn-wd pull-right" name="submit2" id="submit2" type="submit" value="Add">
</div>
</div>
</div>
<br>
</form>
<script type="text/javascript">
$(document).ready(function(){
//live check availability
$('#cat').keyup(function() {
var usercheck3 = $(this).val();
$.post("check.php", {user_name3: usercheck3} , function(data)
{
if (data.status == true)
{
$('#usercheck3').parent('div').removeClass('has-error').addClass('has-success');
$('#submit2').attr("disabled", false);
} else {
$('#usercheck3').parent('div').removeClass('has-success').addClass('has-error');
$('#submit2').attr("disabled", true);
}
$('#usercheck3').html(data.msg);
},'json');
});
//dynamic form
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var fieldHTML = '<div class="form-group"><div class="row"><div class="col-md-1"><a rel="tooltip" title="Delete" class="btn btn-info btn-icon remove_button" href="javascript:void(0);"><i class="ti-minus"></i></a></div><div class="col-md-2"><label class="control-label pull-left">Category<star>*</star></label><input class="form-control" type="text" name="cat[]" id="cat" title="This field needed" required="true" placeholder="Student"/><span id="usercheck3" class="help-block pull-left"></span></div></div>';
var x = 1;
$(addButton).click(function(){
x++;
$(wrapper).append(fieldHTML);
});
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parents('.form-group').remove();
x--;
});
});
</script>
check.php
//db connection
if (isset($_POST['user_name3']) && $_POST['user_name3'] != '') {
$response = array();
$cat = $_POST['user_name3'];
$sql = "select cat from cat_tables where cat='" . $cat . "'";
$res = mysqli_query($con, $sql);
$count = mysqli_num_rows($res);
if ($count > 0) {
$response['status'] = false;
$response['msg'] = 'Not available';
} else {
$response['status'] = true;
$response['msg'] = 'Available';
}
}
echo json_encode($response);

Dropzone sending all queue of uploaded files to the controller once

I am trying to send multiple files in one request using DropZone js.
<script type="text/javascript">
Dropzone.autoDiscover = false;
var file= new Dropzone(".dropzone",{
url: any url,
method:"post",
paramName:"PhotoFiles",
addRemoveLinks:true,
autoProcessQueue: false
});
//Upload file onsubmit
$('#UploadMultiFiles').submit(function(){
file.processQueue();
});
file.on("sending",function(a,b,c){
a.token=Math.random();
c.append("token",a.token);
});
The issue is I have other inputs in the same form that is why I used onsubmit, and these inputs are saved in a table and the images from dropzone are saved in another table with and both tables have one to many relationship
The Controller like:
public function university_offers($id){
$data['university_offer_name']=$this->input->post('university_offer_name');
$data['university_id_fk']=$this->input->post('university_id_fk');
$data['university_offer_details']=$this->input->post('university_offer_details');
if ($this->input->post('save')){
$data2['university_offer_id_fk'] = insertrecords('university_offers',$data);
$data2['university_id_fk'] = $data['university_id_fk'];
//when I put the next IF at the begining of the function it works but ofcourse without the other data fields that I need.
if(isset($_FILES) && $_FILES != null){
$data2['photo_name'] = upload_image('PhotoFiles');
insertrecords('university_offer_photos',$data2);
}
if (insertrecords('university_offer_photos',$data2)==true)
message('success','');
redirect('Admin/university_offers/0','refresh');
}
$data['view']="admin/universities/university_offers";
$this->load->view('index',$data);
}
What I need is sending al uploaded files and do a loop in the controller to save it right in the database, not sending each file to the controller and saving it.
Edit:
My view is like:
<form action="university_offers/<?=$id?>" id="UploadMultiFiles" autocomplete="off" method="post" enctype="multipart/form-data" class="m-t-5" novalidate>
<div class="form-body">
<h3 class="card-title">بيانات العرض</h3>
<hr>
<div class="row p-t-20">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">إسم العرض<span class="text-danger">*</span></label>
<div class="controls">
<input type="text" autocomplete="off" name="university_offer_name" class="form-control" required value="<?php if(isset($result)) echo $result['university_offer_name']?>" data-validation-required-message="يجب إدخال إسم العرض" placeholder="إسم العرض">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">إسم الجامعة<span class="text-danger">*</span></label>
<div class="controls">
<select name="university_id_fk" id="select" class="form-control" required data-validation-required-message="يجب إختيار الجامعة" aria-invalid="false">
<option value="">إختر الجامعة</option>
<?php
foreach (selectrecords("*",'universities') as $university):
$select = '';
if(isset($result) && $result['university_id_fk'] == $university->university_id_pk)
$select = 'selected';
?>
<option <?=$select?> value="<?php echo $university->university_id_pk ?>"><?php echo $university->university_name ?></option>
<?php endforeach;?>
</select>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="control-label">تفاصيل العرض<span class="text-danger">*</span></label>
<div class="controls">
<textarea id="mymce" name="university_offer_details"><?php if(isset($result)) echo $result['university_offer_details'] ?></textarea>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="control-label">صور العرض<span class="text-danger">*</span></label>
<div class="row">
<?php
if(isset($result)) {
foreach (selectrecords('*','university_offer_photos',array('university_offer_id_fk'=>$result['university_offer_id_pk'])) as $photo):
echo'
<div class="form-group text-center" id="'.$photo->photo_id_pk.'">
<div class="col-md-12">
<img style="border: none; height: 150px; width: 150px; border-radius: 10px;" class="img-thumbnail" src="'.base_url().'public/uploads/images/'.$photo->photo_name.'">
</div>
حذف الملف
</div>
';
endforeach;
}
?>
</div>
<div class="dropzone">
<div class="dz-message">
<span> Drag and Drop your files here Or Click here to upload</span>
</div>
</div>
</div>
</div>
</div>
<div class="form-actions">
<input type="hidden" id="url" value="university_offers/<?=$id?>" />
<?php
if($id == 0)
echo '<button type="submit" id="butt" name="save" value="save" class="btn btn-primary"> <i class="fa fa-check"></i> حفظ</button>';
else
echo '<button type="submit" id="butt" name="edit" value="edit" class="btn btn-primary"><i class="fa fa-check"></i> حفظ</button>';
?>
<button type="reset" class="btn btn-inverse"><i class="fa fa-times"></i> إلغاء</button>
<?php
if($id == 0)
echo'<button type="button" id="backword" class="btn btn-second"><i class="fa fa-undo"></i> رجوع</button>';
else{
echo '<input type="hidden" name="university_offer_id_pk" value="'.$result['university_offer_id_pk'].'"/>
<button type="button" class="btn btn-second"><i class="fa fa-undo"></i> رجوع</button>';
}
?>
</div>
</div>
</form>
upload_image function, I put it in the Helper
function upload_image($file_name){
$CI =& get_instance();
$config['upload_path'] = 'public/uploads/images';
$config['allowed_types'] = 'gif|Gif|ico|ICO|jpg|JPG|jpeg|JPEG|BNG|png|PNG|bmp|BMP|WMV|wmv|MP3|mp3|FLV|flv|SWF|swf';
$config['max_size'] = '1024*8';
$config['encrypt_name']=true;
$CI->load->library('upload',$config);
if(! $CI->upload->do_upload($file_name)){
return false;
}else{
$datafile = $CI->upload->data();
thumb($datafile);
watermark($datafile);
return $datafile['file_name'];
}}

How to add email field to Stripe checkout for one-time payment

I am selling a product on my website. I have Stripe setup and have been accepting orders. I added a email field, however it is not saving to Stripe.
I'm not sure what I am doing wrong, if someone could offer some help. The email field is towards the bottom of the code.
popup_html.php
<div class="modal fade" id="model_stripe" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Credit Card Information</h4>
</div>
<div class="modal-body">
<div id="submit_card_info"></div>
<form class="form-horizontal te-ajax-form" id="upgrade_form" action="upgrade/payment" role="form">
<div class="form-group">
<label class="col-sm-3 control-label" for="">Card Number</label>
<div class="col-sm-9">
<input class="form-control required" name="cardnumber" id="cardnumber" type="text" placeholder="Card Number" value=""/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="">CVC</label>
<div class="col-sm-9">
<input class="form-control required" name="cvc" id="cvc" type="text" placeholder="CVC" value="" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="">Expiration</label>
<div class="col-sm-9">
<div class="row">
<div class="col-xs-6">
<select id="expMonth" style="width:100%;padding:5px;">
<?php
$year = date('Y');
for ($i=1; $i < 13; $i++) {
?>
<option value="<?php echo $i ?>"><?php echo $i ?></option>
<?php
}
?>
</select>
</div>
<div class="col-xs-6">
<select id="expYear" name="year" style="width:100%;padding:5px;">
<?php
$year = date('Y');
for ($i=1; $i < 21; $i++) {
?>
<option value="<?php echo $year+$i ?>"><?php echo $year+$i ?></option>
<?php
}
?>
</select>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="">E-mail Address</label>
<div class="col-sm-9">
<input class="form-control required" name="email" id="email" type="text" placeholder="Your E-mail Address" value=""/>
</div>
</div>
</form>
<form id="upgrade_form_token" class="te-ajax-form" action="inc/stripe_charge.php">
Stripe_handler.php:
<?php
require_once ('stripe/lib/Stripe.php');
define('PRICE',9.99);
$stripe = array(
'secret_key' => ' sk_test_665545656565656 ',
'publishable_key' => 'pk_test_35845754785784578'
);
Stripe::setApiKey($stripe['secret_key']);
?>
<script type="text/javascript" src="https://js.stripe.com/v1/"></script>
<script type="text/javascript">
Stripe.setPublishableKey("<?php echo $stripe['publishable_key']; ?>");
jQuery(document).ready(function() {
jQuery('#model_stripe .extra_items input').change(function(){
if( jQuery(this).attr('name')=='info[addon3]' ){
if( jQuery(this).is(':checked') ) {
jQuery('#saNotes').show();
} else {
jQuery('#saNotes').hide();
}
}
var extra_for_stripe = 0;
jQuery('#model_stripe .extra_items input:checked').each(function(){
extra_for_stripe += Number(jQuery(this).val());
});
var notes = false;
var total_charges = extra_for_stripe+(<?php echo PRICE ?>);
jQuery('#upgrade_form_token').find('[name="amount"]').val(total_charges);
jQuery('#model_stripe .total_charges').text('$'+total_charges)
});
jQuery("#proceed_stripe").click(function(event) {
jQuery('#submit_card_info .payment-message').remove();
var card_no = jQuery('#cardnumber').val();
var cvc = jQuery('#cvc').val();
if(card_no.length==0){
var errorHTML = '<div class="payment-message alert alert-danger alert-dismissable fade in"><button class="close" data-dismiss="alert">×</button ><p>Card Number is required.</p></div>';
jQuery("#submit_card_info").prepend(errorHTML);
return false;
}
if(cvc.length==0){
var errorHTML = '<div class="payment-message alert alert-danger alert-dismissable fade in"><button class="close" data-dismiss="alert">×</button ><p>CVS is required.</p></div>';
jQuery("#submit_card_info").prepend(errorHTML);
return false;
}
// jQuery('#model_stripe .modal-footer button ').attr('disabled',true);
Stripe.createToken({
number: card_no,
cvc: cvc,
exp_month: jQuery('#expMonth').val(),
exp_year: jQuery('#expYear').val(),
}, stripeResponseHandler);
return false; // submit from callback
});
});
function stripeResponseHandler(status, response) {
if (response.error) {
jQuery('#upgrade_button').removeAttr("disabled");
// show the errors on the form
var errorHTML = '<div class="payment-message alert alert-danger alert-dismissable fade in"><button class="close" data-dismiss="alert">×</button ><p>'+response.error.message+'</p></div>';
jQuery("#submit_card_info").prepend(errorHTML);
}
else {
var form = jQuery("#proceed_stripe");
// token contains id, last4, and card type
var token = response['id'];
// insert the token into the form so it gets submitted to the server
jQuery('#upgrade_form_token input[name="stripeToken"]').val(token);
jQuery('#footer-form input[type="text"], #footer-form select').each(function(){
var h = '<input value="'+jQuery(this).val()+'" name="info['+jQuery(this).attr('name')+']" type="hidden">';
jQuery('#upgrade_form_token').append(h);
});
jQuery('#upgrade_form_token').submit();
}
}
function upgrade_form_token_success(form,resp){
jQuery('#submit_card_info .payment-message').remove();
if( resp.type=='success'){
var h = '<div style="display: block;font-size: 16px;padding-bottom: 10px;font-weight: bold;">Thanks for buying. Buy More</div>';
jQuery("#model_stripe .modal-body").html(h);
jQuery("#model_stripe .modal-footer").remove();
jQuery("#model_stripe .modal-backdrop").css({
'opacity':1,
'background-color':'#fff',
});
} else {
jQuery("#submit_card_info").append(bs_alert('danger',resp.msg ) );
}
}
</script>
Stripe has some good documentation on converting an existing form to a Stripe form # https://stripe.com/docs/stripe.js/switching.
(1) Note that you remove the the name attribute from all sensitive input fields ( as noted by michael above) Unless you are running a PCI compliant server, this is critical.
(2) When you parse your form and try and finally try and charge the card, you want to pass in the email address as receipt_email:customer#email.com (see https://stripe.com/docs/api#create_charge)
Hope this helps!

Categories