hi guys i have an issue on ajax. where ajax can't work to take the data of second rows.
This's code in model
function getdtbarang($barcode = FALSE) {
if ($barcode === FALSE)
{
$query = $this->db1->get('tblmstbarang');
return $query->result_array();
}
$query = $this->db1->get_where('tblmstbarang', array('barcode' => $barcode));
return $query->row_array();
}
This's code in controller:
function getdatabarang() {
$barcode = $this->input->post('barcode');
$data=$this->Mbarang->getdtbarang($barcode);
echo json_encode($data);
}
This's ajax code in view. NB:some code has updated
<script type="text/javascript">
function getdatabrg(barcode){
$('#barcode_2').each(function() {
var barcode =$('#barcode_2').val();
$.ajax({
type : "post",
data : "barcode=" +barcode,
url : "<?php echo base_url();?>index.php/master/barang/Cbarang/getdatabarang",
dataType:"json",
success: function(data){
for(var i in data)
{
var obj= data[i];
$("#barang_nama_2").val(obj.barang_nama);
$("#harga_beli_2").val(obj.harga_beli);
}}
});
});
}
$(document).ready(function() {
$('#barcode_2').keyup(function() {
getdatabrg();
});
});
</script>
<td><input type="text" class="form-control" id="barcode" name="barcode[]" value="<?php echo set_value('barcode['.$i.']') ;?>" onKeyUp="getValues()" ></td>
<td><input type="text" class="form-control" id="barang_nama" name="barang_nama[]" value="<?php echo set_value('barang_nama['.$i.']') ;?>" onKeyUp="getValues()" disabled></td>
<td><input type="text" class="form-control" id="harga_beli" name="harga_beli[]" value="<?php echo set_value('harga_beli['.$i.']');?>" onKeyUp="getValues()" disabled></td>
<td><input type="text" class="form-control" id="barcode_2" name="barcode[]" value="<?php $a=set_value('barcode[0]') ; echo $a;?>"></td>
<td><input type="text" class="form-control" id="barang_nama_2" name="barang_nama[]" value="<?php $a=set_value('barang_nama[0]') ; echo $a;?>" onKeyUp="getValues()" readonly></td>
<td><input type="text" class="form-control" id="harga_beli_2" name="harga_beli[]" value="<?php $a=set_value('harga_beli[0]'); echo $a;?>" onKeyUp="getValues()" readonly></td>
<td><input type="text" class="form-control" id="barcode_3" name="barcode[]" value="<?php echo $detail->barcode;?>"></td>
<td><input type="text" class="form-control" id="barang_nama_3" name="barang_nama[]" value="<?php echo $detail->barang_nama;?>" onKeyUp="getValues()" readonly></td>
<td><input type="text" class="form-control" id="harga_beli_3" name="harga_beli[]" value="<?php echo $detail->harga_beli;?>" onKeyUp="getValues()" readonly></td>
i hope getting solve for this problem. many thanks for all your response.
Like Zerfiryn mentioned : "You cannot use the same id for html elements. jQuery will only fetch the first element"
solutions: you can use the same class multiple times on html elements. Call not the id in your ajax but the class form-control.
So, replace $("#barcode") with $(".form-control")
writing an answer cause I can't place comments -.-
You have not constructed model correctly your model is directly outputting the data which so you will end up with the output something like
[{barang_name:"value"},{harga_beli:"value"}][{barang_name:"value"},{harga_beli:"value"}][{barang_name:"value"},{harga_beli:"value"}]...
which is not correct JSON
your should output correct JSON your output should be
[ [{barang_name:"value"},{harga_beli:"value"}], [{barang_name:"value"},{harga_beli:"value"}],.. ]
which is array of arrays
The simplest way to achieve this is
1 ) get the desired data from your model
function your_model_function()
{
$result = execute_query($sql);
$rows = array();
if($result->num_rows)
{
while($row = $result->fetch_row())
$rows[] = $row;
}
return $rows;
}
2) use json_encode to encode your whole data array in json format
$data = $this->model->your_model_func();
echo json_encode($data);
3) Use the JSON in your success callback function
//writing success function of ajax
function(data)
{
for(var i in data)
{
var row = data[i];
// to acccesss the data of row ie json object you can use . operator
console.log(row.key)
// manipulate dom content.
}
}
NOTE: i have written a pseudo code only you cannot directly copy paste it to get result it's just to clear your mind.
Related
Inside a table, I've created multiple forms using a loop based on data inside database.
Now I am not getting a way to implement a logic by which I wanted to identify of which form submit button is pressed so that I can update data accordingly in database.
What I did is putted an ID of that particular row as submit button id, but I am not getting how to put the same ID in javascript file (separate file) to fetch the field details, can someone help?
<?php
foreach ($get_subscribed_data as $filtered_items) { ?>
<tr>
<form id="<?php echo $filtered_items->id; ?>" method="POST">
<td><input type="text" class="form-group" id="user_account_name" value="<?php echo $filtered_items->user_account_name; ?>"><?php echo $filtered_items->user_account_name; ?></td>
<td><input type="text" class="form-group" id="user_project_name" value="<?php echo $filtered_items->user_project_name; ?>"><?php echo $filtered_items->user_project_name; ?></td>
<td><input type="text" class="form-group" id="start_date" value="<?php echo $filtered_items->start_date; ?>"><?php echo $filtered_items->start_date; ?></td>
<td><input type="text" class="form-group" id="due_date" value="<?php echo $filtered_items->due_date; ?>"><?php echo $filtered_items->due_date; ?></td>
<td><input type="submit" id="<?php echo $filtered_items->id; ?>" class="btn-primary btn-sm">Submit</button></td>
</tr></form>
<?php } ?>
UPDATE:
jQuery code I am using:
$(document).ready(function() {
$('.row-submit').on('click', e => {
alert('test');
e.preventDefault();
let $tr = $(e.target).closest('tr');
$.ajax({
type: "POST",
url: ajaxurl,
action: "send_modification_training_data",
data: {
user_account_name: $tr.find('.user_account_name').val(),
user_project_name: $tr.find('.user_project_name').val(),
start_date: $tr.find('.start_date').val(),
due_date: $tr.find('.due_date').val(),
},
success: response => {
console.log(response);
}
});
});
});
I'm presuming that you're using AJAX to send the form data, otherwise you wouldn't need to know which form was submit as the browser will collate the data for you.
To retrieve the data related to the clicked submit button you need to correct your HTML. Firstly, you need to remove all id attributes from the HTML you generate in the PHP loop as it will create duplicate values which is invalid, they must be unique. Change them to classes instead. Secondly, you cannot place a form element as a child of a tr.
In fact, given that you're using a table here you cannot use a form at all, as there's no way to make the HTML valid. You need to collate the input data on each row. To do this you can use closest() to find the tr related to the button and retrieve the input values using find(). Something like this:
<?php foreach ($get_subscribed_data as $filtered_items) { ?>
<tr>
<td>
<input type="text" class="form-group user_account_name" value="<?php echo $filtered_items->user_account_name; ?>">
<?php echo $filtered_items->user_account_name; ?>
</td>
<td>
<input type="text" class="form-group user_project_name" value="<?php echo $filtered_items->user_project_name; ?>">
<?php echo $filtered_items->user_project_name; ?>
</td>
<td>
<input type="text" class="form-group start_date" value="<?php echo $filtered_items->start_date; ?>">
<?php echo $filtered_items->start_date; ?>
</td>
<td>
<input type="text" class="form-group due_date" value="<?php echo $filtered_items->due_date; ?>">
<?php echo $filtered_items->due_date; ?>
</td>
<td>
<button type="button" class="btn-primary btn-sm row-submit">Submit</button>
</td>
</tr>
<?php } ?>
$('.row-submit').on('click', e => {
e.preventDefault();
let $tr = $(e.target).closest('tr');
$.ajax({
url: 'your-handler.php',
type: 'POST',
data: {
user_account_name: $tr.find('.user_account_name').val(),
user_project_name: $tr.find('.user_project_name').val(),
start_date: $tr.find('.start_date').val(),
due_date: $tr.find('.due_date').val(),
},
success: response => {
console.log(response);
}
});
});
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]);
I am creating an input field using foreach loop like this
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
$data is Array
(
[0] => Array
(
[asset_id] => abc-02
[asset_name] => Freezer
)
[1] => Array
(
[asset_id] => xyz-01
[asset_name] => Refrigerator
)
[2] => Array
(
[asset_id] => 300001
[asset_name] => Generator
)
)
and in javascript, I am trying to get the value using this code but it always alerts first value of the input.
<script type="text/javascript">
$(document).ready(function () {
var typename = $('#typename').val();
alert(typename);
});
</script>
i have to disable this input field when value is 'Generator'
Try:
$('[readonly].form-control').each(function(i,e) {
console.log($(e).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="2">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="3">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="4">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="5">
</td>
.val() called once will always produce only one value; .val() docs:
Get the current value of the first element in the set of matched elements .
HTML id attribute is supposed to be unique, try this instead.
<?php
$count = 0;
foreach($data as $key=>$val) {
?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename_<?php echo $count++; ?>" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
It'll produce different id attributes for each input, typename_0, typename_1, ..., typename_n, allowing you to for example:
$('[id^="typename_"]').each(function(i,e) {
console.log($(e).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename_0" type="text" value="1">
<input readonly class="form-control" name="model[]" id="typename_1" type="text" value="2">
<input readonly class="form-control" name="model[]" id="typename_2" type="text" value="3">
<input readonly class="form-control" name="model[]" id="typename_3" type="text" value="4">
<input readonly class="form-control" name="model[]" id="typename_4" type="text" value="5">
</td>
Where [id^="typename_"] is CSS attribute selector, matching all elements with an id attribute starting with typename_.
You should never use same id for several elements.
Update you code for debug, and you'll see that you have an array:
<script type="text/javascript">
$(document).ready(function () {
var typename = $('[name="model[]"]')
.toArray().map(e => e.value);
alert(JSON.stringify(typename));
});
</script>
You should update your php, to set different id for each element drawn in a cycle, i.e:
<?php $i=1;foreach($nomatter as $a) {?>
<input id="typename_<?=$i++?>">
<?php } ?>
So you'll be able to address eash input separately:
var typename = $('#typename_1').val();
Use class instead of duplicate id like this.
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control clsValue" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
And in jquery loop your class and get value using this instant..
$(document).ready(function () {
$( ".clsValue" ).each(function( index ) {
var typename = $(this).val();
alert(typename);
});
});
try this ,
this will call alert function for each input with form-control class
$(document).ready(function () {
$(".form-control").each(function(){
alert($(this).val());
})
});
Set class="typename" instead of id="typename":
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" class="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
You can get values like this:
<script type="text/javascript">
$(document).ready(function () {
var typename1 = $('.typename')[0].val();
var typename2 = $('.typename')[1].val();
alert(typename1);
});
</script>
there is a big mistake in your code, you can't use same id for multiple input fields, when the loop run multiple input fields will create with same id, you have to make the id dynamic, you can make the id dynamic by appending some unique value to the id each time you create an input field the use that id to fetch the data.
Please let me know if you need sample code.
pure js approach;
replace id with class;
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control typename" name="model[]" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
js
window.onload = alertTypeNames();
function alertTypeNames() {
document.getElementsByClassName('typename').map((inputTag) => {
alert(inputTag.value);
return true;
});
}
you fired with your id that's why it's fired only first element value.
this is how you can do that with your current code
$(document).ready(function () {
$('input[name="model[]"]').each(function(){
alert($(this).val());
});
});
However, it's highly recommended that you have to used unique id for each element otherwise used class to do what you want to.
The id attribute specifies a unique id for an HTML element it's not a good practice to use same ID more than once on a page, instead of ID attribute loop the class attribute in jquery.
<script type="text/javascript">
$(document).ready(function () {
$('.common-class').each(function() {
alert($(this).val());
});
});
</script>
<?php $incr_var = 1; ?>
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control common-class" name="model[]" id="typename<?php echo $incr_var ?>" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
Element id should be unique. And try it inside on event because dynamically adding elements will not grab ready state.
http://api.jquery.com/live/
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1 status">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
And in jquery
$(document).on('change','.status',function(){
var $status = $(this).val();
if($status == 'not_working'){
$(this).closest('tr').find('.reason').removeAttr('disabled');
}
});
reason is class you have to give which input field you want to disable
I have a php generated form with fields retrieved from DB and I want to do in time calculations before save again in DB. Im retrieving all values from inputs and the sum is working, but Im not able to insert the sum result into a inputbox(it doesnt have to be necessarily a inputbox).
What im doing wrong?
Inside a php while I have the fields:
<td><input type="text" onkeyup="calculate(<?php echo($row["usr_id"]);?>)" class="valor_<?php echo($row["usr_id"]);?>" title="Valor Pago" style="font-size:18px; text-align:center;" value="<?php echo(formata_moeda($row["pedprod_valorpago"]));?>" name="<?php echo($row["usr_id"]);?>" id="<?php echo($row["prod_id"]);?>" /></td>
The TOTAL input is like this
<th><input type="text" class="totalpago_<?php echo($row["usr_id"]); ?>" name="totalpago_<?php echo($row["usr_id"]); ?>" id="totalpago_<?php echo($row["usr_id"]); ?>" value="<? echo(formata_moeda($total_valorpago_cestante)); ?>" disabled="disabled"></th>
And the javascript function
function calculate(usrId) {
var total = 0;
var totalusr = 0;
$("input.valor_"+usrId).each(function() {
var price = parseFloat($(this).val().replace(',','.'));
totalusr += price;
//window.alert("Usuario: "+ usrId +" - Valor: "+ price);
});
$("input.totalpago_"+usrId).val(totalusr);
window.alert($("input.totalpago_"+usrId).val());
}
This alerts are just to test proposes.
I am trying to retrieve data from excel file and sending it to a php file to check if it exists in the database otherwise notify the user that the data is wrong.
HTML
<form name="trialInsert" id="trialInsert" action="trial_insert_excel.php" method="post">
<?php foreach( $data as $row ) { ?>
<tr class="item-row">
<td><input type="text" name="acc_code[]" id="acc_code[]" class="code" onchange="validate();" value="<?php echo ($row['acc_code']); ?>"/></td>
<td><input type="text" readonly name="int_code[]" id="int_code[]" value="<?php echo ( $row['int_code']); ?>"/></td>
<td><input type="text" readonly name="debit[]" id="debit[]" value="<?php echo ( $row['debit'] ); ?>"/></td>
<td><input type="text" readonly name="credit[]" id="credit[]" value="<?php echo( $row['credit'] ); ?>"/></td>
<td><input type="text" readonly name="debitOld[]" id="debitOld[]" value="<?php echo( $row['debitOld'] ); ?>"/></td>
<td><input type="text" readonly name="creditOld[]" id="creditOld[]" value="<?php echo($row['creditOld'] ); ?>"/></td>
</tr>
<?php } ?>
jQuery
$(document).ready(function(){
var code = $('.code').val()
jQuery.ajax({
type: 'POST',
source:'autocomplete.php',
data: 'acc_code='+ code,
cache: false,
success: function(response){
if(response > 0){
alert(code);
} else {
$('.code').addClass('errorClass');
}
}
});
});
function validate(){
var code = $('.code').val()
jQuery.ajax({
type: 'POST',
url: 'autocomplete.php',
data: 'acc_code='+ code,
cache: false,
success: function(response){
if(response > 0){
alert(code);
} else {
$('.code').addClass('errorClass');
}
}
});
}
PHP
$q=$_GET['q'];
$my_data=mysql_real_escape_string($q);
$mysqli=mysqli_connect('localhost','root','03300130','mydb') or die("Database Error");
$sql="SELECT acc_code,acc_desc,acc_type FROM charts WHERE acc_code LIKE '%$my_data%' ORDER BY acc_code";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error());
if($result) {
echo 1;
} else {
echo 0;
}
It looks like the return value is wrong or something,the textbox always goes red as if data entered is wrong even if it's not.
you are mixing mysqli_* and mysql_* commands.
quote from the documentation of mysql_real_escape_string():
Returns the escaped string, or FALSE on error.
Since you don't have a mysql_connect() call before it will most probably return false. You can check that with var_dump($my_data);.
You can use mysqli_real_escape_string() instead, alternatively you should look at prepared statements. Note: mysqli_real_escape_string() must also be called AFTER the mysqli_connect() call.