How ajax work in dynamically generated div - javascript

I am doing sales of product in which I use AJAX to capture data based on a selection from a dropdown to another one. When I dynamically create a field it works only once i want it to work N number of time.
Here is my HTML & PHP Code:
<div class="row col-md-12 mrg-top-20">
<h4 class="card-title" style="color:#ff0033">Sales Details</h4><br>
<div class="col-md-12"></div>
<div class="row col-md-12" data-duplicate="add">
<div class="col-md-4">
<label>Select <strong>Installation Date</strong></label>
<div class="form-group">
<div class="timepicker-input input-icon form-group">
<i class="ti-time"></i>
<input type="text" name="ins_date" class="form-control datepicker-1" placeholder="Datepicker" data-provide="datepicker">
</div>
</div>
</div>
<div class="col-md-4" id="sel_dynamic">
<div class="form-group">
<label>Select <strong>Manufacturer</strong></label>
<select name="manu" id="manu" class="form-control" style="width:100%">
<option disabled="disabled" selected="selected">Select Manufacturer</option>
<?php
$data = mysqli_query($conn,"SELECT * FROM manufacturer_details");
while($itemcat = mysqli_fetch_array($data))
{
?>
<option value="<?php echo $itemcat['MANUFACTURER_ID']; ?>"><?php echo $itemcat['MANUFACTURER_NAME'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Select <strong>Modal</strong></label>
<select name="modal" id="modal" class="form-control" style="width:100%">
<option value="" selected disabled="disabled">Select Modal...</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Ser<strong>ial</strong></label>
<input type="text" name="serial" placeholder="Enter Serial No" class="form-control">
</div>
</div>
<div class="col-md-4">
<label>Select <strong>AMC Start Date</strong></label>
<div class="form-group">
<div class="timepicker-input input-icon form-group">
<i class="ti-time"></i>
<input type="text" name="amc_date" class="form-control datepicker-1" placeholder="Datepicker" data-provide="datepicker" data-date-format="mm/dd/yyyy">
</div>
</div>
</div>
<div class="col-md-4">
<label>Select <strong>AMC End Date</strong></label>
<div class="form-group">
<div class="timepicker-input input-icon form-group">
<i class="ti-time"></i>
<input type="text" name="amc_edate" class="form-control datepicker-1" placeholder="Datepicker" data-provide="datepicker" data-date-format="mm/dd/yyyy">
</div>
</div>
</div>
</div>
<div>
<input type="button" id="add" data-duplicate-add="add" class="btn btn-info" value="+"/>
</div>
<div >
<input type="button" data-duplicate-remove="add" class="btn btn-info" value="-"/>
</div>
</div>
Here is My Js Script to Call Ajax Each Time
<script type="text/javascript">
$(document).ready(function()
{
$("#sel_dynamic").on("change","#manu",(function() //just try to use on change
{
var id = $("#manu").val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax_modal.php",
data: dataString,
cache: false,
success: function(html)
{
$("#modal").html(html);
}
});
});
});
</script>
Here is my Ajax File
<?php
include('script/db.php');
if($_POST['id'])
{
$id=$_POST['id'];
$sql=mysqli_query($conn,"select * from modal_details where MANUFACTURER_ID='".$id."'");
?>
<option selected disabled="disabled">Select Modal Name</option>
<?php
while($row = mysqli_fetch_assoc($sql))
{
$id = $row['MODAL_ID'];
$data = $row['MODAL_NAME'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
?>
Whenever I create a new field dynamically my AJAX is not working.

Try this :
<script type="text/javascript">
$(document).ready(function()
{
$(document).on('change','#manu',function()
{
var id = $("#manu").val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax_modal.php",
data: dataString,
cache: false,
success: function(html)
{
$("#modal").html(html);
}
});
});
});
</script>

The comments made it clear that you are duplicating your form. I think you have duplicate IDs on your page and your jQuery event will not work anymore. An ID may only occur once.
Take a look here:
Clone form and increment

Add the class to select as shown below:
<select name="manu" id="manu" class="form-control manuClass" style="width:100%">
And use the below script
<script type="text/javascript">
$(document).ready(function()
{
$(document).on('change','.manuClass',function()
{
var id = $(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax_modal.php",
data: dataString,
cache: false,
success: function(html)
{
$(this).parent().parent().next().children().children("#modal").html(html);
}
});
});
});
</script>

Related

How to submit form including image on button click [duplicate]

This question already has answers here:
Sending formdata for file upload using ajax
(3 answers)
Closed 9 months ago.
I have this HTML:
<form id="form" enctype="multipart/form-data">
<div class="row">
<div class="col">
<div class="mb-3">
<label for="design_title" class="form-label">Ttile of the design</label>
<input type="text" name="design" class="form-control" id="design_title">
</div>
</div>
<div class="col">
<div class="mb-3">
<label for="design" class="form-label">Upload a new design</label>
<input type="file" name="design" class="form-control" id="design">
</div>
</div>
</div>
<div class="mb-3">
<div class="row">
<div class="col">
<label for="fontsize" class="form-label">Enter the font size</label>
<input type="number" name="design_font_size" class="form-control" id="fontsize">
</div>
<div class="col">
<label for="position_x" class="form-label">Position X</label>
<input type="number" name="design_x" class="form-control" id="position_x">
</div>
<div class="col">
<label for="position_y" class="form-label">Position Y</label>
<input type="number" name="design_y" class="form-control" id="position_y">
</div>
</div>
</div>
<div class="mb-3">
<label class="form-label" for="domain">Choose a domain</label>
<select name="domain" id="domain" class="form-control" data-form="design_output">
<option value="">--Choose--</option>
<?php
$get_domain = mysqli_query( $mysqli, "SELECT * FROM eg_domains");
if( mysqli_num_rows( $get_domain ) > 0 ) {
while( $get_result = mysqli_fetch_array( $get_domain, MYSQLI_ASSOC ) ) {
$domain_name = $get_result['domain_name'];
$company = $get_result['company_name'];
$domain_id = $get_result['domain_id'];
echo "<option value='$domain_id'>$domain_name ($company)</option>";
}
}
?>
</select>
</div>
<button type="button" class="btn btn-primary ajax-btn output-desing" data-form="output_design">Output Design</button>
<button type="submit" class="btn btn-success ajax-btn">Save Design</button>
<div class="mt-3">
<div class="result"></div>
</div>
</form>
Now, on Output Design button click I want to get all the data including image.
So, I am doing this in JQuery/Ajax:
$(document).on("click", ".output-desing", function (e) {
e.preventDefault();
var form = document.querySelector(".output-desing");
var form_name = form.dataset.form;
var data = $("#form").serialize() + "&form=" + form_name;
// var data = '1';
console.log(data);
$.ajax({
dataType: "html",
type: "GET",
url: 'helper/process.php',
data: data,
contentType: false,
cache: false,
processData: false,
beforeSend: function () {
$(".output-design").val("Please wait...");
},
success: function (data) {
$(".output-design").html(data);
}
});
});
But I can get only form data not image data.
How can I get all the data including image data on that button click?
Anyways, I fix it this way:
var form = document.querySelector(".output-desing");
var form_name = form.dataset.form;
var data = new FormData(document.getElementById("form"));
data.append('form', form_name);

AJAX fails to get data from input

I am trying to create/insert data into the database, but I am still getting an error for getting the data I've input. I tried using the dump and die method, and I encountered that no data is being gotten from the data that has been input. What could be wrong with my codes?
Here is the result of the inspected element
Click to see image
My Modal
<div id="modalAddChild" class="modal fade" tabindex="-1" aria-labelledby="modalAddChild">
#csrf_field
{{ method_field('PUT') }}
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"><b>Add Child</b></h4>
<button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">X</button>
</div>
<div class="modal-body">
<p><i>Note: In Weight, it is required to put (.) regardless if it is (.0).</i></p>
<p><i>Note: In Height, do not add (.) if it is (.0) but it is allowed to put (.) if it's any number.</i>
</p>
<form id="saveChild" method="post">
<div class="form-group row">
<div class="col-sm-6">
<label for="mothersname">Mother's Name:</label>
<input type="text" class="form-control" id="mothersname" name="mothersname" required>
</div>
<div class="col-sm-6">
<label for="childsname">Child's Name:</label>
<input type="text" class="form-control" id="childsname" name="childsname" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
<label>Indigenous:</label>
<select class="form-control" id="ind_id" name="ind_id" required>
<option value="">YES or NO</option>
#foreach ($indigenous as $key => $value)
<option id="{{ $key }}" value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
</div>
<div class="col-sm-6">
<label>Sex:</label>
<select class="form-control" id="sex_id" name="sex_id" required>
<option value="">M or F</option>
#foreach ($sex as $key => $value)
<option id="{{ $key }}" value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
<label>Date of Birth:</label>
<input type="text" class="form-control" id="birthdate" name="birthdate"
placeholder="YYYY-MM-DD" required>
</div>
<div class="col-sm-6">
<label>Actual Date of Weighing:</label>
<input type="text" class="form-control" id="actualdate" name="actualdate"
placeholder="YYYY-MM-DD" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
<label>Weight(kg):</label>
<input type="text" class="form-control" id="weight" name="weight" required>
</div>
<div class="col-sm-6">
<label>Height(cm):</label>
<input type="text" class="form-control" id="height" name="height" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
<label for="zone">Zone:</label>
<input type="text" class="form-control" id="zone" name="zone" required>
</div>
<div class="col-sm-6">
<label>Age in Months:</label>
<input type="text" class="form-control" id="ageinmonths" name="ageinmonths" required>
</div>
</div>
<div class="form-group">
<button type="submit" value="Submit" class="btn btn-flat btn-primary" id="saveBtn">Submit</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
My AJAX
<script type="text/javascript">
$('#saveChild').submit('click', function() {
var zone = $('#zone').val();
var mothersname = $('#mothersname').val();
var childsname = $('#childsname').val();
var ind_id = $('#ind_id').val();
var sex_id = $('#sex_id').val();
var birthdate = $('#birthdate').val();
var actualdate = $('#actualdate').val();
var weight = $('#weight').val();
var height = $('#height').val();
var ageinmonths = $('#ageinmonths').val();
var dataString="zone="+zone+"&mothersname="+mothersname+"&childsname="+childsname+"&ind_id="+ind_id+"&sex_id="+sex_id
+"&birthdate="+birthdate+"&actualdate="+actualdate+"&weight="+weight+"&height="+height+"&ageinmonths="+ageinmonths;
$.ajax({
type: "POST",
dataType: "JSON",
data: dataString,
url: "insert_child",
success: function(data) {
console.log(data);
if (data == "success"){
alert("Data successfully added!");
} else if (data = "failed") {
alert("ERROR IN FETCHING DATA!");
}
displayData();
}
});
return false;
});
$('#saveBtn').click(function() {
$('#modalAddChild').modal('hide');
});
$('#modalAddChild').on('hidden.bs.modal', function(e) {
$(this)
.find("input,textarea,select")
.val('')
.end()
.find("input[type=checkbox], input[type=radio]")
.prop("checked", "")
.end();
})
</script>
This old ajax is working before but I changed it to the ajax mentioned above but both of them are not working anymore.
My OLD Ajax
<script type="text/javascript">
$('#saveChild').submit('click', function() {
var zone = $('#zone').val();
var mothersname = $('#mothersname').val();
var childsname = $('#childsname').val();
var ind_id = $('#ind_id').val();
var sex_id = $('#sex_id').val();
var birthdate = $('#birthdate').val();
var actualdate = $('#actualdate').val();
var weight = $('#weight').val();
var height = $('#height').val();
var ageinmonths = $('#ageinmonths').val();
$.ajax({
type: "POST",
dataType: "JSON",
data: {
zone: zone,
mothersname: mothersname,
childsname: childsname,
ind_id: ind_id,
sex_id: sex_id,
birthdate: birthdate,
actualdate: actualdate,
weight: weight,
height: height,
ageinmonths: ageinmonths,
"_token": "{{ csrf_token() }}"
},
url: "insert_child",
success: function(data) {
alert("Data successfully added!");
displayData();
}
});
return false;
});
$('#saveBtn').click(function() {
$('#modalAddChild').modal('hide');
});
$('#modalAddChild').on('hidden.bs.modal', function(e) {
$(this)
.find("input,textarea,select")
.val('')
.end()
.find("input[type=checkbox], input[type=radio]")
.prop("checked", "")
.end();
})
</script>
well in your first line off java script you wrote:
$('#saveChild').submit('click', function()
this is wrong, the jquery submit event only gets a function, but you passed a 'click' event as well.
you should write it like this:
$('#saveChild').submit(function()...

backend not adding books to android app sql

i have made an ebook android app everything works fine but the backend code of admin age which is written in php and javascript .the admin has a function to add book known as savebook the "savebook" function is not working please help me guys....every time i try to add a book i it just shows a failed message but when i add the book to the database manually via phpmyadmin it works here is the code to that function
the problem is in last function (what is think) but stil i would appreciate if you guys find some other mistake in the code the whole website is working but this only function is not working the app in on android platform the backend is done using codeigniter and the app is linked to a database which maintains the details of book
<?php
$this->load->view('admin/comman/header');
?>
<div class="clearfix"></div>
<div class="content-wrapper">
<div class="container-fluid">
<!-- Breadcrumb-->
<div class="row pt-2 pb-2">
<div class="col-sm-9">
<h4 class="page-title">Add Book</h4>
<ol class="breadcrumb">
<li class="breadcrumb-item">Dashboard</li>
<li class="breadcrumb-item">Books</li>
<li class="breadcrumb-item active" aria-current="page">Add Book</li>
</ol>
</div>
<div class="col-sm-3">
<div class="btn-group float-sm-right">
Books List
</div>
</div>
</div>
<!-- End Breadcrumb-->
<div class="row">
<div class="col-lg-10 mx-auto">
<div class="card">
<div class="card-body">
<div class="card-title">Add Book
<form id="edit_video_form" enctype="multipart/form-data">
<div class="form-group">
<label for="input-1">Book Name</label>
<input type="text" required value="" class="form-control" name="input_name" id="input-1">
</div>
<input type="hidden" name="id" value="">
<div class="form-group">
<label for="input-3">Book Cost</label>
<select name="select_cost" required class="form-control" id="purpose">
<option value="0">Free</option>
<option value="1">Paid</option>
</select>
</div>
<div class="form-group" id="business" style="display:none">
<label for="input-1">Book price</label>
<input type="text" required value="" class="form-control" name="input_price" id="input-1" placeholder="Enter Book Price">
</div>
<div class="form-group">
<label for="input-2">Book Category</label>
<!-- DropDown -->
<select name="select_category" required class="form-control">
<option value="">Select Category</option>
<?php $i = 1;
foreach($categorylist as $cat) { ?>
<option required value="<?php echo $cat->cat_id; ?>"><?php echo $cat->cat_name; ?></option>
<?php $i++;
} ?>
</select>
</div>
<div class="form-group">
<label for="input-2">Book Author</label>
<!-- DropDown -->
<select name="select_author" required class="form-control">
<option value="">Select Author</option>
<?php $i = 1;
foreach($authorlist as $cat) { ?>
<option value="<?php echo $cat->a_id; ?>"><?php echo $cat->a_title; ?></option>
<?php $i++;
} ?>
</select>
</div>
<div class="form-group">
<label for="input-1"> Book Cover Poster</label>
<input type="file" required class="form-control" name="input_bookcover" id="input-1" placeholder="select Book Cover image"
onchange="readURL(this,'showImage')">
<input type="hidden" name="input_bookcover" value="">
<p class="noteMsg">Note: Image Size must be less than 2MB.Image Height and Width less than 1000px.</p>
<img id="showImage" src="<?php echo base_url() . 'assets/images/placeholder.png'; ?>" height="100" width="100" alt="your image"/>
</div>
<div class="form-group">
<label for="input-1"> Upload Sample Book</label>
<input type="file" required class="form-control" name="input_sample_book" id="input-1" placeholder="select Sample Book">
<input type="hidden" name="input_sample_book" value="">
</div>
<div class="form-group">
<label for="input-1"> Upload Full Book</label>
<input type="file" required class="form-control" name="input_full_book" id="input-1" placeholder="select Full Book">
<input type="hidden" name="input_full_book" value="">
</div>
<div class="form-group">
<label for="input-1">Book Description</label>
<textarea cols="40" rows="5" style="height: 150px" type="text" required value="" class="form-control" name="input_description"
id="input-1"></textarea>
</div>
<div class="form-group">
<button type="button" onclick="savebook()" class="btn btn-primary shadow-primary px-5">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
$this->load->view('admin/comman/footerpage');
?>
<script type="text/javascript">
$('#purpose').on('change', function () {
if (this.value === '1') {
$("#business").show();
} else {
$("#business").hide();
}
});
function savebook() {
var wallpaper_title = jQuery('input[name=wallpaper_title]').val();
if (wallpaper_title == '') {
toastr.error('Please enter Book Name');
return false;
}
$("#dvloader").show();
var formData = new FormData($("#edit_video_form")[0]);
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>index.php/admin/savebook',
data: formData,
cache: false,
contentType: false,
processData: false,
dataType: "json",
success: function (resp) {
$("#dvloader").hide();
if (resp.status == '200') {
document.getElementById("edit_video_form").reset();
toastr.success(resp.msg, 'success');
setTimeout(function () {
location.reload();
}, 500);
} else {
toastr.error(resp.msg);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#dvloader").hide();
toastr.error(errorThrown.msg, 'failed');
}
});
}
</script>
here is the database code
enter code here
public function savebook(){
$input_name = $_POST['input_name'];
$input_description = $_POST['input_description'];
$input_price = $_POST['input_price'];
$select_category = $_POST['select_category'];
$select_author = $_POST['select_author'];
$select_cost = $_POST['select_cost'];
$is_feature = "yes";
$b_status = "enable";
$fa_id = $_POST['select_author'];
$input_bookcover=$this->imageupload($_FILES['input_bookcover'],'input_bookcover', FCPATH . 'assets/images/book');
if (isset($_FILES['input_sample_book']) && !empty($_FILES['input_sample_book']['name'])) {
$input_sample_book=$this->fileupload($_FILES['input_sample_book'],'input_sample_book', FCPATH . 'assets/images/book');
}
if (isset($_FILES['input_full_book']) && !empty($_FILES['input_full_book']['name'])) {
$input_full_book=$this->fileupload($_FILES['input_full_book'],'input_full_book', FCPATH . 'assets/images/book');
}
$data = array(
'b_title' => $input_name,
'b_description' => $input_description,
'is_paid' => $select_cost,
'sample_b_url' => $input_sample_book,
'b_url' => $input_full_book,
'b_price' => $input_price,
'fcat_id'=> $select_category,
'b_image' => $input_bookcover,
'is_feature' => $is_feature,
'b_status' => $b_status,
'fa_id' => $fa_id,
'b_date' => date('Y-m-d h:i:s')
);
$res_id=$this->Adminmodel->add_book($data);
if($res_id){
$res=array('status'=>'200','msg'=>'Book added successfully.','id'=>$res_id);
echo json_encode($res);exit;
}else{
$res=array('status'=>'400','msg'=>'fail');
echo json_encode($res);exit;
}
}

how to upload files from 2 different file input in from with ajax using formData?

I'm trying to upload 2 file which is in form with ajax but when i print_r($_POST) and print_r($_FILES) it showing me empty array.
here is my html code:
<form id="addFloorEntityTypeFrom" method="POST" action="api/apiRoute.php" enctype="multipart/form-data boundary=----WebKitFormBoundary0BPm0koKA">
<div class="col-md-12">
<div class="form-group">
<label for="categories">Category *</label>
<select class="form-control" id="categories" name="category" required>
<option value="">Please select category</option>
<?php foreach ($categories as $category) {
echo "<option value=\"" . $category['entityTypeId'] . "\">" . $category['entityName'] . "</option>";
} ?>
</select>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="typeSVG" class="sr-only">Upload SVG *</label>
<div class="input-group">
<input type="text" name="filename" class="form-control custom-file" placeholder="Please select base svg file" readonly>
<span class="input-group-btn">
<div class="btn btn-dark custom-file custom-file-uploader">
<input type="file" id="typeSVG" name="entityTypeBaseSVG" onchange="this.form.filename.value = this.files.length ? this.files[0].name : ''" required/>
Browse
</div>
</span>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="baseImage" class="sr-only">Upload style Image *</label>
<div class="input-group">
<input type="text" name="baseImage_filename" class="form-control custom-file" placeholder="Please base style image" readonly>
<span class="input-group-btn">
<div class="btn btn-dark custom-file custom-file-uploader">
<input type="file" id="baseImage" name="base_style_image" onchange="this.form.baseImage_filename.value = this.files.length ? this.files[0].name : ''" required />
Browse
</div>
</span>
</div>
</div>
</div>
<div class="col-md-12">
<button type="button" name="addFloorEntity" onclick="SaveEntity(this, true)" class="btn btn-dark mt-3">Save</button>
<button type="button" onclick="closeBaseEntity()" class="btn btn-default mt-3">Cancel</button>
</div>
</form>
here is my JavaScript code.
var formData = new FormData();
var formDataArray = $(form[0]).serializeArray();
for(let i = 0; i < formDataArray.length; i++) {
if(formDataArray[i].name !== 'entityTypeBaseSVG' || formDataArray[i].name !== 'base_style_image') {
formData.append(formDataArray[i].name, formDataArray[i].value);
}
}
formData.append('entityTypeBaseSVG', $('#typeSVG')[0].files[0]);
formData.append('base_style_image', $('#baseImage')[0].files[0]);
$.ajax({
method: "POST",
url: baseUrl + 'newIFPAdmin/api/apiRoute.php',
data: formData,
cache: false,
contentType: false,
processData: false,
}).done(function (response) {
console.log('response', response);
});
this is my server side code..
print_r(json_decode(file_get_contents('php://input'), true));
print_r($_POST);
print_r($_FILES);
exit;
response is:
Array
(
)
Array
(
)
Please try this code. It's working fine. Review screenshot.
https://ibb.co/wJWLfW5
<form id="addFloorEntityTypeFrom" method="POST" action="" enctype="multipart/form-data boundary=----WebKitFormBoundary0BPm0koKA">
<div class="col-md-12">
<div class="form-group">
<label for="categories">Category *</label>
<select class="form-control" id="categories" name="category" required>
<option value="">Please select category</option>
<?php foreach ($categories as $category) {
echo "<option value=\"" . $category['entityTypeId'] . "\">" . $category['entityName'] . "</option>";
} ?>
</select>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="typeSVG" class="sr-only">Upload SVG *</label>
<div class="input-group">
<input type="text" name="filename" class="form-control custom-file" placeholder="Please select base svg file" readonly>
<span class="input-group-btn">
<div class="btn btn-dark custom-file custom-file-uploader">
<input type="file" id="typeSVG" name="entityTypeBaseSVG" onchange="this.form.filename.value = this.files.length ? this.files[0].name : ''" required/>
Browse
</div>
</span>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="baseImage" class="sr-only">Upload style Image *</label>
<div class="input-group">
<input type="text" name="baseImage_filename" class="form-control custom-file" placeholder="Please base style image" readonly>
<span class="input-group-btn">
<div class="btn btn-dark custom-file custom-file-uploader">
<input type="file" id="baseImage" name="base_style_image" onchange="this.form.baseImage_filename.value = this.files.length ? this.files[0].name : ''" required />
Browse
</div>
</span>
</div>
</div>
</div>
<div class="col-md-12">
<button type="button" name="addFloorEntity" onclick="SaveEntity(this, true)" class="btn btn-dark mt-3">Save</button>
<button type="button" onclick="closeBaseEntity()" class="btn btn-default mt-3">Cancel</button>
<script>
function SaveEntity()
{
var formData = new FormData();
var formDataArray = $("form").serializeArray();
for(let i = 0; i < formDataArray.length; i++) {
if(formDataArray[i].name !== 'entityTypeBaseSVG' || formDataArray[i].name !== 'base_style_image') {
formData.append(formDataArray[i].name, formDataArray[i].value);
}
}
formData.append('entityTypeBaseSVG', $('#typeSVG')[0].files[0]);
formData.append('base_style_image', $('#baseImage')[0].files[0]);
$.ajax({
method: "POST",
url: 'demo.php',
data: formData,
cache: false,
contentType: false,
processData: false,
}).done(function (response) {
console.log('response', response);
});
}
</script>

I want to display data from database.if we newly add a form data ,i want to append the new post on display without refresh using codeigniter

I have a show and hide div. That is an add form. I want to display all data from the table on the bottom of the form. If form is opened or not, the data must be displayed. When we add new post, that must append on the top of displayed data without refresh.
My view
<div class="slidingDiv" style="display:none">
<div class="row">
<div class="col-xs-12">
<div class="box box-primary">
<div class="box-header">
<h3 class="box-title">Add Requirement Item</h3>
</div><!-- /.box-header -->
<!-- form start -->
<?php echo validation_errors(); ?>
<?php
$attributes = array('id' => 'myForm');
echo form_open_multipart(base_url().'moderator/Requirement/add_employee_data',$attributes); ?>
<div class="box-body">
<div class="row">
<div class="col-xs-6">
<div class="form-group">
<div class="row">
<div class="col-xs-12">
<label for="txttitle">Requirement Title (Product/Service) : </label>
</div>
<div class="col-xs-12">
<input type="text" name="txtService" class="form-control" id="txttitle" placeholder="Requirement Title (Product/Service) : " value="" required>
</div>
</div>
</div>
</diV>
<div class="col-xs-6">
<div class="form-group">
<div class="row">
<div class="col-xs-8">
<label for="txtquantity">Estimated Quantity : </label>
</div>
<div class="col-xs-4">
<label for="txtquantity"></label>
</div>
<div class="col-xs-8">
<input type="text" name="txtQuantity" class="form-control" id="txtquantity" placeholder="Estimated Quantity" value="
" required>
</div>
<div class="col-xs-4">
<select class="form-control" name="txtunit" required="required">
<option value="">----Select------</option>
<?php
foreach ($units as $name) {
echo ' <option value="' . $name->id . '">' . $name->name . '</option>';
}
?>
</select>
</div>
</div>
</div>
</diV>
<div class="col-xs-12">
<div class="form-group">
<div class="row">
<div class="col-xs-12">
<label for="txtdetails">Requirement Details : </label>
</div>
<div class="col-xs-12">
<textarea class="textarea" name="txtRequirement" placeholder="Requirement Details" id="txtdetails" style="width: 100%; height: 200px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;">
</textarea>
</div>
</div>
</div>
</div>
<div class="col-xs-12">
<div class="form-group">
<div class="row">
<div class="col-xs-6">
<label for="sbUser">Expiry of Requirement : </label><br>
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input id="thedate" type="text" name="txtBidclosing" class="form-control" required="required"/>
</div>
</div>
</div>
</div>
</div>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<input type="button" class="button" value="submit" />
</form>
</div>
</div>
</div>
</div>
<div id="sort">
<br>
</div>
Ajax code
<script>
$(document).ready(function(){
$(".button").click(function(){
$.ajax({
type:"POST",
url: "<?php echo base_url() ?>moderator/Requirement/add_employee_data",
data:$("#myForm").serialize(),
success: function (dataCheck) {
//alert(dataCheck);
$('#sort').append(dataCheck);
//window.location.reload();},
});});});
</script>
Model
public function add_employee_data($data){
$this->db->insert('jil_requirementdetail',$data);
$id = $this->db->insert_id();
$this->db->select('*');
$this->db->from('jil_requirementdetail');
$this->db->where('rqmd_id',$id);
$result = $this->db->get()->result();
return $result;
}
On your model
public function add_employee_data($data){
$this->db->insert('jil_requirementdetail',$data);
$id = $this->db->insert_id();
$this->db->select('*');
$this->db->from('jil_requirementdetail');
// $this->db->where('rqmd_id',$id); // get all data
$this->db->order_by('rqmd_id','DESC');
$result = $this->db->get();
if($result->num_row() > 0)
{
echo json_encode(['status'=>'pass','data'=>$result->result()];
}else{
echo json_encode(['status'=>'fail']);
}
}
On Ajax Success
<script>
$(document).ready(function(){
$(".button").click(function(){
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>moderator/Requirement/add_employee_data",
data: $("#myForm").serialize(),
success: function(dataCheck){
//alert(dataCheck);
var res = JSON.parse(dataCheck);
if(res.status=='pass')
{
var user_data = res.data;
var html = '';
var length = user_data.length;
for(var i = 0; i < length; i++)
{
//your html
html += '<div>' + user_data[i].name + '</div>'; //add your html structure as you want
}
$('#sort').append(html);
},
}
});
});
});
</script>

Categories