I have post ajax data with all data from form. Users can add dynamically blocks with rows for previous employers. [empName] maybe 10 or 20 ... or 2 ...How to catch count of previous employers have and save it to variable?
Here is post data:
["step-3"]=> string(1065) "{
"empYrXp":"min10yexp",
"empName-1":"TEST PAYPAL TEST",
"empStr-1":"TEST ORDER PAYPAL",
"empCity-1":"Pleven",
"empState-1":"CT",
"empContactPerson-1":"mbnmbnmbnm",
"empContactPersonPhone-1":"999-999-9999",
"empFromDate-1":"08-2013",
"empToDate-1":"06-2019",
"empPositionHeld-1":"bnmb",
"empReasonForLeaving-1":"nmbnmbnmbnm",
"empWereSubject-1":"No",
"empWasPrevJobDesignated-1":"No",
"empName-2":"TEST PAYPAL TEST",
"empStr-2":"TEST ORDER PAYPAL",
"empCity-2":"Pleven",
"empState-2":"CA",
"empContactPerson-2":"fghfhfhfgh",
"empContactPersonPhone-2":"999-999-9999",
"empFromDate-2":"02-2008",
"empToDate-2":"08-2013",
"empPositionHeld-2":"fghfgh",
"empReasonForLeaving-2":"fghfghfgh",
"empWereSubject-2":"No",
"empWasPrevJobDesignated-2":"No",
"empName-3":"TEST TEST",
"empStr-3":"TEST ORDER PAYPAL",
"empCity-3":"Pleven",
"empState-3":"CA",
"empContactPerson-3":"sdfsdfsdfsdf",
"empContactPersonPhone-3":"999-999-9999",
"empFromDate-3":"01-2006",
"empToDate-3":"01-2006",
"empPositionHeld-3":"sdfsdfs",
"empReasonForLeaving-3":"dfsdfsdfsdf",
"empWereSubject-3":"No",
"empWasPrevJobDesignated-3":"No"
}"
i try to count prevouse employer like this
$countAllEmp = ( count($jsonDecode3) - 1 ) / 12;
but when i try save data, the endless rotation of the query ...
here is what i am tried:
for($b = 1; $b <= $countAllEmp; $b++){
if(isset($jsonDecode3["empName-".$b.""]) && $jsonDecode3["empName-".$b.""]!=''){
$empName.$b = $jsonDecode3["empName-".$b.""];
}else{
$empName.$b = '';
}
if(isset($jsonDecode3["empStr-".$b.""]) && $jsonDecode3["empStr-".$b.""]!=''){
$empStr.$b = $jsonDecode3["empStr-".$b.""];
}else{
$empStr.$b = '';
}
if(isset($jsonDecode3["empCity-".$b.""]) && $jsonDecode3["empCity-".$b.""]!=''){
$empCity.$b = $jsonDecode3["empCity-".$b.""];
}else{
$empCity.$b = '';
}
if(isset($jsonDecode3["empState-".$b.""]) && $jsonDecode3["empState-".$b.""]!=''){
$empState.$b = $jsonDecode3["empState-".$b.""];
}else{
$empState.$b = '';
}
if(isset($jsonDecode3["empContactPerson-".$b.""]) && $jsonDecode3["empContactPerson-".$b.""]!=''){
$empContactPerson.$b = $jsonDecode3["empContactPerson-".$b.""];
}else{
$empContactPerson.$b = '';
}
if(isset($jsonDecode3["empContactPersonPhone-".$b.""]) && $jsonDecode3["empContactPersonPhone-".$b.""]!=''){
$empContactPersonPhone.$b = $jsonDecode3["empContactPersonPhone-".$b.""];
}else{
$empContactPersonPhone.$b = '';
}
if(isset($jsonDecode3["empFromDate-".$b.""]) && $jsonDecode3["empFromDate-".$b.""]!=''){
$empFromDate.$b = $jsonDecode3["empFromDate-".$b.""];
}else{
$empFromDate.$b = '';
}
if(isset($jsonDecode3["empToDate-".$b.""]) && $jsonDecode3["empToDate-".$b.""]!=''){
$empToDate.$b = $jsonDecode3["empToDate-".$b.""];}else{$empToDate.$b = '';
}
if(isset($jsonDecode3["empPositionHeld-".$b.""]) && $jsonDecode3["empPositionHeld-".$b.""]!=''){
$empPositionHeld.$b = $jsonDecode3["empPositionHeld-".$b.""];
}else{
$empPositionHeld.$b = '';
}
if(isset($jsonDecode3["empReasonForLeaving-".$b.""]) && $jsonDecode3["empReasonForLeaving-".$b.""]!=''){
$empReasonForLeaving.$b = $jsonDecode3["empReasonForLeaving-".$b.""];
}else{
$empReasonForLeaving.$b = '';
}
if(isset($jsonDecode3["empWereSubject-".$b.""]) && $jsonDecode3["empWereSubject-".$b.""]!=''){
$empWereSubject.$b = $jsonDecode3["empWereSubject-".$b.""];
}else{
$empWereSubject1.$b = '';
}
if(isset($jsonDecode3["empWasPrevJobDesignated-".$b.""]) && $jsonDecode3["empWasPrevJobDesignated-".$b.""]!=''){
$empWasPrevJobDesignated.$b = $jsonDecode3["empWasPrevJobDesignated-".$b.""];
}else{
$empWasPrevJobDesignated.$b = '';
}
}
this is the button for add new box with all inputs:
function addEmployers(years) {
var $ = jQuery,
html = '<div class="employers"> <div class="employer"> <p class="text-center">Employer #1 : (the most recent)</p><div class="row"> <div class="col-sm-5 col-sm-offset-1 text-right"> <label>Name: *</label> </div><div class="col-sm-6 form-group"> <input type="text" class="form-control" id="empName-1" name="empName-1" data-validation="length" data-validation-length="1-100"> </div></div><div class="row"> <div class="col-sm-5 col-sm-offset-1 text-right"> <label>Street: *</label> </div><div class="col-sm-6 form-group"> <input type="text" class="form-control" id="empStr-1" name="empStr-1" data-validation="letternumeric" data-validation-allowing="-,.\'` "> </div></div><div class="row"> <div class="col-sm-5 col-sm-offset-1 text-right"> <label>City: *</label> </div><div class="col-sm-6 form-group"> <input type="text" class="form-control" id="empCity-1" name="empCity-1" data-validation="length" data-validation-length="1-100"> </div></div><div class="row"> <div class="col-sm-5 col-sm-offset-1 text-right"> <label>State: *</label> </div><div class="col-sm-6 form-group"> <select class="form-control" id="empState-1" name="empState-1" data-validation="length" data-validation-length="min1">' + genStates() + '</select> </div></div><div class="row"> <div class="col-sm-5 col-sm-offset-1 text-right"> <label>Contact person: *</label> </div><div class="col-sm-6 form-group"> <input type="text" class="form-control" id="empContactPerson-1" name="empContactPerson-1" data-validation="length" data-validation-length="1-100"> </div></div><div class="row"> <div class="col-sm-5 col-sm-offset-1 text-right"> <label>Phone number: *</label> </div><div class="col-sm-6 form-group"> <input type="text" class="form-control phone-mask" id="empContactPersonPhone-1" placeholder="123-456-7890" name="empContactPersonPhone-1" data-validation="custom" data-validation-regexp="^([0-9]{3}\-[0-9]{3}\-[0-9]{4})$"> </div></div><div class="row"> <div class="col-sm-5 col-sm-offset-1 text-right"> <label>Date from: *</label> </div><div class="col-sm-6 form-group"> <input type="text" class="form-control datepicker-no-day" id="empFromDate-1" name="empFromDate-1" data-validation="' + years + '" data-validation-format="mm-yyyy" readonly> </div></div><div class="row"> <div class="col-sm-5 col-sm-offset-1 text-right"> <label>Date to: *</label> </div><div class="col-sm-6 form-group"> <input type="text" class="form-control datepicker-no-day" id="empToDate-1" name="empToDate-1" data-validation="' + years + '" data-validation-format="mm-yyyy" readonly> </div></div><div class="row"> <div class="col-sm-5 col-sm-offset-1 text-right"> <label>Position held: *</label> </div><div class="col-sm-6 form-group"> <input type="text" class="form-control" id="empPositionHeld-1" name="empPositionHeld-1" data-validation="length" data-validation-length="1-100"> </div></div><div class="row"> <div class="col-sm-5 col-sm-offset-1 text-right"> <label>Reason for leaving: *</label> </div><div class="col-sm-6 form-group"> <input type="text" class="form-control" id="empReasonForLeaving-1" name="empReasonForLeaving-1" data-validation="length" data-validation-length="1-100"> </div></div><div class="row"> <div class="col-sm-5 col-sm-offset-1 text-right"> <label>Were you subject to the Federal Motor Carrier Safety Regulations (FMCSRs) while employed by the previous employer? *</label> </div><div class="col-sm-6 form-group"> <label class="radio-inline"> <input type="radio" name="empWereSubject-1" value="Yes" data-validation="required"> Yes </label> <label class="radio-inline"> <input type="radio" name="empWereSubject-1" value="No" data-validation="required"> No </label> </div></div><div class="row"> <div class="col-sm-5 col-sm-offset-1 text-right"> <label>Was the previous job position designated as a safety sensitive function in any DOT regulated mode, subject to alcohol and controlled substances testing requirements as required by 49 CFR Part 40? *</label> </div><div class="col-sm-6 form-group"> <label class="radio-inline"> <input type="radio" name="empWasPrevJobDesignated-1" value="Yes" data-validation="required"> Yes </label> <label class="radio-inline"> <input type="radio" name="empWasPrevJobDesignated-1" value="No" data-validation="required"> No </label> </div></div></div><div class="text-center"> <button class="text-center btn btn-danger add-prev-emp" onclick="addPrevEmp(\'' + years + '\')" disabled>Add previous employer</button> </div></div>';
$(html).insertAfter($('.empAfterHere'));
setTimeout(function () {
setupValidate();
$('.datepicker-no-day').datetimepicker({
format: 'MM-YYYY',
ignoreReadonly: true,
maxDate: moment()
});
$('.datepicker-no-day').on('dp.change', function (e) {
var target = $(e.currentTarget);
var id = target.attr('id');
var idNum = parseInt(id.substring(id.length - 1));
if (target.is('[id^="empFromDate"]')) {
$('#empToDate-' + idNum).data('DateTimePicker').minDate(e.date);
if ($('#empFromDate-' + (idNum + 1)).length > 0) {
$('#empFromDate-' + (idNum + 1)).data('DateTimePicker').maxDate(e.date);
$('#empToDate-' + (idNum + 1)).data('DateTimePicker').maxDate(e.date);
}
}
});
// Mask some fields
$('.phone-mask').mask('999-999-9999');
}, 500);
}
Don't know how you get your json, but forms support naming with [] which results in arrays on server side:
<input name="someName[]" />
<input name="someName[]" />
<input name="someName[]" />
Try outputting $_POST['someName'], it will be 0-indexed array with 3 elements.
Moreover, you can define indexes in [] explicitly:
<input name="someName[11]" />
<input name="someName[12]" />
<input name="someName[13]" />
Try outputting $_POST['someName'], it will be array with 3 keys - 11, 12, 13.
So, you have to rename you fields instead of empName-, empStr- etc. - use [] notation: empName[], empStr[] etc.
Related
I am looking to submit 2 forms with 1 single submission button. So 2 lines that will be added in my database at the time of submission.
here's what i started doing:
HTML:
<form enctype="multipart/form-data" method="POST" action="{$link->getModuleLink('blocksouhaits', 'create', ['action' => 'create'], true)|escape:'html'}">
<div class="col-md-6">
<h1>{l s='Souhait N°1' mod='blocksouhaits'}</h1>
<input type="hidden" name="souhait[]" value="1">
<div class="form-group row">
<label for="nbVoyager_1"
class="col-sm-10 col-form-label">{l s='Nombre de voyageurs' mod='blocksouhaits'}</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="nbVoyager_1">
</div>
</div>
<div class="infos-voyager_1"></div>
<div class="form-group row">
<label class="col-sm-4 col-form-label" for="locationVoyager_1">{l s='Votre location' mod='blocksouhaits'}</label>
<div class="col-sm-8">
<select class="form-control" name="locationVoyager_1" id="locationVoyager_1">
{foreach $productLoc as $pl}
<option value="{$pl.id_product}">{$pl.name}</option>
{/foreach}
</select>
</div>
</div>
</div>
<div class="col-md-6">
<h1>{l s='Souhait N°2' mod='blocksouhaits'}</h1>
<input type="hidden" name="souhait[]" value="2">
<div class="form-group row">
<label for="nbVoyager_2"
class="col-sm-10 col-form-label">{l s='Nombre de voyageurs' mod='blocksouhaits'}</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="nbVoyager_2">
</div>
</div>
<div class="infos-voyager_2"></div>
<div class="form-group row">
<label class="col-sm-4 col-form-label" for="locationVoyager_2">{l s='Votre location' mod='blocksouhaits'}</label>
<div class="col-sm-8">
<select class="form-control" name="locationVoyager_2" id="locationVoyager_2">
{foreach $productLoc as $pl}
<option value="{$pl.id_product}">{$pl.name}</option>
{/foreach}
</select>
</div>
</div>
</div>
<div class="col-sm-12">
<button class="btn btn-primary float-xs-right" type="submit" name="submitSouhaits">
{l s='Envoyer la demande de souhait' mod='customerannonces'}
</button>
</div>
</form>
PHP:
public function postProcess()
{
if (Tools::getValue('action') == 'create') {
if (Tools::isSubmit('submitSouhaits')) {
$submit = $_POST;
dump($submit);
}
}
}
JS:
$(document).ready(function () {
$("#nbVoyager_1").change(function () {
var i = 0;
var rows = $(this).val();
$(".infos-voyager_1").empty();
for (i = 0; i < rows; i++) {
$(".infos-voyager_1").append(
'<div class="form-group row">' +
'<div class="col-sm-6">' +
'<input type="text" class="form-control" id="firstnameVoyager_1" name="firstnameVoyager_1[]" placeholder="Prénom">' +
'</div>' +
'<div class="col-sm-6">' +
'<input type="text" class="form-control" id="lastnameVoyager_1" name="lastnameVoyager_1[]" placeholder="Nom">' +
'</div>' +
'</div>');
}
});
$("#nbVoyager_2").change(function () {
var j = 0;
var rows = $(this).val();
$(".infos-voyager_2").empty();
for (j = 0; j < rows; j++) {
$(".infos-voyager_2").append(
'<div class="form-group row">' +
'<div class="col-sm-6">' +
'<input type="text" class="form-control" id="firstnameVoyager_2" name="firstnameVoyager_2[]" placeholder="Prénom">' +
'</div>' +
'<div class="col-sm-6">' +
'<input type="text" class="form-control" id="lastnameVoyager_2" name="lastnameVoyager_2[]" placeholder="Nom">' +
'</div>' +
'</div>');
}
});
});
in the form there is:
a field to define the number of people, this will automatically add X fields according to this number and another fields to choose the location. The 2 forms are identical.
The result of the var_dump to the submission.
But I do not see how to do the submission properly in PHP. Do you have a solution to submit to me?
Thanks for help.
i'm new with angular 5.
I'm trying to populate a form with data from a database.
So far this it hid my form and from the ts side it only shows null.
PHP code:
include ('conexion.php');
$id = $_GET['id'];
$sql = "SELECT * FROM tbl_usuario WHERE id=".$id;
if($con){
if(!$result = mysqli_query($con,$sql)) die();
while($data = mysqli_fetch_assoc($result)){
$arreglo[] = $data;
}
echo json_encode($arreglo);
}else{
die ("error");
}
form.html:(the ngModel i used with or without brackets)
<div class="forms">
<form method="post" *ngFor="let x of datos">
<div class="form-row">
<div class="form-group col-md-4">
<label>Nombre</label>
<input type="text" class="form-control col-10" (ngModel)="x.nombre" name="nombre" value="x.nombre" />
</div>
<div class="form-group col-md-4">
<label>Apellido Paterno</label>
<input type="text" class="form-control col-10" (ngModel)="x.a_paterno" name="a_paterno" value="x.a_paterno" required/>
</div>
<div class="form-group col-md-4">
<label>Apellido Materno</label>
<input type="text" class="form-control col-10" (ngModel)="x.a_materno" name="a_materno" value="x.a_materno" required/>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Edad</label>
<input type="text" class="form-control col-10" (ngModel)="x.edad" name="edad" value="x.edad" required/>
</div>
<div class="form-group col-md-6">
<label>Carrera</label>
<input type="text" class="form-control col-10" (ngModel)="x.carrera" name="carrera" value="x.carrera" required />
</div>
<div class="col-md-10">
<label>Direccion</label>
<input type="text" class="form-control col-12" (ngModel)="x.direccion" name="direccion" value="x.direccion" required/>
</div>
<div class="col-md-10">
<br>
<label>Telefono</label>
<input type="text" class="form-control col-12" (ngModel)="x.telefono" name="telefono" value="x.telefono" required/>
</div>
</div>
<br>
<button type="submit" class="btn btn-primary">Enviar Datos</button>
<br>
<br>
</form>
</div>
form.ts:
constructor(private http: HttpClient, private router: Router, private route: ActivatedRoute) {
this.mostrarDatos();
}
ngOnInit() {
this.route.params.subscribe(params => {
this.id = params['id']; // (+) converts string 'id' to a number
console.log('Mi id' + this.id);
});
}
mostrarDatos() {
console.log(this.id);
this.http.get('http://localhost/crudu/mostrarID.php?id=' + this.id).subscribe((data) => {
this.datos = data;
console.log(this.datos);
});
}
I've been trying with many solutions but nothing at the end.
Also in my route or url it shows as eUsuario/1
Try to replace (ngModel) with [(ngModel)]. Currently you have a binding from the input into model but not vice versa.
Remove the call of mostrarDatos from the constructor and call it after you get the id.
this.route.params.subscribe(params => {
this.id = params['id']; // (+) converts string 'id' to a number
console.log('Mi id' + this.id);
this.mostrarDatos();
});
If i select Local Sales from dorpdown and enter DEF, GHI values then the sum of DEF,GHI should be displayed in total value or if i select Inter State,Stock Transfers from dropdown then if we enter ABC value that value should be displayed in total value or else if we select JOB WORK,EXEMPTED SALES from dropdown then the total value should be displayed as zero. The total value which ever we are getting that should be inserted into database.
Controller:
function addinvoice()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<br /><span class="error"> ','</span>');
$this->form_validation->set_rules('user','User');
$this->form_validation->set_rules('freight_charges');
$this->form_validation->set_rules('abc');
$this->form_validation->set_rules('def');
$this->form_validation->set_rules('ghi');
$this->form_validation->set_rules('total');
if($this->form_validation->run()== FALSE)
{
$data['mainpage']='invoice';
$data['mode']='add';
$this->load->view('templates/template',$data);
}
else
{
$this -> invoice_model -> insert();
$this->flash->success('<h2> Details added Successfully!</h2>');
redirect('invoice');
}
}
Model:
function insert()
{
$data['total']=0;
$data['user'] = $this->input->post('user');
$data['ghi'] = ($this->input->post('ghi'))?$this->input->post('ghi'):0;
$data['abc'] = ($this->input->post('abc'))?$this->input->post('abc'):0;
$data['def'] = ($this->input->post('def'))?$this->input->post('def'):0;
$data['total'] = $data['ghi'] + $data['abc'] + $data['def'];
$data['freight_charges'] = $this->input->post('freight_charges');
$this->db->insert('invoice',$data);
}
View:
<script>
function showRequiredOption(cval)
{
if((cval=='interstate') || (cval == "stocktransfers"))
{
$('#ghi').hide();
$('#def').hide();
$('#abc').show();
}
else if ((cval=='exemptedsales') || (cval=="zeroratedsales") ||(cval=="jobwork"))
{
$('#ghi').hide();
$('#def').hide();
$('#abc').hide();
}
else
{
$('#abc').hide();
$('#ghi').show();
$('#def').show();
}
}
</script>
<div class="col-md-9 col-md-offset-2">
<div id="legend">
<legend class="">Profile Information</legend>
</div>
<form role="form" action="<?php echo site_url();?>invoice/addinvoice" method="post" class="form-horizontal" id="location" method="post" accept-charset="utf-8">
<div class="form-group">
<label class="control-label col-sm-2 " for="user">User</label>
<div class="col-sm-4 col-sm-offset-1">
<select id="user" name="user" onchange="showRequiredOption(this.value)">
<option value="employee">Local Sales</option>
<option value="interstate">Inter state</option>
<option value="stocktransfers">Stock transfers</option>
<option value="exemptedsales">Exempted Sales</option>
<option value="zeroratedcompany">Zero Rated Sales</option>
<option value="jobwork">Job Work</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2 " for="freight_charges">Freight Charges</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="freight_charges" name="freight_charges" value="<?php echo set_value('freight_charges');?>" />
</div>
</div>
<div class="form-group" id="abc" style="display:none;">
<label class="control-label col-sm-2 " for="abc">ABC</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="abc" name="abc" value="<?php echo set_value('abc');?>"/ >
</div>
</div>
<div class="form-group" id="def">
<label class="control-label col-sm-2 " for="def">DEF </label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="def" name="def" value="<?php echo set_value('def');?>"/ >
</div>
</div>
<div class="form-group" id="ghi">
<label class="control-label col-sm-2 " for="ghi">GHI</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="ghi" name="ghi" value="<?php echo set_value('ghi');?>"/ >
</div>
</div>
<div class="form-group" id="cgst">
<label class="control-label col-sm-2 " for="total">Total</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" name="total" >
</div>
</div>
<button id="submit" type="submit" class="btn" name="submit">Submit</button>
</form>
</div>
Whatever values i have selected from dropdown only those values to be inserted into database and the rest of the values should be inserted as zero in the database.
Actually i am not getting how to do these can anyone check this.Thanks in Advance.
you should check for posted values in your php code as:
$total = 0;
if($this->input->post('this')){
$total = $this->input->post('this');//value in total
}
if($this->input->post('this2')){
$total += $this->input->post('this2');//value in total
}
and at the end send $total value in db as well.
in short php if else tags you can set variables like;
$this = ($this->input->post('this'))?$this->input->post('this'):0;
$this2 = ($this->input->post('this2'))?$this->input->post('this2'):0;
and then at the end you can make total of them and save them to database. OR as suggested above in comments that make your columns as DEFAULT 0 in your table.
------- IN YOUR CASE------
function insert()
{
$data['total']=0;
$data['user'] = $this->input->post('user');
$data['ghi'] = ($this->input->post('ghi'))?$this->input->post('ghi'):0;
$data['abc'] = ($this->input->post('abc'))?$this->input->post('abc'):0;
$data['def'] = ($this->input->post('def'))?$this->input->post('def'):0;
$data['total'] = $data['ghi'] + $data['abc'] + $data['def'];
$data['freight_charges'] = $this->input->post('freight_charges');
$this->db->insert('invoice',$data);
}
---------------IN JavaScript------------
on your event handler you can sum these by their IDs.
var total = parseInt($('#ghi').val())+parseInt($('#def').val());
and then show this total in your total div
$('#yourTotalDiv').text(total);
Displaying total amount on enter the details.
<script>
function showRequiredOption(cval)
{
if((cval=='interstate') || (cval == "stocktransfers"))
{
$('#ghi').hide();
$('#def').hide();
$('#abc').show();
}
else if ((cval=='exemptedsales') || (cval=="zeroratedsales") || (cval=="jobwork"))
{
$('#ghi').hide();
$('#def').hide();
$('#abc').hide();
}
else
{
$('#abc').hide();
$('#ghi').show();
$('#def').show();
}
}
</script>
<script>
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
</script>
<div class="col-md-9 col-md-offset-2">
<div id="legend">
<legend class="">Profile Information</legend>
</div>
<form role="form" action="<?php echo site_url();?>invoice/addinvoice" method="post" class="form-horizontal" id="location" method="post" accept-charset="utf-8">
<div class="form-group">
<label class="control-label col-sm-2 " for="user">User</label>
<div class="col-sm-4 col-sm-offset-1">
<select id="user" name="user" onchange="showRequiredOption(this.value)">
<option value="employee">Local Sales</option>
<option value="interstate">Inter state</option>
<option value="stocktransfers">Stock transfers</option>
<option value="exemptedsales">Exempted Sales</option>
<option value="zeroratedcompany">Zero Rated Sales</option>
<option value="jobwork">Job Work</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2 " for="freight_charges">Freight Charges</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control txt" id="freight_charges" name="freight_charges" value="<?php echo set_value('freight_charges');?>" />
</div>
</div>
<div class="form-group" id="abc" style="display:none;">
<label class="control-label col-sm-2 " for="abc">ABC</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control txt" id="abc" name="abc" value="<?php echo set_value('abc');?>"/ >
</div>
</div>
<div class="form-group" id="def">
<label class="control-label col-sm-2 " for="def">DEF </label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control txt" id="def" name="def" value="<?php echo set_value('def');?>"/ >
</div>
</div>
<div class="form-group" id="ghi">
<label class="control-label col-sm-2 " for="ghi">GHI</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control txt" id="ghi" name="ghi" value="<?php echo set_value('ghi');?>"/ >
</div>
</div>
<div class="form-group" id="summation">
<label class="control-label col-sm-2 " for="total">Total</label>
<div class="col-sm-4 col-sm-offset-1">
<span id="sum" class="form-control" type="text" name="total">0</span>
</div>
</div>
<button id="submit" type="submit" class="btn" name="submit">Submit</button>
</form>
</div>
I am using Rivets to bind my form data. Is there any way to bind my input type file with the help rivet binders.
Like in this example https://jsfiddle.net/steinbring/v29vnLuh/ You can see that we bind text area . But how will we bind over input file .
Let me explain more
here is my form
<form class="product-inputs full-width-inputs" method="post" action="/create/save-manual-products-shopify">
<section id="rivettest">
<ul class="no-bullet">
<li class="product-input-header">
<div class="row no-padding">
<div class="small-2 columns">
<p>Product Name</p>
</div>
<div class="small-2 columns">
<p>Product Detail</p>
</div>
<div class="small-2 columns">
<p>Product Type</p>
</div>
<div class="small-2 columns">
<p>Price</p>
</div>
<div class="small-2 columns floatleft">
<p>Sku</p>
</div>
<div class="small-2 columns floatleft">
<p>Image</p>
</div>
</div>
</li>
<li class="product-input" rv-each-product="products">
<div class="row no-padding">
<div class="small-2 columns" style="position: relative">
<input class="product-name-input" type="text" rv-value="product.name" placeholder="New Product"/>
<span class="icon-error remove-btn" rv-on-click="controller.removeItem"></span>
</div>
<div class="small-2 columns">
<input type="text" rv-value="product.product_detail"/>
</div>
<div class="small-2 columns">
<input type="text" rv-value="product.product_type"/>
</div>
<div class="small-2 columns">
<input type="text" rv-value="product.price">
</div>
<div class="small-2 columns">
<input type="text" rv-value="product.sku">
</div>
<div class="small-2 columns">
<input type="file" rv-value="product.image">
<!-- <input type="file"> -->
<!-- <span class="icon-upload"></span> Upload Image -->
</div>
</div>
</li>
<li class="additem">
<span class="icon-plus"></span>Add Product Manually
</li>
</ul>
</section>
<input type="submit" value="Submit for KF Approval" class="button radius add-product-shopify" >
</form>
And here is my script
var products = [];
var controller = {
addItem: function(e, model) {
model.products.push({name: "New Product", product_detail: "", product_type: "", price: null, sku: null, image: ""});
e.preventDefault();
return false;
},
removeItem: function(e, model) {
var index = model.index;
if (index > -1) {
products.splice(index, 1);
}
},
};
rivets.bind($('#rivettest'), {products: products, controller: controller});
But when i submit my form i got this response
image: ""
name: "a"
price: "12"
product_detail: "b"
product_type: "c"
sku: "12"
Here you see that image param is empty ... please help me .Thanks
Here's a working example written in coffescript
controller = (el, data) ->
that = this
#email_valid = false
#update = ->
if #type == "file"
data[#id] = #files[0]
else
data[#id] = #value
#submit = ->
_data = new FormData()
Object.keys(data).forEach( (key) ->
_data.append(key, data[key])
)
req = new XMLHttpRequest()
req.open('POST', 'addUser', true)
req.onreadystatechange = (aEvt) ->
if req.readyState == 4
if req.status == 200
return req.responseText
else
return "Erreur pendant le chargement de la page.\n"
req.send(_data)
#email_validate = ->
re = /\S+#\S+\.\S+/
return re.test data.email
return this
rivets.components['user'] = {
# Return the template for the component.
template: ->
return tpl
# Takes the original element and the data that was passed into the
# component (either from rivets.init or the attributes on the component
# element in the template).
initialize: (el, data) ->
return new controller(el, data)
}
the form
<form enctype="multipart/form-data" class="form-horizontal" id="userForm">
<fieldset>
<!-- Form Name -->
<legend>Form Name</legend>
<!-- File Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="picture">Photo</label>
<div class="col-md-4">
<input rv-value="picture" rv-on-change="update" id="picture" name="picture" class="input-file" type="file">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Name</label>
<div class="col-md-4">
<input rv-value="name" id="name" rv-on-input="update" name="name" type="text" placeholder="Name" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="password">Password</label>
<div class="col-md-4">
<input rv-value="password" id="password" rv-on-input="update" name="password" type="text" placeholder="Password" class="form-control input-md">
</div>
</div>
<!-- Password input-->
<div class="form-group">
<label class="col-md-4 control-label" for="password-validate">Password Validate</label>
<div class="col-md-4">
<input rv-value="password-validate" rv-on-input="update" id="password-validate" name="password-validate" type="password" placeholder="Password" class="form-control input-md">
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="save">Save</label>
<div class="col-md-4">
<button type="button" rv-on-click="submit" id="save" name="save" class="btn btn-primary">Save</button>
</div>
</div>
</fieldset>
</form>
and the server side
multipart = require('connect-multiparty');
multipartMiddleware = multipart();
app.post '/addUser', multipartMiddleware, (req, resp) ->
console.log(req.body, req.files)
You need to set your form to allow file upload using the enctype attribute.
<form enctype="multipart/form-data">
You can try to bind an onchange event to the file input:
<input type="file" rv-on-change="update" rv-value="product.image">
and create an update method in your controller that update the product.image value with the value of form.
this.update = function(){
model[this.id] = this.value
}
I have a dozen fully functional scripts that use heredoc statements to display HTML including e.g. $errors[field_name] yet this nearly identical script results in POST errors like
"Notice: Undefined index: user_password in register.php on line 162"
When the user enters a password with 5 characters when 8+ characters are required, a validation function populates $errors['password'] and the form is supposed to re-display along with validation errors.
Can't see what I'm missing in this Bootstrap style form. The $errors array is global and I can force the display of errors, so I know errors are initialized but I keep getting
"Notice: Undefined index"
$fields = array( 'user_name', 'user_email', 'user_password', 'user_password2' );
function display_form($string = '')
{
global $error_token, $cfg, $fields, $form, $errors, $s, $token, $validation_status;
$error_message = '';
switch($_SERVER['REQUEST_METHOD'])
{
Case 'POST':
// validation failed, redisplay the form
$autofocus = '';
foreach($fields as $field){
$$field = htmlentities(get_cgi_var($field), ENT_QUOTES, 'UTF-8');
// wrap errors in Bootstrap alert markup
$errors[$field] = !empty($errors[$field]) ? '<div class="alert alert-danger">'.htmlentities($errors[$field], ENT_QUOTES, 'UTF-8').'</div>' : '';
// debug, force the premature display of errors.
// echo !empty($errors[$field]) ? '<div class="alert alert-danger">'.htmlentities($errors[$field], ENT_QUOTES, 'UTF-8').'</div>' : '<p>empty</p>';
}
break;
Case 'GET':
default:
$autofocus = 'autofocus';
foreach($fields as $field){
$$field = '';
$errors[$field] = '';
}
$error_token = '';
break;
};
foreach($fields as $field){
$validation_status[$field] = empty($errors[$field]) ? ' has-success' : ' has-error';
}
$self = SELF;
print<<<_HTML_
<div class="col-lg-6">
<div class="panel panel-primary">
<div class="panel-heading">Registration</div>
<div class="panel-body">
$string
$error_message
<form name="form1" id="form1" action="$self" class="form-horizontal" role="form" method="POST">
<fieldset>
$error_token
$errors[user_name]
<div class="row form-group$validation_status[user_name]">
<label for="user_name" class="col-lg-3 control-label">Name</label>
<div class="col-lg-9">
<input type="text" name="user_name" id="user_name" value="$user_name" maxlength="255" $autofocus required placeholder="Your First & Last Name" title="Your First & Last Name" autocomplete="on" class="form-control">
</div>
</div>
$errors[user_email]
<div class="row form-group$validation_status[user_email]">
<label for="user_email" class="col-lg-3 control-label">Email</label>
<div class="col-lg-9">
<input type="email" name="user_email" id="user_email" value="$user_email" maxlength="255" required placeholder="Your Email Address" autocomplete="on" class="form-control">
</div>
</div>
$errors[user_password]
<div class="row form-group$validation_status[user_password]">
<label for="user_password" class="col-lg-3 control-label">Password</label>
<div class="col-lg-9">
<input type="text" name="user_password" id="user_password" value="$user_password" maxlength="255" required placeholder="Password or Passphrase" autocomplete="on" class="form-control">
<p class="help-block">Case sensitive password containing 8+ characters or a phrase containing 3-5 words</p>
</div>
</div>
$errors[user_password2]
<div class="row form-group$validation_status[user_password2]">
<label for="user_password2" class="col-lg-3 control-label">Password</label>
<div class="col-lg-9">
<input type="text" name="user_password2" id="user_password2" value="$user_password2" maxlength="255" required placeholder="Re-enter Password or Passphrase" autocomplete="on" class="form-control">
</div>
</div>
<div class="row form-group">
<label for="submit_button" class="col-lg-3 control-label"> </label>
<div class="col-lg-9 text-center">
<input type="hidden" name="token" value="$token">
<input type="submit" name="submit_button" id="submit_button" value="Submit" onClick="return captcha_validation(this.form);" class="btn btn-primary">
</div>
</div>
</fieldset>
</form>
</div><!-- /panel-body -->
<div class="panel-footer text-center"> </div>
</div><!-- /panel -->
</div><!-- /col -->
<div class="col-lg-6">
<div class="well">unused column</div>
</div><!-- /col -->
_HTML_;
};
Here's your problem:
default:
$autofocus = 'autofocus';
foreach($fields as $field){
$$field = ''; // <------------------
$errors[$field] = '';
}
$error_token = '';
break;
replace $$field with $field or remove it altogether - it's not needed here.