Hi guys i have an issue for displaying all data where a column with name header_id having same data. but when it displayed, his result
just one row. actually of data with header_id='100002' having 4 rows.Thanks.
Model:
function getdtHeaderid($header_id = FALSE) {
if ($header_id === FALSE)
{
$query = $this->db1->get('tbltransactiondtl');
return $query->result_array();
}
$query = $this->db1->get_where('tbltransactiondtl', array('header_id' => $header_id));
return $query->row_array();
}
Controller:
function getdtHeaderid() {
$header_id = $this->input->post('header_id');
$data=$this->M_selltransaction->getdtHeaderid($header_id);
echo json_encode($data);
}
View:
<div class="col-md-6">
<label for="header_id" class="col-md-4 control-label" style="text-align:left">Transaction No</label>
<label class="col-md-1 control-label">:</label>
<div class="col-md-6">
<div class="input-group input-group-unstyled">
<input type="text" class="header_id form-control" placeholder="Search" id="header_id" name="header_id"/>
<span class="input-group-addon"><i class="fa fa-search "></i></span>
</div>
</div>
</div>
<table>
<td><input type="text" width="10" class="detail_id form-control"
id="detail_id" name="detail_id[]" value="<?php $a =
set_value('detail_id[0]'); echo $a;?>" required ></td>
<td><input
type="text" width="10" class="item_code form-control" id="item_code"
name="item_code[]" value="<?php $a = set_value('item_code[0]'); echo
$a;?>" required ></td>
<td><input type="text" class="item_name
form-control" id="item_name" name="item_name[]" value=""
readonly></td>
</table>
<script type="text/javascript">
function getdHeaderid(header_id){
var header_id = header_id.val();
$.ajax({
type : "post",
data : {header_id:header_id},
url : "<?php echo base_url();?>index.php/transaction/selltransaction/getdtHeaderid",
dataType:"json",
cache :false,
success: function(data){
console.log(data);
$(".detail_id").val(data.detail_id);
$(".item_code").val(data.item_code);
$(".item_name").val(data.item_name);
}
});
}
$(document).ready(function() {
$('.header_id').on('keyup change', function() {
getdHeaderid($(this));
});
});
function getdtHeaderid($header_id = FALSE) {
if ($header_id === FALSE)
{
$query = $this->db1->get('tbltransactiondtl');
return $query->result_array();
}
$query = $this->db1->get_where('tbltransactiondtl', array('header_id' => $header_id));
return $query->result_array();
}
Here is Your Correct model function you were using row_array() instead of result_array() thats why getting only one result
update
$(".detail_id").val(data.detail_id);
$(".item_code").val(data.item_code);
$(".item_name").val(data.item_name);
to
$(".detail_id").val(data[0].detail_id);
$(".item_code").val(data[0].item_code);
$(".item_name").val(data[0].item_name);
Related
I want to sent some data with ajax to a php file. I created a FormData, and then, i append all the data to it, that i want to send. I dont get any error message in the console.
My problem is, that the formdata is always empty, and the php file is not getting any data also.
The form:
<div class="tab-pane show" id="tab5">
<form id="AllapotForm" class="form-horizontal" method="post" enctype="multipart/form-data">
<table id="products" class="table table-hover">
<thead>
<tr class="tr_bold">
<!--width="33.3%"-->
<td class="left" >Létrehozva</td>
<td class="left" >Állapot</td>
<td class="left" >A megrendelő értesítve email-ben</td>
<td class="left" >Megjegyzés</td>
</tr>
</thead>
<tbody id="allapotok">
<?php
$get_r_allaptok = mysqli_query($kapcs,
"
SELECT
rendeles_allapot.*,
rendeles_allapotok.rendeles_allapotok_nev
FROM rendeles_allapot
LEFT JOIN rendeles_allapotok ON rendeles_allapot.allapot_allapot_id = rendeles_allapotok.rendeles_allapotok_id
WHERE allapot_rendeles_id = '$id' ORDER BY allapot_id ASC
")
or die(mysqli_error($kapcs));
if(mysqli_num_rows($get_r_allaptok) > 0 )
{
while($r_allapot = mysqli_fetch_assoc($get_r_allaptok))
{
if($r_allapot['allapot_notify'] == 0 ) { $ertesitve = "Nem"; }
if($r_allapot['allapot_notify'] == 1 ) { $ertesitve = "Igen"; }
echo '<tr>
<td class="left">'.$r_allapot['allapot_datetime'].'</td>
<td class="left">'.$r_allapot['rendeles_allapotok_nev'].'</td>
<td class="left">'.$ertesitve.'</td>
<td class="left">'.$r_allapot['allapot_comment'].'</td>
</tr>';
}
}
?>
</tbody>
</table>
<img src="<?php echo $host; ?>/images/assets/preloader.gif" id="preloaderImage2" style="display:none" class="img-responsive" style="margin:10px auto;">
<div class="form-group row">
<label class="control-label col-md-2">Állapot:</label>
<div class="col-md-2">
<select name="allapot" id="allapot" class="input input-select form-control">
<?php
$check_allapot = mysqli_query($kapcs, "SELECT allapot_allapot_id FROM rendeles_allapot WHERE allapot_rendeles_id = '$id' ORDER BY allapot_id DESC LIMIT 1");
if(mysqli_num_rows($check_allapot) > 0 )
{
$allapot_fetch = mysqli_fetch_assoc($check_allapot);
$ertek = $allapot_fetch['allapot_allapot_id'];
}
else
{
$ertek = intval($a['status']);
}
$get_allapotok = mysqli_query($kapcs, "SELECT rendeles_allapotok_id, rendeles_allapotok_nev FROM rendeles_allapotok WHERE rendeles_allapotok_status = 1 ORDER BY rendeles_allapotok_nev ASC");
if(mysqli_num_rows($get_allapotok) > 0 )
{
while($allapot = mysqli_fetch_assoc($get_allapotok))
{
$selected = $ertek == $allapot['rendeles_allapotok_id'] ? ' selected="selected"':'';
echo '<option ' . $selected . ' value="' . $allapot['rendeles_allapotok_id'] . '">' . $allapot['rendeles_allapotok_nev'] . '</option>'."\n";
}
}
?>
</select>
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Megrendelő értesítése email-ben:</label>
<div class="col-md-2">
<input type="checkbox" name="notify" id="notify" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Megjegyzés hozzáadása az email-hez:<span class="help">Amennyiben ezt bepipálja, a megjegyzés az ügyfélnek kiküldött üzenetbe is bele fog kerülni.</span></label>
<div class="col-md-2">
<input type="checkbox" name="add_text" id="add_text" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Fájl csatolása az email-hez:</label>
<div class="col-md-2">
<input type="file" name="file" id="file" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Megjegyzés:</label>
<div class="col-md-8">
<textarea name="comment" id="comment" style="width:100%;height:200px;"></textarea>
<div style="margin-top: 10px; text-align: center;">
<a class="saveButton btn btn-primary" style="color:#fff" onclick="allapot_modosit();" id="history_button">Állapot módosítása</a>
</div>
</div>
</div>
</form>
</div>
I call this function on a button click event.
function send_data()
{
var html;
var RendelesID = <?php echo $id; ?>;
var RendelesUserEmail = "<?php echo html($a['email']); ?>";
var RendelesUserName = "<?php echo html($a['nev']); ?>";
var webshopEmail = "<?php echo $webshopEmail; ?>";
var webshopName = "<?php echo $webshopName; ?>";
var Allapot = $( "#allapot option:selected" ).val();
var Comment = CKEDITOR.instances['comment'].getData();
if($("#notify").is(':checked')){var Notify = 1;}else{var Notify = 0;}
if($("#add_text").is(':checked')){var AddToEmail = 1;}else{var AddToEmail = 0;}
var formData = new FormData($('#AllapotForm')[0]);
formData.append('fileName', $('#file')[0].files[0]);
formData.append(RendelesID, RendelesID);
formData.append(RendelesUserEmail, RendelesUserEmail);
formData.append(RendelesUserName, RendelesUserName);
formData.append(webshopEmail, webshopEmail);
formData.append(webshopName, webshopName);
formData.append(Allapot, Allapot);
formData.append(Comment, Comment);
formData.append(Notify, Notify);
formData.append(AddToEmail, AddToEmail);
console.log(formData);
$.ajax({
type: 'POST',
cache: false,
url: 'files/update_rendeles_allapot.php',
//dataType: 'html',
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: { formData:formData },
beforeSend: function(){
$('#preloaderImage2').show();
},
success: function(data)
{
alert(data);
},
complete: function(){
$('#preloaderImage2').hide();
},
error: function (e) {
alert(e.responseText);
console.log(e);
}
});
}
data: { formData:formData },
You need to pass the form data object itself, not a plain object.
data: formData
Have you already seen this?
FormData created from an existing form seems empty when I log it
If yes try to check your network look to the Network then take a look at your request.
You can also try to check your API via Postman if it's working properly.
I am not sure how to word this title. Feel free to edit it.
Intro I am doing a datatables.net library server-side table using JSON and PHP. I am basically done except for the edit form.
My first problem was solved. I had a while loop instead of an if statement.
My second problem is now going to be transferring this Javascript code near before the AJAX call:
var edit_id = $('#example').DataTable().row(id).data();
var edit_id = edit_id[0];
to here which is php:
$edit_id = $_POST['edit_id'];
They are both on the same page, index.php so I do not think I can use ajax for this.
Index.php
<script type="text/javascript">
$(document).on('click', '.edit_btn', function() {
var id = $(this).attr("id").match(/\d+/)[0];
var edit_id = $('#example').DataTable().row(id).data();
var edit_id = edit_id[0];
$("#form2").show();
//console.log(edit_id[0]);
$.ajax({
type: 'POST',
url: 'edit.php',
data: {
edit_id: edit_id,
first_name: $("#edit2").val(),
last_name: $("#edit3").val(),
position: $("#edit4").val(),
updated: $("#edit5").val(),
},
success: function(data) {
alert(data);
if (data == 'EDIT_OK') {
alert("success");
} else {
// alert('something wrong');
}
}
})
});
</script>
<?php
$sql="select * from employees WHERE id=$edit_id";
$run_sql=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($run_sql)){
$per_id=$row[0];
$per_first=$row[1];
$per_last=$row[2];
$per_position=$row[3];
//$per_date=$row[4];
$per_updated=$row[5];
?>
<form id="form2" class="form-horizontal">
<label class="col-sm-4 control-label" for="txtid">ID</label>
<input id="edit1" type="text" class="form-control" name="txtid" value="<?php echo $per_id;?>" readonly>
<div class="form-group">
<label class="col-sm-4 control-label" id="edit2" for="txtname">First Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="txtname" name="txtname" value="<?php echo $per_first;?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="txtsalary">Last Name</label>
<div class="col-sm-6">
<input type="number" class="form-control" id="edit3" name="txtsalary" value="<?php echo $per_last;?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="txtage">Position</label>
<div class="col-sm-6">
<input type="number" class="form-control" id="edit4" name="txtage" value="<?php echo $per_position;?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="txtage">Updated</label>
<div class="col-sm-6">
<input type="number" class="form-control" id="edit5" name="txtage" value="<?php echo $per_updated;?>">
</div>
<button type="button" class="close" value="Cancel" data-dismiss="modal">×</button>
<button type="button" class="update" value="Update"></button>
</form>
edit.php
$edit_id = $_POST['edit_id'];
$stmt = $conn->prepare("UPDATE employees SET first_name=?, last_name=?, position=?, updated=? WHERE id=?");
$stmt->bind_param('ssssi', $_POST['first_name'], $_POST['last_name'], $_POST['position'], $_POST['updated'], $_POST['edit_id']);
$confirmUpdate = $stmt->execute();
if($confirmUpdate) {
echo "EDIT_OK";
}else {
trigger_error($conn->error, E_USER_ERROR);
return;
}
?>
I eventually figured it out:
<script type="text/javascript">
$(document).on('click','.edit_btn',function (){
var id = $(this).attr("id").match(/\d+/)[0];
var edit_id = $('#example').DataTable().row( id ).data();
var edit_id = edit_id[0];
alert(edit_id);
$.ajax({
url: 'index.php',
data: { edit_id : edit_id },
contentType: 'application/json; charset=utf-8',
success: function(result) {
//alert(result);
}
});
});
</script>
I am trying to edit a open-source project which I downloaded from internet
I want to display the value of HSN no. in table,here is the code.
var $hsn;
$("#invoice_item").delegate(".product_name","change",function(){
var pid = $(this).val();
var tr = $(this).parent().parent();
if (pid != 0) {
$.ajax({
url : domain+"/includes/update.php",
method : "POST",
data : {get_price_qty:1,pid:pid},
success : function(data){
if(data == "NO_PRODUCT"){
alert("Sorry, Selected product is not available");
}else{
var ar = data.split(",");
tr.find(".pro_name").val(ar[2]);
tr.find(".price").val(ar[0]);
tr.find(".total_qty").val(ar[1]);
tr.find(".qty").val(0);
tr.find(".hsn").val(ar[3]);
tr.find(".amt").html(tr.find(".price").val() * tr.find(".qty").val());
$hsn=ar[3];
$("#discount").val(0);
}
}
})
}else{
alert("Please Select at least one product");
} })
Here is how the table looks
Now the code for adding a new row is as below
if (isset($_POST["addNewRow"])) {
$num = $_POST["number"];
$pro = new DBOperation();
$rows = $pro->displayBrandAndCategory("products");
?>
<tr>
<td><b class="number"></b></td>
<td>
<select name="pname[]" class="form-control form-control-sm product_name">
<option value="0">Choose Product</option>
<?php
foreach ($rows as $row) {
?>
<option value="<?php echo $row['pro_id']; ?>"><?php echo $row["pro_name"]; ?></option>
<?php
}
?>
</select>
</td>
<td><input name="total_qty[]" type="text" class="form-control form-control-sm total_qty" readonly></td>
<td><input name="qty[]" type="text" class="form-control form-control-sm qty"></td>
<td><input name="hsn[]" type="text" class="form-control form-control-sm qty" readonly> </td>
<td><input name="price[]" type="text" class="form-control form-control-sm price" readonly></td>
<td>Rs.<span class="amt">0</span></td>
</tr>
<?php
exit();}
but hsn column is always showing 0,I tried doing this
document.write(ar[3]);
It correctly shows the HSN no. I don't know exactly what the statement below does,could anyone explain it to me?
tr.find(".hsn").val(ar[3]);
Hi I am using codeigniter framework. I have a auto fill code like when I enter a id in a text box it retrieves a value from database and fills the remaining text box automatically.
When I type the full id and click somewhere I made to auto-fill with the help of ajax. Now when I select some data from the related data drop down I need to auto fill them. How to do this?
Can someone help me code?
Here is my code where I am got struck.
My controller function
<?php
class Admin_billing extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('billing_model');
$this->load->model('client_model');
$this->load->model('employee_model');
$this->load->model('products_model');
$this->load->model('package_model');
if(!$this->session->userdata('is_logged_in')){
redirect('admin/login');
}
}
public function ticket($id)
{
$id=$this->uri->segment(4);
$data['id']=$this->uri->segment(4);
$data['main_content'] = 'admin/billing/ticket_page';
$this->load->view('includes/template', $data);
}
public function getdetails()
{
$data_to_search=$_POST['val'];
$details=array();
$details['description']=$this->billing_model->get_service_name($data_to_search);
$details['type']=$this->billing_model->get_service_name($data_to_search);
$details['cost']=$this->billing_model->get_service_name($data_to_search);
$details['qty_prch'] = 1;
$details['qty_used'] = 1;
$details['price']=$this->billing_model->get_service_pricevalue($data_to_search);
echo json_encode($details);
}
}?>
This is my controller page admin_billing.php. Here I have a getdetails() that is called when I enter some value in the text box and click somewhere. When I click somewhere or press tab the value is posted from view to this function with help of ajax.
This is my model page.
<?php
class billing_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function get_service_name($id)
{
$this->db->select('*');
$this->db->from('service');
$this->db->where('id', $id);
$query = $this->db->get();
$result = $query->result_array();
return $result[0]['name'];
}
public function get_service_pricevalue($id)
{
$this->db->select('*');
$this->db->from('service');
$this->db->where('id', $id);
$query = $this->db->get();
$result = $query->result_array();
return $result[0]['price'];
}
public function get_service_mins($id)
{
$this->db->select('*');
$this->db->from('service');
$this->db->where('id', $id);
$query = $this->db->get();
$result = $query->result_array();
return $result[0]['mins'];
}
public function get_service_price($id)
{
$this->db->select('*');
$this->db->from('service');
$this->db->where('id', $id);
$query = $this->db->get();
$result = $query->result_array();
return $result[0]['price'];
}
public function get_service_id($id)
{
$this->db->select('*');
$this->db->from('service');
$this->db->where('id', $id);
$query = $this->db->get();
$result = $query->result_array();
return $result[0]['id'];
}
}
?>
Here in this model page, billing_model.php I have few function which retrieves the value from database. Here I get the id from the controller search for it and get the related content with the help of id.
Here is my view page.
I have a function that when onchange action happens get the value from my textbox with name pid[] and calls a ajax function getvalues()
I have another function BindControls() for auto-complete action. When I select some value again I need to pass that value to the ajax function getvalues()
<html>
<head>
<link href="<?php echo base_url(); ?>assets/css/demo.css" rel="stylesheet">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type='text/javascript' src='//code.jquery.com/jquery-compat-git.js'></script>
<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>
<script type='text/javascript'>
var baseurl='<?php echo base_url(); ?>';
$(function() {
$('#test').on('change', 'input[name="pid[]"]', function() {
var indexOfTheChangedRow = $(this).closest("tr").index();
get_values(this.value, indexOfTheChangedRow);
});
});
function get_values(val,rowIndex)
{
$.ajax({
url: baseurl + 'admin/billing/getdetails',
type: 'post',
data: {
val: val
},
success: function (indexOfTheChangedRow, response) {
if (response != "") {
var json = jQuery.parseJSON(response),
rowToUpdate = $("#test tr:nth-child(" + (indexOfTheChangedRow + 1) + ")");
// add the changed row as the context to restrict the search for the classes to this one row only
$('.description', rowToUpdate).val(json.description);
$('.type', rowToUpdate).val(json.type);
$('.qty_used', rowToUpdate).val(json.qty_used);
$('.qty_prch', rowToUpdate).val(json.qty_prch);
$('.price', rowToUpdate).val(json.price);
}
}.bind(window, rowIndex),
error: function (response) {
alert("error");
}
});
}
function displayResult() {
<?php
$attributes = array('class' => 'form-horizontal', 'id' => '');
$options_employee = array('' => "Select");
foreach ($employee as $row)
{
$options_employee[$row['first_name']] = $row['first_name'];
}
$dropdown = form_dropdown('employee', $options_employee, set_value('employee[]'), 'class="span2"');
?>
var complex = <?php echo json_encode($dropdown); ?>;
var row = document.getElementById("test").insertRow(-1);
row.innerHTML = '<td><div>'+complex+'</div></td><td><input type="text" name="start_time[]" value="" style="width:35px;"/></td><td><input type="text" name="pid[]" style="width:35px;"/></td><td><input type="text" name="description[]" class="description" value="" style="width:145px;"/></td><td><input type="text" class="type" value="" style="width:45px;"/></td><td class="qty_prch"><input type="text" class="qty_prch" value="" style="width:45px;"/></td><td><input type="text" class="qty_used" value="" style="width:45px;"/></td><td class="price"><input type="text" class="price" value="" style="width:70px;"/></td><td><input type="text" value="" class="discount" style="width:70px;"/></td><td><input type="text" value="" class="tax" style="width:70px;"/></td><td class="total"><input type="text" value="" class="total" style="width:70px;"/></td>';
}
</script>
<script>
$(document).ready(function () {
$('#test').on('mousemove', 'input', sumtotal);
function sumtotal() {
var hour = 0;
var rate = 0;
var total = 0;
var subtotal = 0;
$('#test tbody tr').each(function () {
hour = parseNumber($(this).find('.price input').val());
rate = parseNumber($(this).find('.qty_prch input').val());
subtotal = (hour * rate);
$(this).find('.total input').val(subtotal);
total += subtotal;
});
$('.Grandtotal input').val(total);
}
function parseNumber(n) {
var f = parseFloat(n); //Convert to float number.
return isNaN(f) ? 0 : f; //treat invalid input as 0;
}
});
$(document).ready(function() {
BindControls();
});
function BindControls() {
var Countries = ['ARGENTINA',
'AUSTRALIA',
'BRAZIL',
'BELARUS',
'BHUTAN',
'CHILE',
'CAMBODIA',
'CANADA',
'CHILE',
'DENMARK',
'DOMINICA'];
$('#pid').autocomplete({
source: Countries,
autoFocus: true,
minLength: 0,
scroll: true
}).focus(function() {
$(this).autocomplete("search", "");
});
}
</script>
</head>
<?php
$attributes = array('class' => 'form-horizontal', 'id' => '');
$options_employee = array('' => "Select");
foreach ($employee as $row)
{
$options_employee[$row['first_name']] = $row['first_name'];
}
echo form_open('admin/billing/ticket_page');
?>
<table id="test">
<thead>
<tr>
<td style="width:80px;">employee</td>
<td style="width:35px;">start time</td>
<td style="width:35px;">id</td>
<td style="width:145px;">Description</td>
<td style="width:45px;">Type</td>
<td style="width:45px;">Qty prch</td>
<td style="width:45px;">Qty used</td>
<td style="width:70px;">Price</td>
<td style="width:70px;">discount</td>
<td style="width:70px;">Tax</td>
<td style="width:70px;">Total</td>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo form_dropdown('employee', $options_employee, set_value('employee[]'), 'class="span2"');?></td>
<td><input type="text" name="start_time[]" value="" style="width:35px;"/></td>
<td><input type="text" name="pid[]" id="pid" value="" style="width:35px;"/></td>
<td><input type="text" name="description[]" class="description" value="" style="width:145px;"/></td>
<td><input type="text" name="type[]" class="type" style="width:45px;"/></td>
<td class="qty_prch"><input type="text" name="qty_prch[]" class="qty_prch" style="width:45px;"/></td>
<td><input type="text" name="qty_used[]" class="qty_used" style="width:45px;"/></td>
<td class="price"><input type="text" name="price[]" class="price" style="width:70px;"/></td>
<td><input type="text" name="discount[]" class="discount" style="width:70px;"/></td>
<td><input type="text" name="tax[]" class="tax" style="width:70px;"/></td>
<td class="total"><input type="text" name="total[]" class="total" style="width:70px;"/></td>
</tr>
</tbody>
</table>
<div id="add_row">
<button type="button" onClick="displayResult()" class="add_r"></button>
</div>
<?php echo form_close(); ?>
<div id="last_button">
<input type="button" class="Delete"/>
<input type="button" class="Edit"/>
<script src="<?php echo base_url(); ?>assets/js/function.js"></script>
</body>
</html>
Can someone help me code? Please give me some solutions.
When you add a row, the .on('autocompleteselection'... only works on existing html and not anything generated. You need to add delegation, so go from:
$(document).ready(function () {
$('#pid').on('autocompleteselect', function (e, ui) {
var indexOfTheChangedRow = $(this).closest("tr").index();
get_values(ui.item.value, indexOfTheChangedRow);
});
});
to
$(document).ready(function () {
$('#pid').on('autocompleteselect', 'tr',function (e, ui) {
var indexOfTheChangedRow = $(this).closest("tr").index();
get_values(ui.item.value, indexOfTheChangedRow);
});
});
That way you are delegating the .on to also include table rows added later
I create a search form that using ajax as the action. In success ajax, how can I just load some specific div without load all refresh page.
This is my form
<?php
$properties = array('id' => 'form1');
echo form_open("", $properties);
?>
<fieldset>
<div class="controls" id="chekboxes">
<label class="checkbox "><input type="checkbox" name="criteria[]" id="nomorcb"/> Nomor Request </label>
<input type="text" class="input-xlarge focused" id="no" name="no" placeholder="Masukkan No Request..."/>
<label class="checkbox "><input type="checkbox" name="criteria[]" id="namacb"/> Nama User </label>
<input type="text" class="input-xlarge focused" id="nama" name="nama" placeholder="Masukkan Nama User..."/>
<label class="checkbox "><input type="checkbox" name="criteria[]" id="departementcb" /> Departement</label>
<div class="control-group">
<div class="controls">
<select class="input-xlarge" id="selectError" name="dep">
<option value="">-- Pilih departement --</option>
<?php
foreach ($dep as $data) {
echo "<option value='" . $data['nama_departement'] . "'>" . $data['nama_departement'] . "</option>";
}
?>
</select>
</div>
</div>
<label class="checkbox "><input type="checkbox" name="criteria[]" id="rentangcb"/> Rentang waktu</label>
<div class="controls" id="tanggal-rentang">
<input type="text" class="input-small datepicker" id="tanggal" value="" name="tgl_awal"><span> s/d </span>
<input type="text" class="input-small datepicker" id="tanggal2" value="" name="tgl_akhir">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary" id="submit">Cari</button>
<button type="reset" class="btn" id="cancel">Cancel</button>
</div>
</fieldset>
<?php echo form_close(); ?>
this is the action's code for execute the form.
public function search() {
$id_request = $this->input->post('nomor');
$nama_user = $this->input->post('nama');
$departement = $this->input->post('departement');
$awal = $this->input->post('tgl_awal');
if ($awal != "") {
$awal = $this->input->post('tgl_awal');
} else {
$awal = "2014-01-01";
}
$timestamp_awal = strtotime($awal);
$tgl_awal = date("Y-m-d H:i:s", $timestamp_awal);
$akhir = $this->input->post('tgl_akhir');
if ($akhir != "") {
$akhir = $this->input->post('tgl_akhir');
} else {
$akhir = "2020-01-01";
}
$timestamp_akhir = strtotime($akhir);
$tgl_akhir = date("Y-m-d H:i:s", $timestamp_akhir);
$data = $this->model_request->search($id_request, $nama_user, $departement, $tgl_awal, $tgl_akhir);
echo json_encode($data);
}
and this is the Ajax jquery for form above :
$('form').on('submit', function() {
var nomor = $('#no').val();
var nama = $('#nama').val();
var departement = $('#selectError').val();
var tgl_awal = $('#tanggal').val();
var tgl_akhir = $('#tanggal2').val();
$.ajax({
url: '<?php echo base_url() . 'it_team/control_it/search' ?>',
type: 'POST',
data: {nomor: nomor,
nama: nama,
departement: departement,
tgl_awal: tgl_awal,
tgl_akhir: tgl_akhir},
dataType: 'json',
success: function(obj) {
//Please give me an idea
}
});
return false;
For testing, I try seearch and thank God, it gives me a success on json like this:
[{"id_request":"015","nama_user":"Dzil","departement":"IT","waktu_it_terima":"2015-06-19 02:51:05"},
{"id_request":"017","nama_user":"Dzil","departement":"IT","waktu_it_terima":"2015-06-19 13:32:46"}]
My problem is, the result of search form above will be displaying into a table in same page with the form above. You know, in tbody's table will be generate the object on based the return of json. I am newbie using json. The table looked like this
<div class="box-content" id="things_table2">
<table class="table table-bordered table-striped table-condensed" id="table1">
<thead>
<tr>
<th>No. </th>
<th>No Request</th>
<th>Nama user</th>
<th>Departement</th>
<th>Tanggal Request</th>
<th>Action</th>
</tr>
</thead>
<tbody id="hasil-pencarian">
// Result will be showing here
</tbody>
</table>
</div>
Any help it so appriciated.
Try like this (beware there are less fields in your json than in your table):
var data = [
{
'id_request': '015',
'nama_user': 'Dzil',
'departement': 'IT',
'waktu_it_terima': '2015-06-19 02:51:05'
},
{
'id_request': '017',
'nama_user': 'Dzil',
'departement': 'IT',
'waktu_it_terima': '2015-06-19 13:32:46'
}
];
var html = '';
for (var i = 0; i < data.length; i++) {
var td="";
for(var key in data[i]){
td+='<td>'+data[i][key]+'</td>';
}
html+="<tr>"+td+"</tr>";
}
$('#hasil-pencarian').html(html);
There is nothing special about json. Treat it like any js object, ie after parsing it.
Since its just an array of objects, you can iterate over it and do whatever.
var html = '';
$.each(data, function (index, element) {
// build your html
html += '<tr>;'
html += '<td>'+ index + 1 + '</td>';
html += '<td>'+ element.id_request + '</td>';
// same for other elements use `element.<key-name>`
// end tr after all the td's are done
html += '</tr>;'
});
Once you have iterated over all the elements, inject it in the dom.
$('.DOM-ELEMENT').html(html);