ajax removing everything after space - javascript

In my form select field I use ajax to list my options, but when submitting to the controller everything after space will be removed.
<div class="col-md-9">
<form class="" action="<?php echo base_url(); ?>Sms/add" method="post">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Compose New Message</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="form-group">
<input class="form-control" value="<?php echo set_value('title'); ?>" name="title" placeholder="Subject: 20 characters" maxlength="20">
</div>
<div class="form-group">
<textarea id="compose-textarea" name="message" class="form-control" style="height: 150px" placeholder=" Enter your message here: 150 characters" maxlength="150"><?php echo set_value('message'); ?></textarea>
</div>
<div class="form-group">
<label><input type="radio" class="flat-red" onclick="javascript:yesnoCheck();" name="yesno" id="yesCheck" value="company"> Send To Company's Database</label>
</div>
<div class="form-group">
<label><input type="radio" class="flat-red" onclick="javascript:yesnoCheck();" name="yesno" id="noCheck" value="ecofarmer"> Send To Ecofarmer Database</label>
</div>
<div id="ifYes" style="display:none" class="form-group">
<select class="form-control" name="database_name">
<option value="">Choose target</option>
<?php foreach ($databases as $item): ?>
<option value="<?php echo $item->db_id; ?>"><?php echo $item->db_name; ?></option>
<?php endforeach; ?>
</select>
</div>
<div id="ifNo" style="display:none">
<div class="form-group">
<select class="form-control" name="province" id="province">
<option value="">Choose Province</option>
<?php foreach ($provinces as $item): ?>
<option value="<?php echo $item->province_id; ?>"><?php echo $item->province_name; ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<select class="form-control" name="district" id="district" disabled="disabled">
<option value="">Choose District</option>
</select>
</div>
<div class="form-group">
<select class="form-control" name="ward" id="ward" disabled="disabled">
<option value="">Choose Ward</option>
</select>
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<div class="pull-right">
<button type="submit" name="draft" class="btn btn-default" value="true"><i class="fa fa-pencil"></i> Draft</button>
<button type="submit" name="submit" class="btn btn-primary" value="true"><i class="fa fa-envelope-o"></i> Send</button>
</div>
<button type="reset" class="btn btn-default"><i class="fa fa-times"></i> Discard</button>
</div>
<!-- /.box-footer -->
</div>
<!-- /. box -->
</form>
Below is my JavaScript that I use for radio input and select options
<script type="text/javascript">
function yesnoCheck() {
if (document.getElementById('yesCheck').checked) {
document.getElementById('ifYes').style.display = 'inline';
}
else document.getElementById('ifYes').style.display = 'none';
if (document.getElementById('noCheck').checked) {
document.getElementById('ifNo').style.display = 'inline';
}
else document.getElementById('ifNo').style.display = 'none';
}
$('#province').change(function() {
var province = this.value;
$.ajax({
url: "<?php echo base_url('Sms/get_district'); ?>",
data:{pID:province},
type: 'post',
success: function(data){
var arr = JSON.parse(data);
document.getElementById("district").disabled = false;
var $el = $("#district");
$el.empty();
$el.append($("<option>Choose District</option>"));
$.each($(arr),function(key,value){
var div_data="<option value="+value.district_id+">"+value.district_name+"</option>";
$(div_data).appendTo('#district');
console.log(value.district_name);
});
}
});
});
$('#district').change(function() {
var district = this.value;
$.ajax({
url: "<?php echo base_url('Sms/get_ward'); ?>",
data:{dID:district},
type: 'post',
success: function(data){
var arr = JSON.parse(data);
document.getElementById("ward").disabled = false;
var $il = $("#ward");
$il.empty();
$il.append($("<option>Choose A Ward</option>"));
$.each($(arr),function(key,value){
var div_data="<option value="+value.ward_number+">"+value.ward_number+"</option>";
$(div_data).appendTo('#ward');
console.log(value.ward_number);
});
}
});
});
Now when I'm submitting the value of the selection ward is being removed of everything after the space. How can I prevent that from happening?

The problem was on quotes
I changed the code below
var div_data="<option value="+value.ward_number+">"+value.ward_number+"</option>";
To this
var div_data = '<option value="' + value.ward_number + '">' + value.ward_number + '</option>';

Related

Stepformwizard is not getting hidden. Overflowing on right of the screen

Am not very expert in jquery and stepformwizard. Am working on code written by someone else. The issue is the multistepformwizard fieldset is used and the next step should be loaded only when Next button is clicked. But currently both of the steps are visible on the screen with extra horizontal scrollbar. I dont want the step 2 form to be visible. Here is the html and jquery code.
<div class="ztab-sec ztab-desbrd bksrvsec bksecrv2">
<div class="row">
<div class="col-md-12">
<form action="<?php echo base_url()?>service/service_request" method="POST" id="wizard_example_6" autocomplete="off">
<input type="hidden" value="<?php echo $ownerArr[0]['email_id']; ?>" name="email_id">
<input type="hidden" value="<?php echo $ownerArr[0]['phone']; ?>" name="mobile">
<fieldset>
<legend>Basic information about your car</legend>
<div class="row bkmargin">
<div class="col-lg-4 col-sm-4">
<div class="form-group">
<label>Vehicle Brand</label>
<select id="u_car_id" class="form-control" name="car_id" required>
<option selected disabled value="">Select a Car</option>
<?php foreach ($cars as $car_details) : ?>
<option value="<?php echo $car_details['user_car_id']; ?>"><?php echo $car_details['makesTitle']; ?> (<?php echo $car_details['modelsTitle']; ?>) <?php echo $car_details['car_reg_no']; ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="col-lg-4 col-sm-4">
<div class="form-group">
<label>Variants</label>
<input type="text" class="form-control" name="variant" placeholder="Variants" required data-parsley-group="block0" id="variant" readonly pattern="^[a-zA-Z\s]*$">
</div>
</div>
<div class="col-lg-4 col-sm-4">
<div class="form-group">
<label>Transmission</label>
<input type="text" class="form-control" placeholder="Transmission" name="transmission" readonly required data-parsley-group="block0" id="transmission" pattern="^[a-zA-Z\s]*$">
</div>
</div>
</div>
<legend class="clearfix">Select service for your car? <a href="#" class="car-link pull-right" data-toggle="modal" data-target="#myModal3" >Add New Car</a></legend>
<div class="row bkmargin">
<div class="col-md-4 col-sm-4">
<div class="form-group besrvx">
<input id="option-one" name="service_type" value="1" class="styled-radio " type="radio" data-parsley-group="block0" required data-required-message="Please check one service">
<label class="srvlabel" id="1" for="option-one"><strong>Basic Service: </strong>
<span class="srvspa">3 months or 5000 kms (whichever is earlier)</span>
</label>
</div>
</div>
</fieldset>
<fieldset>
<legend>Vehicle picked up address </legend>
<div class="row bkmargin">
<div class="col-lg-4 col-sm-4">
<div class="form-group">
<label>Select Address</label>
<select class="form-control" id="user_add_id" name="pick_id">
<option selected disabled>Select Address</option>
<?php $i=1; foreach ($address as $user_details) : ?>
<option value="<?php echo $user_details['add_id'] ?>"> Address <?php echo $i; ?></option>
<?php $i++; endforeach; ?>
<option id="neww" class="neww" value="neww">Select new Address</option>
</select>
</div>
</div>
<div class="col-lg-4 col-sm-4">
<div class="form-group">
<label>Address Type</label>
<select class="form-control" id="add_type" name="add_type" disabled>
<option value="" selected disabled>Select Address Type</option>
<option value="Home">Home Address</option>
<option value="Office">Office Address</option>
<option value="Other">Other Address</option>
</select>
</div>
<div class="row bkmargin">
<noscript>
<input class="nocsript-finish-btn sf-right nocsript-sf-btn" type="submit" value="submit"/>
</noscript>
</div>
</fieldset>
</form>
I have skipped some part as its a long form. I want the second fieldset should only be visible when user clicks on next button
here is the jquery
w6 = $("#wizard_example_6").stepFormWizard({
onNext: function(b, a) {
return $("#wizard_example_6").parsley().validate("block" + b)
},
onFinish: function(b) {
return $("#wizard_example_6").parsley().validate()
}
});
var d = window.location.hash.match(/^#step-(\d+)/),
c = 0;
null !== d && (c = d[1] - 1);
w7 = $("#wizard_example_7").stepFormWizard({
startStep: c,
onNext: function(b, a) {
window.location.hash = "#step-" + (b + 2)
},
onPrev: function(b, a) {
window.location.hash = "#step-" + b
},
onFinish: function(b) {
window.location.hash = "#form-sended"
}
})
};
$(document).ready(function() {
prepare_example();
$("pre code").each(function(c, b) {
hljs.highlightBlock(b)
});
var d = $(location).attr("search").match(/t=([a-z]+)/);
"undefined" != typeof d && null != d ? ($(".sf-wizard").parent().removeClass("sf-sea").addClass("sf-" + d[1]), $(".bt-" + d[1]).removeClass("btn-default").addClass("btn-info")) : $(".bt-sea").removeClass("btn-default").addClass("btn-info")
});
Please help me with this. I have tried using but no luck also changed css display:none inplace of block but couldnt resolve the issue.

Jquery on click can't show the data from database

Please help, I have trouble in this Jquery onclick at my form, Why my data from database can't show ? example, I choose a category "jantung", that should be show data dokter where category is jantung, but if I use onchange at the form it's work.
This is a html where I click the category (if click this category will show the modal)
<?php foreach ($poli as $row): ?>
<div class="col-sm-4 col-6 poliklinik-item">
<a class="poliklinik-link" data-toggle="modal" href="#poliklinikModal1" onclick="hmm('<?=$row->id_poli?>')">
<img class="img-fluid" src="<?php echo base_url();?>assets/upload/<?php echo $row->gambar?>" width="200" height="200">
</a>
<div class="poliklinik-caption text-center">
<h4><?php echo $row->nama_poli; ?></h4>
</div>
<br>
<br>
</div>
<?php endforeach; ?>
And This
<script>
function hmm(idnya) {
$(document).ready(function(){
document.getElementById('poli').value=idnya;
var id_poli = idnya;
$('#dokter').prop('disabled',false);
$.ajax({
url: "http://localhost/coba/Test/get_autofill",
type: "POST",
data: {'id_poli' : id_poli},
dataType: 'json',
success: function(data){
$('#dokter').html(data);
},
error: function(){
alert('Masih error');
}
});
});
}
</script>
The Modal
<?php echo form_open('hal_user/add/')?>
<div class="form-group">
<label>Nama</label>
<input type="hidden" name="id_pasien" class="form-control" readonly="" value="<?=$this->session->userdata('id_pasien') ;?>">
<input type="text" name="nama_pasien" class="form-control" readonly="" value="<?php echo $this->session->userdata('nama_pasien') ; ?>">
</div>
<div class="form-group">
<label>Poli</label>
<select name="id_poli" id="poli" class="form-control">
<option value="">Select Poli</option>
<?php foreach ($poli as $p): ?>
<option value="<?php echo $p->id_poli;?>"><?php echo $p->nama_poli;?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label>Dokter</label>
<select name="id_dokter" id="dokter" class="form-control" disabled="">
<option value="">Select Dokter</option>
</select>
</div>
<div class="form-group">
<label>Tanggal</label>
<input type="date" class="form-control" name="tanggal" placeholder="Pilih Tanggal">
</div>
<div class="form-group">
<label>Waktu</label>
<a class="btn btn-primary form-control" data-toggle="collapse" href="#waktuanak" role="button" aria-expanded="false" aria-controls="collapseExample">
Pilih Waktu
</a>
<div class="collapse" id="waktuanak">
<div class="card card-body">
<div class="btn-group-toggle" data-toggle="buttons">
<?php foreach ($waktu as $row) :?>
<label class="btn btn-outline-primary">
<input type="radio" name="id_waktu" autocomplete="off" value="<?php echo $row->id_waktu; ?>"><?php echo $row->waktu;?>
</label>
<?php endforeach;?>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success btn-wd">Simpan</button>
Batal
</div>
<?php echo form_close(); ?>
Try this
On your view file no need to call function and try to use data-attr and add a class hmm on
<?php foreach ($poli as $row): ?>
<div class="col-sm-4 col-6 poliklinik-item">
<a class="poliklinik-link hmm" data-toggle="modal" href="#poliklinikModal1" data-attr="<?=$row->id_poli?>">
<img class="img-fluid" src="<?php echo base_url();?>assets/upload/<?php echo $row->gambar?>" width="200" height="200">
</a>
<div class="poliklinik-caption text-center">
<h4><?php echo $row->nama_poli; ?></h4>
</div>
</div>
<?php endforeach; ?>
On your jquery try this
<script>
$(document).ready(function(){
$('.hmm').on('click',function(){
var idnya = $(this).attr('data-attr');
$('#poli').val(idnya );
var id_poli = idnya;
$('#dokter').prop('disabled',false);
$.ajax({
url: "http://localhost/coba/Test/get_autofill",
type: "POST",
data: {'id_poli' : id_poli},
dataType: 'json',
success: function(data){
$('#dokter').html(data);
},
error: function(){
alert('Masih error');
}
});
});
}
Updated
$("#poli option[value='" + idnya+ "']").prop("selected", true);

Not able to fetch value for Update Data from database using jQuery Ajax Bootstrap Model - json data

My main problem is that my modal is showing but alert is showing [object Object]. I have four tables like stud,country_master_academic, master_city and master_state.When i click on edit, modal appears but data fetched from database is not showing in it.
jQuery in home.php page
$(document).ready(function(){
$(document).on('click', '.edit_data', function(event){
var stud_no = $(this).attr("id");
$.ajax({
url:"update.php",
method:"POST",
data:{stud_no:stud_no},
dataType:"json",
success:function(data){
console.log(data);
$('#name').val(data.name);
$('#mob_no').val(data.mob_no);
$('#dob').val(data.dob);
$('#add').val(data.add);
$('#photo').val(data.photo);
$('#gender').val(data.gender);
$('#country').val(data.country);
$('#state').val(data.state);
$('#city').val(data.city);
$('#stud_no').val(data.stud_no);
$('#update_data_modal').modal('show');
},
});
});
});
Modal for update in home.php page
<div class="container">
<div class="modal fade" id="update_data_modal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-heading" style="margin-top:30px;text-align:center">
<button class="close" data-dismiss="modal" style="margin-right:20px;font-weight:bold;">x</button>
<h4 class="modal-title"><span class="glyphicon glyphicon-edit"></span>Update Student</h4>
</div>
<div class="modal-body">
<?php
$img = "images/".trim($vrow["photo"]);
echo '<img src='.$img.' class="image" style="margin-left:75%;margin-top:5%;width:120px;height:120px;border:2px solid #bbbbbb;border-radius:10px;">';
?>
<br/>
<input type="file" name="photo" style="margin-left:70%;">
<div class="form-group">
<form class="form-horizontal" name="form" id="form" method="post" action="<?php $_PHP_SELF?>" enctype="multipart/form-data">
<label for="name" id="name"><span class="glyphicon glyphicon-user"></span><b> Student Name: </b></label>
<input type="text" class="form-control" name="name" id="name" pattern="[a-zA-Z]{3,}" title="Name should only contain letters and atleast 3 letters" required />
</div>
<div class="form-group">
<label for="no"><span class="glyphicon glyphicon-phone"></span><b> Mobile No: </b></label>
<input type="text" class="form-control" name="mob_no" id="mob_no" pattern="[0-9]{10}" title="Mobile number should be of 10 digits" required />
</div>
<div class="form-group">
<label for="dob"><span class="glyphicon glyphicon-calendar"></span><b> Birth Date: </b></label>
<input type="date" class="form-control" name="dob" id="dob" required />
</div>
<div class="form-group">
<label for="add"><span class="glyphicon glyphicon-map-marker"></span><b> Address: </b></label>
<textarea rows="4" cols="33" class="form-control" name="add" id="add" required></textarea>
</div>
<div class="form-group">
<label for="photo"><span class="glyphicon glyphicon-camera"></span><b> Photo: </b></label>
<input type="file" name="photo" id="photo" required />
</div>
<div class="form-group">
<label for="gen"><b> Gender: </b></label>
<input type="radio" name="gender" id="gender" value="M" required="required">Male
<input type="radio" name="gender" id="gender" value="F" required="required">Female
</div>
<div class="form-group">
<label for="cntry"><span class="glyphicon glyphicon-map-marker"></span><b> Country: </b></label>
<select name="country" id="country" class="form-control">
<option value="0">Select</option>
<?php
$country="SELECT * from country_master_academic";
$res= $conn->query($country);
if($res->num_rows>0){
while($row=$res->fetch_assoc()){
if($row["country_name"]==$vcountry or $vrow['country'] == $row["country_code"] )
{
echo '<option value='.$row["country_code"].' selected>'.$row["country_name"].'</option>';
}
else
{
echo '<option value='.$row["country_code"].'>'.$row["country_name"].'</option>';
}
}
}
?>
</select>
</div>
<div class="form-group">
<label for="state"><span class="glyphicon glyphicon-map-marker"></span><b> State: </b></label>
<select name="state" id="state" class="form-control">
<option value="0">Select</option>
<?php
$state="SELECT * from master_state";
$res= $conn->query($state);
if($res->num_rows>0){
while($row=$res->fetch_assoc()){
if($row["state_name"]==$vstate or $vrow['state'] == $row["state_code"] )
{
echo '<option value='.$row["state_code"].' selected>'.$row["state_name"].'</option>';
}
else
{
echo '<option value='.$row["state_code"].'>'.$row["state_name"].'</option>';
}
}
}
?>
</select>
</div>
<div class="form-group">
<label for="city"><span class="glyphicon glyphicon-map-marker"></span><b> City: </b></label>
<select name="city" id="city" class="form-control">
<option value="0">Select</option>
<?php
$city="SELECT * from master_city";
$res= $conn->query($city);
if($res->num_rows>0){
while($row=$res->fetch_assoc()){
if($row["city_name"]==$vcity or $vrow['city'] == $row["city_code"] )
{
echo '<option value='.$row["city_code"].' selected>'.$row["city_name"].'</option>';
}
else
{
echo '<option value='.$row["city_code"].'>'.$row["city_name"].'</option>';
}
}
}
?>
</select>
</div>
<div class="form-group">
<input type="hidden" name="stud_no" id="stud_no" />
<button type="submit" name="update" id="update" class="btn btn-info">Update</button>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-danger" type="button" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
update.php page but still i am trying to fetch data, so only wrote code for selecting records from database.
My edit button which is kept in a loop
echo '<td><button name="edit" style="font-weight:bold;" type="submit" id='.$row["stud_no"].' class="btn btn-warning edit_data" data-target="#update_data_modal" data-toggle="modal"><span class="glyphicon glyphicon-edit"></span> Edit</button></td>';
Change in your html as below.
<div class="form-group">
<label for="gen"><b> Gender: </b></label>
<input type="radio" name="gender" id="genderMale" value="M" required="required">Male
<input type="radio" name="gender" id="genderFemale" value="F" required="required">Female
</div>
Add this code in your ajax success.
if(data[6] == 'M')
{
$("#genderMale").prop("checked", true);
} else if(data[6] == 'F') {
$("#genderFemale").prop("checked", true);
}
For image file you can use as below in your html
<div class="form-group">
<img id="resultedPhoto">
<label for="photo"><span class="glyphicon glyphicon-camera"></span><b> Photo: </b></label>
<input type="file" name="photo" id="photo" required />
</div>
Add below code in ajax success
$("#resultedPhoto").attr("src","/path-to-your-folder/" + data[5]);
As shown in the snapshot, your object has numeric indexes hence data.photo will not return anything as there is no index photo in your object.
You can access image name by using data[5].
Similarly you can get any index value.
Like for name instead of using data.name you need to use data[1]
So your code would be something like this:
$('#name').val(data[1]);
$('#mob_no').val(data[2]);
$('#dob').val(data[3]);
$('#add').val(data[4]);
$('#photo').val(data[5]);
Also you have given same ids for labels and inputs:
<label for="name" id="name">
You need to remove id from all labels:
<label for="name">
Now when i click on edit Modal is not opening and database value is getting empty
another jquery
$(document).ready(function(){
$("#form1").submit(function(event){
event.preventDefault();
var formData = new FormData(this);
$.ajax({
url:"upresult.php",
type:"POST",
data:{formData:formData},
async:false,
success:function(data) {
alert(data);
location.reload();
},
cache:false,
contentType:false,
processData:false
});
});
});
upresult.php
<?php
include("connection.php");
if(!empty($_POST)){
$no=$_POST['stud_no'];
$name=trim($_POST['name']);
$mob=trim($_POST['mob_no']);
$dob=trim($_POST['dob']);
$add=trim($_POST['add']);
$photo=trim($_FILES['photo']['name']);
$gen=trim($_POST['gender']);
$cn=trim($_POST['country']);
$st=trim($_POST['state']);
$ct=trim($_POST['city']);
$qry="update stud set stud_name='$name',mobile='$mob',dob='$dob',address='$add',gender='$gen',country='$cn',state='$st',city='$ct' where stud_no='$no'";
$data=mysqli_query($conn,$qry);
if($data)
{
echo '<script language="javascript">';
echo 'alert("Updated Successfully")';
echo '</script>';
}
else {
echo '<script language="javascript">';
echo 'alert("Cannot update record")';
echo '</script>';
}
if(!empty($_FILES['photo']['name'])){
$qry1= "update stud set photo='$photo' where stud_no='$no'";
$data1=mysqli_query($conn,$qry1);
if($data1){
$target_dir="images/";
$target_file=$target_dir.basename($_FILES["photo"]["name"]);
$imageFileType=pathinfo($target_file,PATHINFO_EXTENSION);
if(move_uploaded_file($_FILES["photo"]["tmp_name"],$target_file)){
echo '<script language="javascript">';
echo 'alert("Image upload successfully")';
echo '</script>';
} else {
echo '<script language="javascript">';
echo 'alert("Cannot Upload")';
echo '</script>';
}
}
}
}

clone existing div with Jquery

i have an issue. How can i clone an existing div with jquery?
[Image]1
<div class="modal-body">
<div class="row">
<div class="col-md-5 text-center">
<b>Número Factura</b>
<input type="number" class="form-control" id="numero"><br/>
</div>
<div class="col-md-2 text-center">
-o-
</div>
<div class="col-md-5 text-center">
<b>Número Remisión</b>
<input type="number" class="form-control" id="remision"><br/>
</div>
<div class="col-md-12">
<b>NIT:</b>
<?php $consulta = mysqli_query($conexion, "SELECT * FROM proveedores");
$resultado = mysqli_fetch_all($consulta, MYSQLI_ASSOC); ?>
<select class="form-control" id="proveedor">
<?php foreach($resultado as $r): ?>
<option value="<?php echo $r['nit']; ?>"><?php echo $r['nombre']; ?></option>
<?php endforeach; ?>
</select><br/>
</div>
<div class="col-md-2">
<input type="number" class="form-control" id="productos" value="1">
</div>
<div class="col-md-2">
<button type="button" class="btn btn-success agregar_producto" name="agregar_producto">
<i class="fas fa-user-plus" style="color: white"></i>
</button>
</div>
</div>
<br/>
<div id="contenido" class="row text-center">
<div class="col-md-4">
<b>Producto</b>
<?php $consulta = mysqli_query($conexion, "SELECT * FROM productos");
$resultado = mysqli_fetch_all($consulta, MYSQLI_ASSOC); ?>
<select class="form-control" id="producto">
<?php foreach($resultado as $r): ?>
<option value="<?php echo $r['id']; ?>"><?php echo $r['descripcion']; ?></option>
<?php endforeach; ?>
</select><br/>
</div>
<div class="col-md-4">
<b>Cantidad</b>
<input type="number" class="form-control" id="cantidad"><br/>
</div>
<div class="col-md-4">
<b>Precio</b>
<input type="number" class="form-control" id="precio"><br/>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success crear" name="crear">Agregar Factura</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Regresar</button>
</div>
I need to clone the div with id="contenido" when someone press the button with class="agregar_producto".
How can i solve it?
[Example]2
Is it possible? i need only an example to solve my problem.
Thx you! <3
EDIT: If a clone this inputs how can i change ids/class to this inputs?
Hi Please check below code:
<html>
<head>
<title>Sample HTML</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body bgcolor=white>
<div id="contenido" class="row text-center">
<div class="col-md-4">
<b>Producto</b>
<select class="form-control" id="producto">
<option value="product1">product1</option>
<option value="product2">product2</option>
<option value="product3">product3</option>
<option value="product4">product4</option>
<option value="product5">product5</option>
<option value="product6">product6</option>
</select><br/>
</div>
<div class="col-md-4">
<b>Cantidad</b>
<input type="number" class="form-control" id="cantidad"><br/>
</div>
<div class="col-md-4">
<b>Precio</b>
<input type="number" class="form-control" id="precio"><br/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn agregar_producto" name="crear">Agregar Producto</button>
</div>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$(".agregar_producto").on('click', function() {
var $contenido = $("#contenido:last");
var $clone = $contenido.clone();
$clone.find('input').val('');
$contenido.after($clone);
});
});
</script>
</body>
</html>
1.Id need to be unique per element so convert id="contenido" to class="contenido"
2.Use .clone()
$('.agregar_producto').on('click', function(){
var clone = $( ".contenido:first" ).clone();
$(clone).attr('id','changedId'); //change cloned element id attribute
$(clone).find('select').attr('id','changedId1'); //change cloned element children attribute also
$(clone).insertAfter( ".contenido:last" );
});
Note:- add selector(class or id) of the element after which you want to append the clone.
Reference:-
.insertAfter()
Working snippet:-
$('.agregar_producto').on('click', function(){
var clone = $( ".contenido:first" ).clone();
$(clone).attr('id','changedId'); //change cloned element id attribute
$(clone).find('select').attr('id','changedId1'); //change cloned element children attribute also
$(clone).insertAfter( ".contenido:last" );
});
#changedId{
background:yellow;
}
#changedId1{
font-size:20px;
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-body">
<div class="row">
<div class="col-md-5 text-center">
<b>Número Factura</b>
<input type="number" class="form-control" id="numero"><br/>
</div>
<div class="col-md-2 text-center">
-o-
</div>
<div class="col-md-5 text-center">
<b>Número Remisión</b>
<input type="number" class="form-control" id="remision"><br/>
</div>
<div class="col-md-12">
<b>NIT:</b>
<?php $consulta = mysqli_query($conexion, "SELECT * FROM proveedores");
$resultado = mysqli_fetch_all($consulta, MYSQLI_ASSOC); ?>
<select class="form-control" id="proveedor">
<?php foreach($resultado as $r): ?>
<option value="<?php echo $r['nit']; ?>"><?php echo $r['nombre']; ?></option>
<?php endforeach; ?>
</select><br/>
</div>
<div class="col-md-2">
<input type="number" class="form-control" id="productos" value="1">
</div>
<div class="col-md-2">
<button type="button" class="btn btn-success agregar_producto" name="agregar_producto">
<i class="fas fa-user-plus" style="color: black">Click me to append Clone</i>
</button>
</div>
</div>
<br/>
<div class="contenido" class="row text-center">
<div class="col-md-4">
<b>Producto</b>
<select class="form-control" id="producto">
<option value="1">1</option>
<option value="1">2</option>
<option value="1">3</option>
<option value="1">4</option>
<option value="1">5</option>
</select><br/>
</div>
<div class="col-md-4">
<b>Cantidad</b>
<input type="number" class="form-control" id="cantidad"><br/>
</div>
<div class="col-md-4">
<b>Precio</b>
<input type="number" class="form-control" id="precio"><br/>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success crear" name="crear">Agregar Factura</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Regresar</button>
</div>
.clone() method create a deep copy of the set of matched elements. And .appendTo( ) to append the cloned element.
$('.agregar_producto').on('click', function(){
$( "#contenido" ).clone().appendTo( "body" );
});
$('.agregar_producto').click(function(){
$( "#contenido" ).clone().appendTo( "body" );
});
you can change the above to append the clone under specific elements.
You could easily do the following.
<div id="div1">
<p>
Content in DIV1
</p>
</div>
<div id="tgt">
</div>
jQuery snippet would be as follows.
$(document).ready(function(){
var div1 = $("#div1").clone(); //Clone the element. Assigned to the JS variable div1
div1.attr("id", "div1clone"); //Modify the necessary properties using $(element).attr()
$("#tgt").append(div1); //Append the content to where ever desired
});
This is just a very rusty sample. Check this fiddle out to see this in action.

How to pass a variable from a page to other in php

I have a page *book_order*,which is used to add orders into a table *order_management*, where order_id is auto incremented in that table. once after submit this page i want the order_id to be passed to other page *book_order2* to add products under same order_id. For that i have created seperete *order_management2* table in which order_id is not auto-incremented.
My requirement is that i want to pass order_id from book_order page to book_order2 page and that variable is to be remembered till i do keep on adding....if i want to add new order, i will go to book_order page, else i will use book_order2 page.
book_order.php
<div class="grid_4">
<div class="da-panel">
<div class="da-panel-header">
<span class="da-panel-title">
<img src="images/icons/color/wand.png" alt="" />
<font face="Cambria" size="7" color="#009900"><b>Book Order</b></font>
</span>
</div>
<div class="da-panel-toolbar top">
<ul>
<li><div class="da-button blue large">View all Orders</div></li>
</ul>
</div>
<div class="da-panel-content">
<?php
if(isset($_POST['submit']))
{
extract($_POST);
$order_date=date("Y-m-d");
$sql=mysql_query("select sku,quantity_in_stock,sold_quantity,crdate from stock_info where product_name = '$prod'");
$array=mysql_fetch_array($sql);
$sku = $array[0];
$qis = $array[1];
$sold_quan = $array[2];
$crdate = $array[3];
$sql2=mysql_query("INSERT INTO order_management(order_date,brand,product,price,customer_name,phone_number,email,address,quantity,channel,courier,order_status,sku)
VALUES
('$order_date','$brand','$prod','$pri','$customername','$phonenumber', '$email','$address','$quantity','$channel','$courier','booked','$sku')");
if($sql2)
{
echo "<div class='da-message success'>Successfully Booked Your Order</div>";
?>
<script>
var r = confirm("want to add more products?");
if (r == true)
{
//x="You pressed OK!";
window.location = "main.php?page=book_order2";
}
else
{
//x="You pressed Cancel!";
window.location = "main.php";
}
</script>
<?php
}
else
{
die(mysql_error());
}
$quantity_left = $qis - $quantity;
$sold_quan = $sold_quan + $quantity;
$diff_in_days = (strtotime($order_date) - strtotime($crdate))/(60 * 60 * 24);
$expctd_stock=round((7*$quantity_left)/$diff_in_days);
//echo $expctd_stock;
$sql3 =mysql_query("UPDATE stock_info SET quantity_in_stock = '$quantity_left',last_sold_date='$order_date', sold_quantity='$sold_quan', expected_stock='$expctd_stock' WHERE sku='$sku'");
/*$sql3 = mysql_query("update order_management set sku='$sku' where order_date=''");*/
$sql4 =mysql_query("select order_id from order_management where sku='$sku'");
$idarray=mysql_fetch_array($sql4);
$id = $idarray[0];
//$_SESSION['id'] = $id;
}
?>
<form id="da-ex-validate1" class="da-form" method="post" action="">
<div class="da-form-row">
<label>Brand<span class="required">*</span></label>
<div class="da-form-item small">
<!--<input type="text" name="brand" id="brand" class="required" value=""/>-->
<select name="brand" id="brand" onChange="retrievedata(this.value)">
<option value="">--- select brand ---</option>
<?php
$ord=mysql_query("select * from brand_info");
while($ord1=mysql_fetch_array($ord))
{
?>
<option value="<?php echo $ord1['brand'];?>"><?php echo $ord1['brand'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="da-form-row">
<label>Product<span class="required">*</span></label>
<div class="da-form-item small">
<select name="prod" id="prod" onChange="retrievequantity(this.value)">
<option value="">--- select product ---</option>
</select>
</div>
</div>
<div class="da-form-row">
<label>Customer name<span class="required">*</span></label>
<div class="da-form-item small">
<input type="text" name="customername" id="customername" class="required char" value=""/>
</div>
</div>
<div class="da-form-row">
<label>Phone Number<span class="required">*</span></label>
<div class="da-form-item small">
<input type="text" name="phonenumber" id="phonenumber" class="required number" value=""/>
</div>
</div>
<div class="da-form-row">
<label>Email<span class="required">*</span></label>
<div class="da-form-item small">
<input type="text" name="email" id="email" class="required email" value=""/>
</div>
</div>
<div class="da-form-row">
<label>Address<span class="required">*</span></label>
<div class="da-form-item small">
<textarea name="address" id="address" class="required"></textarea>
</div>
</div>
<div class="da-form-row">
<label>Quantity<span class="required">*</span></label>
<div class="da-form-item small">
<select name="quantity" id="quantity">
<option value=""> --- select Quantity--- </option>
</select>
</div>
</div>
<div class="da-form-row">
<label>Total Price<span class="required">*</span></label>
<div class="da-form-item small">
<input type="text" name="pri" id="pri" class="required number" value=""/>
</div>
</div>
<div class="da-form-row">
<label>Courier<span class="required"></span></label>
<div class="da-form-item small">
<!--<input type="text" name="courier" id="courier" class="required" value=""/>-->
<select name="courier" id="courier">
<option value=""> ---select courier --- </option>
<?php
$ord=mysql_query("select courier_name from courier_info");
while($ord1=mysql_fetch_array($ord))
{
?>
<option value="<?php echo $ord1['courier_name'];?>"><?php echo $ord1['courier_name'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="da-form-row">
<label>Channel<span class="required"></span></label>
<div class="da-form-item small">
<!--<input type="text" name="channel" id="channel" class="required" value=""/>-->
<select name="channel" id="channel">
<option value=""> --- select channel ---</option>
<?php
$ord=mysql_query("select channel from channel_info");
while($ord1=mysql_fetch_array($ord))
{
?>
<option value="<?php echo $ord1['channel'];?>"><?php echo $ord1['channel'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="da-button-row">
<input type="submit" name="submit" value="submit" class="da-button grey" />
</div>
</fieldset>
</form>
</div>
<!-- End of .grid_4 --> </div>
</div>
<script>
function retrievedata(data)
{
var option_html = "";
<?php
$sql=mysql_query("SELECT distinct brand,product_name FROM stock_info");
while($ord1=mysql_fetch_array($sql))
{
?>
if(data == '<?php echo $ord1['brand']; ?>')
{
option_html += "<option><?php echo $ord1['product_name']; ?></option>";
/*alert(option_html);*/
}
<?php
}
?>
var par = document.getElementById("prod");
par.innerHTML = "<option>--- select product ---</option>"+option_html;
}
function retrievequantity(product)
{
var option_quantity_html = "";
<?php
$sql=mysql_query("SELECT product_name, quantity_in_stock FROM stock_info");
while($ord2=mysql_fetch_array($sql))
{
$i=1;
?>
if(product == '<?php echo $ord2['product_name']; ?>')
{
<?php
while($i<=intval($ord2['quantity_in_stock'])){?>
option_quantity_html += "<option><?php echo $i++; ?></option>";
<?php }?>
}
<?php
}
?>
var par = document.getElementById("quantity");
par.innerHTML = option_quantity_html;
}
</script>
book_order2.php
<?php /*?><?php
$id = $_SESSION['id'];
echo $id;
?><?php */?>
<?php
include("includes/db.php");
?>
<div class="grid_4">
<div class="da-panel">
<div class="da-panel-header">
<span class="da-panel-title">
<img src="images/icons/color/wand.png" alt="" />
<font face="Cambria" size="7" color="#009900"><b>Book Order</b></font>
</span>
</div>
<div class="da-panel-toolbar top">
<ul>
<li><div class="da-button blue large">View all Orders</div></li>
</ul>
</div>
<div class="da-panel-content">
<?php
if(isset($_POST['submit']))
{
extract($_POST);
$order_date=date("Y-m-d");
$sql=mysql_query("select sku,quantity_in_stock,sold_quantity,crdate from stock_info where product_name = '$prod'");
$array=mysql_fetch_array($sql);
$sku = $array[0];
$qis = $array[1];
$sold_quan = $array[2];
$crdate = $array[3];
$sql2=mysql_query("INSERT INTO order_management2(order_id,order_date,brand,product,price,customer_name,phone_number,email,address,quantity,channel,courier,order_status,sku)
VALUES
('$id','$order_date','$brand','$prod','$pri','$customername','$phonenumber', '$email','$address','$quantity','$channel','$courier','booked','$sku')");
if($sql2)
{
echo "<div class='da-message success'>Successfully Booked Your Order</div>";
?>
<script>
var r = confirm("want to add more products?");
if (r == true)
{
//x="You pressed OK!";
window.location = "main.php?page=book_order2";
}
else
{
//x="You pressed Cancel!";
window.location = "main.php";
}
</script>
<?php
}
else
{
die(mysql_error());
}
$quantity_left = $qis - $quantity;
$sold_quan = $sold_quan + $quantity;
$diff_in_days = (strtotime($order_date) - strtotime($crdate))/(60 * 60 * 24);
$expctd_stock=round((7*$quantity_left)/$diff_in_days);
//echo $expctd_stock;
$sql3 =mysql_query("UPDATE stock_info SET quantity_in_stock = '$quantity_left',last_sold_date='$order_date', sold_quantity='$sold_quan', expected_stock='$expctd_stock' WHERE sku='$sku'");
/*$sql3 = mysql_query("update order_management set sku='$sku' where order_date=''");*/
//$sql4 =mysql_query("select order_id from order_management where sku='$sku'");
//$idarray=mysql_fetch_array($sql4);
}
?>
<form id="da-ex-validate1" class="da-form" method="post" action="">
<div class="da-form-row">
<label>Brand<span class="required">*</span></label>
<div class="da-form-item small">
<!--<input type="text" name="brand" id="brand" class="required" value=""/>-->
<select name="brand" id="brand" onChange="retrievedata(this.value)">
<option value="">--- select brand ---</option>
<?php
$ord=mysql_query("select * from brand_info");
while($ord1=mysql_fetch_array($ord))
{
?>
<option value="<?php echo $ord1['brand'];?>"><?php echo $ord1['brand'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="da-form-row">
<label>Product<span class="required">*</span></label>
<div class="da-form-item small">
<select name="prod" id="prod" onChange="retrievequantity(this.value)">
<option value="">--- select product ---</option>
</select>
</div>
</div>
<div class="da-form-row">
<label>Customer name<span class="required">*</span></label>
<div class="da-form-item small">
<input type="text" name="customername" id="customername" class="required char" value=""/>
</div>
</div>
<div class="da-form-row">
<label>Phone Number<span class="required">*</span></label>
<div class="da-form-item small">
<input type="text" name="phonenumber" id="phonenumber" class="required number" value=""/>
</div>
</div>
<div class="da-form-row">
<label>Email<span class="required">*</span></label>
<div class="da-form-item small">
<input type="text" name="email" id="email" class="required email" value=""/>
</div>
</div>
<div class="da-form-row">
<label>Address<span class="required">*</span></label>
<div class="da-form-item small">
<textarea name="address" id="address" class="required"></textarea>
</div>
</div>
<div class="da-form-row">
<label>Quantity<span class="required">*</span></label>
<div class="da-form-item small">
<select name="quantity" id="quantity">
<option value=""> --- select Quantity--- </option>
</select>
</div>
</div>
<div class="da-form-row">
<label>Total Price<span class="required">*</span></label>
<div class="da-form-item small">
<input type="text" name="pri" id="pri" class="required number" value=""/>
</div>
</div>
<div class="da-form-row">
<label>Courier<span class="required"></span></label>
<div class="da-form-item small">
<!--<input type="text" name="courier" id="courier" class="required" value=""/>-->
<select name="courier" id="courier">
<option value=""> ---select courier --- </option>
<?php
$ord=mysql_query("select courier_name from courier_info");
while($ord1=mysql_fetch_array($ord))
{
?>
<option value="<?php echo $ord1['courier_name'];?>"><?php echo $ord1['courier_name'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="da-form-row">
<label>Channel<span class="required"></span></label>
<div class="da-form-item small">
<!--<input type="text" name="channel" id="channel" class="required" value=""/>-->
<select name="channel" id="channel">
<option value=""> --- select channel ---</option>
<?php
$ord=mysql_query("select channel from channel_info");
while($ord1=mysql_fetch_array($ord))
{
?>
<option value="<?php echo $ord1['channel'];?>"><?php echo $ord1['channel'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="da-button-row">
<input type="submit" name="submit" value="submit" class="da-button grey" />
<?php /*?><a href="book_order2.php?&id=<?php echo $id; ?>" name="submit" value="submit" class="da-button grey">Book Order</a<?php */?>
</div>
</fieldset>
</form>
</div>
<!-- End of .grid_4 --> </div>
</div>
<script>
function retrievedata(data)
{
var option_html = "";
<?php
$sql=mysql_query("SELECT distinct brand,product_name FROM stock_info");
while($ord1=mysql_fetch_array($sql))
{
?>
if(data == '<?php echo $ord1['brand']; ?>')
{
option_html += "<option><?php echo $ord1['product_name']; ?></option>";
/*alert(option_html);*/
}
<?php
}
?>
var par = document.getElementById("prod");
par.innerHTML = "<option>--- select product ---</option>"+option_html;
}
function retrievequantity(product)
{
var option_quantity_html = "";
<?php
$sql=mysql_query("SELECT product_name, quantity_in_stock FROM stock_info");
while($ord2=mysql_fetch_array($sql))
{
$i=1;
?>
if(product == '<?php echo $ord2['product_name']; ?>')
{
<?php
while($i<=intval($ord2['quantity_in_stock'])){?>
option_quantity_html += "<option><?php echo $i++; ?></option>";
<?php }?>
}
<?php
}
?>
var par = document.getElementById("quantity");
par.innerHTML = option_quantity_html;
}
</script>
You can store the order number in the session. This way, it will be protected and persisted across pages.
When you insert the order in book_order.php, store it in the session:
$sql2=mysql_query(....); // inserting
if($sql2){
$_SESSION['order_id'] = mysql_insert_id();
}
Now, in book_order2.php you can retrieve the order ID before you do the insert of the product:
$id = $_SESSION['order_id'];
// insert product with order_id = $id
In order to use PHP sessions, you must calll session_start() at the beginning of any script that makes use of the session. If you have a global/header include then you can do it there.
Side notes:
mysql_* is deprecated. Consider upgrading to PDO or MySQLi. This is a good PDO tutorial, especially if you're upgrading from mysql_*.
Use a Prepared Statement with bound parameters instead of concatenating variables into SQL.
I would use ajax. For example:
$(document).ready(function()
{
$("form").on('submit',function(event)
{
event.preventDefault();
data = "var=data";
$.ajax
({
type: "GET",
url: "parser.php",
data: data
}).done(function(msg)
{
alert(msg);
});
});
});
It will send GET into parser.php. And the data field would be data in $_GET['var']

Categories

Resources