Please help,
I have the data that I loaded with ajax, but I am confused, how when I enter the item code, the data generated in json form, into the table
view
<div class="form-group col-md-4">
<label for="field-1" class="control-label">KODE RUNSHEET</label>
<input name="kd_runsheet[]" class="form-control" id="kode" type="text" placeholder="Masukan Kode Runsheet" style="" required="">
<input name="id_runsheet" id="id_runsheet" class="form-control" type="hidden" style="">
</div>
after searching I want to enter the json results in the table
<table class="table table-bordered" style="width: 100%; cellspacing: 0;">
<thead>
<tr>
<th>Kode Outbound</th>
<th>Kode Resi</th>
</tr>
</thead>
<tbody id="isinya">
</tbody>
</table>
// search by ajax
$(document).ready(function(){
$('#kode').on('input',function(){
var kode=$(this).val();
$.ajax({
type : "POST",
url : "<?php echo base_url('backend/history_status/caris')?>",
dataType : "JSON",
data : {kd_runsheet: kode},
cache:false,
success: function(data) {
jmlData = data.length;
tampung = "";
for (a = 0; a < jmlData; a++) {
tampung += "<tr>" +
"<td>" + (a + 1) + "</td>" +
"<td>" + data[a]["kd_runsheet"] + "</td>" +
"<tr/>";
}
$("tbody")[0].innerHTML += tampung;
}
});
return false;
});
});
Result Json
[
{"id_runsheet":"6","kd_runsheet":"RUNSHEET-0000-0003"},
{"id_runsheet":"6","kd_runsheet":"RUNSHEET-0000-0003"}
]
Model
public function caridb($kode){
$query = $this->db->query("SELECT runsheet.id_runsheet,kd_runsheet FROM runsheet
INNER JOIN runsheet_detail ON runsheet.id_runsheet=runsheet_detail.id_runsheet WHERE kd_runsheet ='$kode'");
return $query->result();
}
Controller
public function caris(){
$id=$this->input->post('kd_runsheet');
$data=$this->M_history_status->caridb($id);
echo json_encode($data);
}
Try something like this. Your markup should be inside a loop.
success: function(data){
var markup = "<tr>
<td><input type='text'></td>
</tr>";
$("#isinya").append(markup);
}
You are getting JSON Object's array
Seperate each JSON Object using loop and add it to table:
success: function(data){
for(i=0;i<data.length;i++){
var row="<tr><td>"+data[i].id_runsheet+"</td><td>"+data[i].kd_runsheet+"</td></tr>";
$("#isinya").append(row); //Adding rows in <tbody>
}
}
Related
From the database, I have a dynamic table like this:
<table>
<?php
$query = ....;
foreach ($query as $row) {
echo '<tr>';
echo '<td>' . ' <span class="bName">' . $row['brand_name'] . '</span>'.
'<input name="product_id" type="number" value="' . $row['product_id'] . '">'.
'<input name="company_id[]" type="number" value="' . $row['company_id'] . '">'.
'<button name="exchange" type="button">Click Me!</button></td>';
echo '</td>';
echo '</tr>';
}
?>
</table>
It returns say 4 rows with brand_name inside the <span> and product_id inside an <input>. The exchange button on click calls an ajax request that query another random brand_name and returns the query as JSON like this:
{product_id: '2206', brand_name: 'New name', company_id: '234' }
The script for ajax is
<script>
$(document).ready(function() {
$('button[name="exchange"]').click(function() {
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
$('.bName').html(data.brand_name); // Problem is here
$('.company_id').html(data.company_id); // and here
console.log(data);
},
});
});
});
</script>
My target is to change the brand_name inside class bName and company_id value with the new values from ajax response for that specific row. But my problem is it changes all the spans with bName class and all the inputs with class company_id. What should be the best approach to change the specific row of that table from the ajax data?
Store a reference to the cell that the button that was actually clicked exists in so you can find within that cell the specific elements.
Also note that the company_id value is in an input thaat you ned to use val() on and you need to give it a class name
$('button[name="exchange"]').click(function() {
// cell this button instance is in
const $cell = $(this).closest('td');
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
$cell.find('.bName').html(data.brand_name); // Problem is here
$cell.find('.company_id').val(data.company_id); // and here
console.log(data);
},
});
});
Unable to test using AJAX but perhaps this might help. Use the event of the click function to find the parentNode and from that use querySelector to target the particular elements in the table row.
$(document).ready(function() {
$('button[name="exchange"]').click(function(e) {
let tr=e.target.parentNode;
let span=tr.querySelector('span.bName');
let pid=tr.querySelector('input[name="product_id"]');
let cid=tr.querySelector('input[name="company_id[]"]');
console.info( span.textContent, cid.value, pid.value)
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
span.textContent=data.brand_name;
cid.value=data.company_id;
pid.value=data.product_id;
},
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<span class="bName">Womble</span>
<input name="product_id" type="number" value="23">
<input name="company_id[]" type="number" value="88">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
<tr>
<td>
<span class="bName">Bagpuss</span>
<input name="product_id" type="number" value="39">
<input name="company_id[]" type="number" value="12">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
<tr>
<td>
<span class="bName">Clanger</span>
<input name="product_id" type="number" value="47">
<input name="company_id[]" type="number" value="91">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
</table>
I have created dynamic rows with type(select),name(text),unit(select), I was writing the code for on change type's select.
But when I change the value from type field it had load the value into current row name field and load option dynamically into current unit select field,
Loading value into active rows is working fine, but loading options into select unit is not.
My code is given below
$(document).on('change', '.raw', function () {
// var r = this.val();
if ($(this).val() != 0) {
var t = $(this).parents('tr').find(".raw :selected").text();
$(this).parents('tr').find(".name").val(t);
where I need help is given below
$(this).parents('tr').find(".amount").html(data); -> here i need help
// $(".amount").html(data); ->this working fine but change all the select value
Thanks in advance.
here my full coding for my table
<table id="addingtable" class="table table-bordered">
<tr>
<th>Raw Master</th>
<th>Name</th>
<th>Display</th>
<th>Value</th>
<th>Unit</th>
<th>Delete</th>
</tr>
<tr>
<td><select name='rawmaster[]' class = 'form-control raw' required><option>Select</option><?php echo rawmaster_item($conn,$type); ?><option value="0">None</option></select></td>
<td><input type='text' name='name[]' placeholder="Name" class = 'form-control name' required /></td>
<td><select name='des[]' class = 'form-control' required><option>Select</option><option Value = 'y'>Yes</option><option Value = 'n'>No</option></select></td>
<td><input type='text' name='value[]' placeholder="Value" class = 'form-control' required /></td>
<td><select name='amount[]' class = 'form-control amount' required><option>Select</option><?php echo $output2; ?></select></td>
<td><button type='button' class='btn btn-icon btn-danger remove'><i class='feather icon-trash-2'></i></button></td>
</tr>
my jquery for adding rows
$(document).on("click", ".addrows", function (event) {
{
// var planid = $("#plan_id").val();
// alert(planid);
var html = '';
html += "<tr>";
html += "<td><select name='rawmaster[]' class = 'form-control raw'><option>Select</option><?php echo rawmaster_item($conn,$type); ?><option value = '0'>None</option></select></td>";
html += "<td><input type='text' name='name[]' placeholder='Name' class = 'form-control name' /></td>";
html += "<td><select name='des[]' class = 'form-control'><option>Select</option><option Value = 'y'>Yes</option><option Value = 'n'>No</option></select></td>";
html += "<td><input type='text' name='value[]' placeholder='Value' class = 'form-control' /></td>";
html += " <td><select name='amount[] amount' class = 'form-control amount' required><option>Select</option><?php echo $output2; ?></select></td>";
html += "<td><button type='button' class='btn btn-icon btn-danger remove'><i class='feather icon-trash-2'></i></button></td>";
html += "</tr>";
$("#addingtable").append(html);
}
});
my jquery for onchange select values
$(document).on('change', '.raw', function () {
// var r = this.val();
if ($(this).val() != 0) {
var t = $(this).parents('tr').find(".raw :selected").text();
$(this).parents('tr').find(".name").val(t);
$(this).parents('tr').find(".name").attr("readonly", "TRUE");
var r = $(this).parents('tr').find(".raw").val();
// alert(r);
$.ajax({
url:"plandetails_getunit.php",
method:"POST",
data:"id="+r,
success:function(data)
{
if(data)
{
$(this).parents('tr').find(".amount").html(data); => need help here
// $(".amount").html(data);
}
}
});
}
else{
$(this).parents('tr').find(".name").val('');
$(this).parents('tr').find(".name").removeAttr("readonly");
var r = $("#ptype").val();
$.ajax({
url:"plandetails_getunit1.php",
method:"POST",
data:"id="+r,
success:function(data)
{
if(data)
{
// $(".amount").html(data);
$(this).parents('tr').find(".amount").val(); =>here remains work gud
}
}
});
}
});
I might be wrong but I think you need to set the context on the ajax request otherwise this will reference a different context (callback), adding context:this like this:
$.ajax({
url:"plandetails_getunit.php",
method:"POST",
data:"id="+r,
context:this,
success:function(data)
{
I have a form where I am selecting a product. On the basis of the selected product, I want to update the rest of the fields in the form.
The Form display with select option
On selecting the product name, I want rest of the details of the form to fill up from the database using php.
Here is the code for the table created.
<table id="productTable" class="table-c">
<tr>
<th class="text-center" style="width: 5%;">SR No.</th>
<th class="text-center" style="width: 45%">DESCRIPTION</th>
<th class="text-center" style="width: 10%">HSN/SAC</th>
<th class="text-center" style="width: 10%">QTY IN-HAND</th>
<th class="text-center" style="width: 10%">ENTER OUTWARD QTY</th>
<th class="text-center" style="width: 5%">Delete</th>
</tr>
<tr style="text-align: center;" id="products">
<?php $j=0; $j++; ?>
<td><?php echo $j; ?></td>
<td><select class="form-control" name="code" id="productID" style="width: 429px;">
<?php
$sql = "SELECT * FROM `product`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option id='".$row['code']."' value='".$row['pname']."'>".$row['pname']."</option>";
}
} else {
echo "0 results";
}
?>
</select>
</td>
<td><input type="number" name="hsnNo" id="hsnNo" readonly></td>
<td><input type="number" name="qty" id="qty" readonly></td>
<td class="coljoin"><input type="number" format="2" name="amount"></td>
<td>
<span class="fa fa-trash"></span>
</td>
</tr>
</table>
How should I do this?
This is PHP Code:-
<form>
<select name="customer" id="customer_id">
<option value="">-- Select customer Name -- </option>
<option value="1">John</option>
<option value="2">Smith</option>
</select>
Address: <input name="add" type="text" value="">
Mobile: <input name="mobile" type="text" value="">
EMail-Id:<input name="email" type="text" value="">
</form>
This is JS Code:-
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#customer_id").change(function() {
var id = $(this).val();
var dataString = 'cid='+id;
//alert(dataString);
$.ajax({
url: 'dataAjax.php',
type: 'post',
data: dataString,
success: function(response) {
// Parse the jSON that is returned
var Vals = JSON.stringify(response);
// These are the inputs that will populate
$("input[name='add']").val(Vals.add);
$("input[name='mobile']").val(Vals.mobile);
$("input[name='email']").val(Vals.email);
}
});
});
});
</script>
This is other PHP File Code:-
<?php
// This is where you would do any database call
if(!empty($_POST)) {
// Send back a jSON array via echo
echo json_encode(array("add"=>'India',"mobile"=>'1234567890','email'=>'demo#demo.com'));
}
?>
using product id use ajax & call the get_product_details(id) & in get product convert response array in json & echo it .in ajax, response data you have to parse in json... then set you required field.. (add require js)
**Ajax Call :**
$(document).on('change','your_dropdown_filed_id',function()
{
var product_id = $(this).val();
//Ajax call
$.ajax({
method: "POST",
url: "/get_product_details", //your php file function path
data: { product_id: product_id}
}).done(function( response ) {
alert( "Data Saved: " + response );
var obj = JSON.parse(response);
//obj hold all values
alert(obj.qty);
alert(obj.hsn);
$('#hsn_id').val(obj.hsn);
$('#qty_id').val(obj.qty);
});
});
**product.php**
function get_product_details(product_id)
{
//Get product details in associative array format
echo json_encode($product_details);
}
Once the product is selected execute ajax request and get data from the database with respective of the selected product.
JAVASCRIPT CODE :
$('#products').change(function(){
$.ajax({
url: 'your php code page name which returns product details.php?product_id'+$('#products').val(),
type: 'post',
success: function(response) {
var obj = JSON.parse(response);
$("#hsn_sac").val(obj.hsn_sac); // hsn or sac values
$("#qty_in_hand").val(obj.qty_in_hand); // qty_in_hand values
}
}});
});
PHP CODE :
<?php
// first connect database and then fire the query to get product details
$connection = mysql_connect("your database host name","database username","database password","database name");
$result = mysql_query("your query");
while ($row = mysql_fetch_array($result)) {
// get data and store in array
}
mysql_close($connection); // close connection
echo json_encode(database result); // encode database result so that it will available to ajax request and assign back to view
exit;
?>
I have created a dynamic table using jquery as follows:
$.ajax({
data : data,
type : "get",
url : url,
dataType : "json",
error : function(resp){
alert("Error !!");
},
success : function(resp){
table = '';
$.each(resp,function(indx,obj){
table += '<tr>';
table += '<td>'+parseInt(indx+1)+'</td>';
table += '<td>'+'<input type="text" value="'+obj.ServiceDetail.service_code+'">'+'</td>';
table += '<td>'+'<input type="text" value="'+obj.ServiceDetail.name+'">'+'</td>';
table += '<td>'+'<input type="text" value="'+obj.ServicePrice.discount_price+'">'+'</td>';
table += '</tr>';
});
$("tbody#sevice_table_body").append(table);
}
});
and a button :
<input type="button" class = "btn btn-success btn-sm" value="submit" >
now i want to get all input value in a array by click submit button so that can be inserted in a database table using jquery ajax.
You can use this code for cycling the input and add them to an array
var arrayOfVar = []
$.each($("input[type='text']"),function(indx,obj){
arrayOfVar.push($(obj).val());
});
You can use .serializeArray() it Encode elements as an array of names and values.
Find below fiddle for more info
$(function() {
var data = $("#tbl2 :input").serializeArray(); // For converting it to array
//If needed below code is converting it to object
var obj = {};
for (var i = 0, l = data.length; i < l; i++) {
obj[data[i].name] = data[i].value;
}
console.log(data); // Print Array in Console
console.log(obj);// Print Object in Console
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tbl2">
<tr>
<td>
<input type="text" name="tb3" value="1" />
</td>
</tr>
<tr>
<td>
<input type="text" name="tb4" value="2" />
</td>
</tr>
<tr>
<td>
<input type="text" name="tb5" value="3" />
</td>
</tr>
<tr>
<td>
<input type="text" name="tb6" value="4" />
</td>
</tr>
</table>
Add attribute name with name and array .
$.ajax({
data : data,
type : "get",
url : url,
dataType : "json",
error : function(resp){
alert("Error !!");
},
success : function(resp){
table = '';
$.each(resp,function(indx,obj){
table += '<tr>';
table += '<td>'+parseInt(indx+1)+'</td>';
table += '<td>'+'<input type="text" name="service_code[]" value="'+obj.ServiceDetail.service_code+'">'+'</td>';
table += '<td>'+'<input type="text" name="name[]" value="'+obj.ServiceDetail.name+'">'+'</td>';
table += '<td>'+'<input type="text" name="discount_price[]" value="'+obj.ServicePrice.discount_price+'">'+'</td>';
table += '</tr>';
});
$("tbody#sevice_table_body").append(table);
}
});
Here you go with a solution
var inputData = [];
$('button[value="submit"]').click(function(){
$('input[type="text"]).each(function(){
inputData.push($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hope this will help you.
In your table section, add name attribute like this:
$.each(resp,function(indx,obj){
table += '<tr>';
table += '<td>'+parseInt(indx+1)+'</td>';
table += '<td>'+'<input name="services[' + indx + '][code]" type="text" value="'+obj.ServiceDetail.service_code+'">'+'</td>';
table += '<td>'+'<input name="services[' + indx + '][name]" type="text" value="'+obj.ServiceDetail.name+'">'+'</td>';
table += '<td>'+'<input name="services[' + indx + '][price]" type="text" name="service[' + indx + '][price]" value="'+obj.ServicePrice.discount_price+'">'+'</td>';
table += '</tr>';
});
This will produce names like services[0][code], services[0][name], etc.,
Now you can access the input values as an array in PHP:
$services = $_POST['services'];
foreach ($services as $index => $service) {
$code = $service['code'];
$name = $service['name'];
$price = $service['price'];
echo "$index : $code, $name, $price \n";
}
I need a help to adding a table row after inserting with PHP/MySQL. I don't know what else to do.
FYI i'm able to insert with $.ajax and my select are working correctly. I need a help on how to retrieve this information to the table row.
agenda.php
<form class="form-inline" id="form-agenda">
<input type="text" name="data" class="input-big datepicker" placeholder="Data">
<input type="text" name="local" class="input-big" placeholder="Local">
<input type="text" name="cidade" class="input-big" placeholder="Cidade">
<button type="submit" name="submit" class="btn btn-primary">Gravar</button>
</form>
<table class="table table-hover">
<thead>
<tr>
<th>Data</th>
<th>Local</th>
<th>Cidade</th>
</tr>
</thead>
<tbody id="teste">
<?php
$agendaDAO = new AgendaDAO();
foreach($agendaDAO->select() as $row){
echo '<tr>'.
'<td>'.$row['data'].'</td>'.
'<td>'.utf8_encode($row['local']).'</td>'.
'<td>'.$row['cidade'].'</td>'.
'<td><i class=icon-edit></i> <i class=icon-remove></td>'.
'</tr>';
}
?>
</tbody>
</table>
agenda.js
$('#form-agenda').submit(function(){
var fields = $(this).serialize();
$.ajax({
url: 'ajax-agenda.php',
type: 'POST',
data: fields,
dataType: 'text',
beforeSend: function(){
$('#loading-indicator').css({display: 'block'});
},
complete: function(){
$('#loading-indicator').css({display: 'none'});
},
success: function(data) {
$('#teste').prepend(data);
$('#teste tr:first').slideDown('slow');
}
});
$(this).trigger('reset');
return false;
});
ajax-agenda.php
<?php
include('util/config.php');
$data = $_POST['data_submit'];
$local = utf8_decode($_POST['local']);
$cidade = utf8_decode($_POST['cidade']);
$agenda = new Agenda($data, $local, $cidade);
$agendaDAO = new AgendaDAO();
$agendaDAO->add($agenda);
foreach($agendaDAO->select("SELECT * FROM agenda ORDER BY id DESC LIMIT 1") as $rowA){
echo '<tr><td>'.$rowA['data'].'</td><td>'.utf8_encode($rowA['local']).'</td><td>'.$rowA['cidade'].'</td><td><i class=icon-edit></i> <i class=icon-remove></td></tr>';
}
?>
Try changing the dataType: 'text' to dataType: 'html'.