2 forms with 1 single submit button - php

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.

Related

How can I add a query in Ajax code with the parameter data passed?

I am doing a project in laravel with a create form in ajax. I need to join two tables after the form is done, so in ajax code because I need to take some selection. Here there is the ajax code:
$.ajax({
data: $('#hourForm').serialize(),
url: "{{ route('others.store') }}",
type: "POST",
dataType: 'json',
success: function (data) {
var name = <?php DB::select('SELECT projects.nameP from projects, data where projects.id = data.project_id?>
var hour = '<tr id="hour_id_' + data.id + '"><td>' + data.day + '</td><td>'+ data.project_id+'</td><td>' + name + '</td><td>' + data.nHours + '</td><td>' + data.notesH + '</td>';
And here the form:
<form id="hourForm" name="hourForm" class="form-horizontal">
<input type="hidden" name="hour_id" id="hour_id">
<div class="form-group">
<label for="day" class="col-sm-2 control-label">DATA</label>
<div class="col-sm-12">
<input type="date" class="form-control" id="day" name="day" value="" required="">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Progetto</label>
<div class="col-sm-12">
<select name="project_id" id="project_id">
<option value="" selected disabled hidden><b>Scegli un'opzione</b></option>
#foreach($projects as $project)
<option value="{{$project->id}}">{{$project->nameP}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group">
<label for="nHours" class="col-sm-2 control-label">Ore</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="nHours" name="nHours" value="" required="">
</div>
</div>
<div class="form-group">
<label for="notesH" class="col-sm-2 control-label">Note</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="notesH" name="notesH" value="">
</div>
</div>
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary" id="btn-save" value="create">Aggiungi
</button>
</div>
</form>
I don't know how to replace data that is only the variable in ajax function. Can anyone help me?
You won't be able to perform such a query inside your javascript.
Why don't you perform the query within the route('others.store')? I believe that its calling a controller's function so: just run that join back there and bring the name along with the rest of the data.

Dynamically save data php

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.

Angular 5 - Populate form with mysql data

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();
});

getting total value after entering the values in the form and inserting into database using codeigniter

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>

chained select with php mysql jQuery

I have a problem with chained selected script in my mvc structure
I have the form view and it contain this:
<div class="col-md-6 col-md-offset-3">
<form action="" method="post" role="form">
<div class="form-group">
<label>Nom de l'annonce:</label>
<input class="form-control input-lg" type="text" name="reg_name">
</div>
<div class="form-group">
<label>Choisi une catégorie:</label>
<select id="first_drop" class="form-control input-lg" name="categories">
<option disabled="disabled" selected="selected">choisi une categorie</option>
<?php
for ($i = 0; $i < count($dispalyCat); $i++) {
echo'<option value="' . $dispalyCat[$i]['id'] . '">' . $dispalyCat[$i]['categorieName'] . '</option>';
}
?>
</select>
</div>
<span id="loading" style="display: none;">
<img alt="Loading..." src="resources/images/loader.gif"/>
</span>
<div class="form-group" id="result" style="display: none">
<label>Choisi une sou-catégorie:</label>
<select id="second_drop" class="form-control input-lg" name="subCategories">
<?php
for ($i = 0; $i < count($dispalySubCat); $i++) {
echo'<option>' . $dispalySubCat[$i]['subCategorieName'] . '</option>';
}
?>
</select>
</div>
<div class="form-group">
<label>Prix:</label>
<input class="form-control input-lg" name="reg_pass2" type="text"/>
</div>
<div class="form-group">
<label>Surface:</label>
<input class="form-control input-lg" name="reg_pass2" type="text"/>
</div>
<div class="form-group">
<label>Description:</label>
<textarea class="form-control input-lg"></textarea>
</div>
<div class="form-group">
<label>Images:</label>
<input type="file" value="Ajouter l'annonce" class="form-control input-lg" multiple="" />
</div>
<div class="form-group">
<input type="submit" value="Ajouter l'annonce" class="btn btn-danger btn-lg" />
</div>
<input type="hidden" name="do" value="register"/>
</form>
</div>
and then the information was manipulated in the controller and this is the code:
<?php
$display = new Display('categories');
$dispalyCat = $display->getAllData();
$func = $_POST['func'];
$drop_val = $_POST['drop_val'];
if (isset($_POST['drop_val'])) {
$display2 = new Display('subcategories');
$dispalySubCat = $display2->getAllDataFromParentId($drop_val, 'categorieId');
}
include 'views/ajouterAnnonce.php';
?>
and the jquery script is:
$(document).ready(function () {
"use strict";
$('#loading').hide();
$('#first_drop').change(function () {
$('#loading').show();
$('#result').hide();
$.post('addAds.php', {
drop_val: $('select[name=categories]').val()
}, function (response) {
$('#result').fadeOut();
setTimeout("finishAjax('result', '" + escape(response) + "')", 400);
});
return false;
});
});
function finishAjax(id, response) {
"use strict";
$('#loading').hide();
$('#' + id).html(unescape(response));
$('#' + id).fadeIn();
}
when I tested this codes and I choose an option from the first select but I had an error message that the class Display not found in line 3 (in 2nd code) although it work in the first select and show me all the categories in the database
where is the problem ?
Divide the problem in 2 parts:
1.- Server side:
//In your file php
<?php
// get values from url, because for a query from a select, is not necessary use request POST
// then
echo $.GET['value'];
// Here you use queries or you do procedures for obtain data related with $.GET['value']
// Last you return data on format Json
?>
// This file php, has a url, for example: get_data_select.php
// Then whitout jquery or javascript, you should test the url, on the browser.
// http://somedomain/get_data_select.php?value=12
// If it return data with header json. server side works good.
2.- Client side: you change selected
$('#idselect').on("change", function(){
var values = '?value=' + $('#idselect').val();
$.get('http://somedomain/get_data_select.php' + values, function(res){
console.log("response", res);
callFunctionRender(res);
});
});
function callFunctionRender(data) {
// here You have data from server
// then you should rendered
};

Categories