Retrive data using PHP and Ajax - javascript

Here I am trying to fetch data from Mysql database using PHP and Ajax. My problem is, when I type the Test ID on test_id text box, just it immediatetly shows the Test Name according to the Test ID on test_name text box.
Here I used the function called checkname. In console just it show the Test Name but does not show in the test_name text box.
Here is the HTML code.
<table class="table table-hover table-white">
<thead>
<tr>
<th class="col-sm-1">Test ID</th>
<th class="col-md-6">Test Name</th>
<th style="width:100px;">Amount</th>
<th> Action</th>
</tr>
</thead>
<tbody id="rows">
<tr>
<td> <input class="form-control" type="text" style="width:200px" id="test_id[]" onblur="checkname();" onkeyup="checkname();" onchange="checkname();"> </td>
<td> <input type="text" style="width:300px" class="form-control text-right form-amt" readonly="" id="test_name[]" > </td>
<td> <input type="text" style="min-width:100px" class="form-control text-right form-amt" readonly="" id="amount[]"> </td>
<td><center> <i class="fa fa-plus"></i> </center> </td>
</tr>
</tbody>
</table>
Here is the Ajax code;
<script>
function checkname()
{
var test_id = document.getElementById("test_id[]").value;
$.ajax({
type: 'post',
url: "adminquery/fetch_test_name.php", // request file the 'check_email.php'
data: {'test_id': test_id, },
success: function (data) {
$("#test_name[]").html(data);
}
});
}
</script>
Here is the PHP code
<?php
include('../auth/dbconnection.php');
$output='';
$sql="SELECT * from testings where test_id='".$_POST['test_id']."'";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($result)){
$name= $row["testing_name"];
$output.=' <input type="text" readonly="" id="test_name[]" value="'.$name.' "> '.$name.' ';
}
echo $output;
?>
Anyone could help me may highly appreciated.

First lose the brackets in the id.
<input id="test_name" type="text" value="other" />
Then use .val() instead of .html()
$("#test_name").val("something")

Related

Create an array of text fields using data from a database and use the values from the fields to do calculate

I would like to fetch items and item prices from database and use it to create an array of input fields for quantity and amount. Then use Jquery to automatically fetch the values of quantity as I type and multiply it by the price to display the amount in the amounts field for each item.
At the same time, the totals value (which is sum of all amounts) should also be displayed.
This is restricted to only the items that have been checked (selected).
<table class="form" id='tab1e'>
<tr>
<th> </th>
<th style="text-align: left;">Material Name</th>
<th style="text-align: center;">Quantity</th>
<th style="text-align: center;">Unit Price</th>
<th style="text-align: center;">Amount</th>
<th style="text-align: center;">Currency</th>
</tr>
<?php
foreach($database_result as $value){
?>
<tr>
<td>
<input type="checkbox" name="checkboxes[]" value="<?php echo $row['price']."".$row['item_name'] ?>">
</td>
<td style="width: 150px">
<?php echo $row['item_name'] ?>
</td>
<td>
<input name="qnty[]" id="qnty">
</td>
<td>
<input name="price" class="form-control" value="<?php echo $row['price']) ?>" id="price">
</td>
<td>
<input name="total_amount[]" class="text form-control" readonly="readonly" id="total_amount">
</td>
</tr>
<?php } ?>
<tr>
<td>Total Amount</td>
<td style="text-align: right;" id="totalpop"></td>
<td></td>
</tr>
</table>
First thing is the inputs should have different ids.
Now, you can use onchange event to call a function when input value changes. You can use plain javascript for that. Here's an example:
<html>
<body>
<script>
function o(id) {
return document.getElementById(id);
}
function updatePrice(id) {
if (!o('qnty'+id).value.match(/^[0-9]+$/)) {
alert('Invalid quantity');
o('total'+id).value = '0';
return false;
}
// Similar check for price
o('total'+id).value = parseInt(o('qnty'+id).value) * parseFloat(o('price'+id).value);
}
</script>
<input name="qnty[]" onchange="updatePrice('1')" id="qnty1">
<input name="price" value="1" onchange="updatePrice('1')" id="price1">
<input name="total_amount[]" id="total1">
</body>
</html>
The 1 corresponds to row number, so you would need to change your PHP code so it has a row number (can be just a simple $i=1; before the loop and $i++; in the end of every loop iteration).

how to fetch the data from database in dynamically created table using codeiginter

<table class="table table-bordered table-striped table-xxs" id="tb3" name="tb3">
<thead>
<tr>
<th></th>
<th>Product Code</th>
<th>Product Name</th>
<th>Qty</th>
<th>Rate</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr >
<td><a href='javascript:void(0);' class='remove3'><span class='glyphicon glyphicon-remove'></span></a></td>
<td>
<input style="width:80px" type="text" id="Product_Code" class="form-control input-xs Product_Code " onkeyup="fetch()" value="<?php echo $r->Product_Code; ?>" name="Product_Code[]" required></td>
<td ><input style="width:300px" type="text" id="Product_Name" class="form-control input-xs" value="<?php echo $r->Prdtname; ?>" name = "Prdtname[]" value=""> </td>
<td><input style="width:80px" type="text" id="Qty" class="form-control input-xs" value="<?php echo $r->Qty; ?>" name="Qty[]" required></td>
<td><input style="width:100px" type="text" id="Rate" class="form-control input-xs" value="<?php echo $r->rate; ?>" name="rate[]" required></td>
<td><input style="width:150px" type="text" id="Value" class="form-control input-xs" value="<?php echo $r->amount; ?>" name="amount[]" ></td>
<th><span class="glyphicon glyphicon-plus"></span></th>
</tr>
</tbody>
</table>
this table code....
<script>
$(document).ready(function (){
$('#addMore3').on('click', function() {
var data = $("#tb3 tr:eq(1)").clone(true).appendTo("#tb3");
data.find("input").val('');
});
$(document).on('click', '.remove3', function() {
var trIndex = $(this).closest("tr").index();
if(trIndex>0) {
$(this).closest("tr").remove();
} else {
alert("Sorry!! Can't remove first row!");
}
});
});
</script>
this is javascript code for creating table by clicking "+" event.
My prblm is how to fetch data from database display in this automatic table..
You should be able to do this using ajax call.
As you are using codeigniter -
View : Write your ajax and table generation code.
Controller: get the ajax request and pass it to modal.
Modal: get the data from database.
you should return array of object to view and then just parse the data and generate table.
If you dont want to write the table code and ajax then you can use datatable plugin.

Add Row Button adds PHP cell with Select2 option

Sorry about the Q form but I couldn't find a better way to explain it.
I have a view table that have drop down form that retrieves its options from the DB to be inserted, and it have an add button to add new row to insert.
But the drop down works on Select2 forms, and it's included in the table, so every time I try to add new row it gives it the same id as the previous one and that conflicts with the JS for the Select2 as it needs to get special id for every drop down I made with it.
here's the table and the add button code
<div class="row">
<div class="table-responsive">
<table class="table table-bordered" id="tab_logic">
<thead>
<tr>
<th>Brand Name</th>
<th>Item Name</th>
<th>Model Number</th>
<th class="col-md-2">Item Description</th>
<th>Part Number</th>
<th>Unit</th>
<th class="col-md-1">QTY</th>
<th class="col-md-1">Unit Price (SR)</th>
<th class="col-md-1">Total Price (SR)</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<strong>Record</strong>
</td>
<td>
<strong>Record</strong>
</td>
<td>
<strong>Record</strong>
</td>
<td>
<div class="form-group">
<?php
$query = $con->query("SELECT products_itemDescription FROM pruc_products"); // Run your query --> For Item Desc.
echo '<select class="form-control" id="DescriptionS2forms" name="itemDescription">'; // Open your drop down box
echo '<option value="" selected="selected" disabled></option>'; //Empty Value for VALIDATION
// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$row['products_itemDescription'].'">'.$row['products_itemDescription'].'</option>';
}
echo '</select>';// Close your drop down box
?>
</div>
</td>
<td>
<strong>Record</strong>
</td>
<td>
<strong>Record</strong>
</td>
<td>
<div>
<input class="form-control" type="number" name="requestQTY" required>
</div>
</td>
<td>
<div>
<input class="form-control" type="number" name="requestUnit" step="0.01" min="0.01" max="1000000" required>
</div>
</td>
<td>
<strong>Record</strong>
</td>
<td class="col-md-1" id="deleteBtn">
<a class="btn btn-default deleteBtn">Delete</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- End of 3rd Row -->
<div class="row">
<a id="add_row" class="btn btn-default pull-right">Add</a>
</div>
And the JS for the add button and select2 function:
$(document).ready(function() {
var i = 0;
$("#add_row").click(function() {
var x = '[{<td><strong>Record</strong></td> <td><strong>Record</strong></td> <td><strong>Record</strong></td> <td><div class="form-group"> <?php $query = $con->query('SELECT products_itemDescription FROM pruc_products'); echo '<select class="form-control" id=DescriptionS2forms'.(i+1).'" name="itemDescription">'; echo '<option value="" selected="selected" disabled></option>'; while($row = $query->fetch(PDO::FETCH_ASSOC)) {echo '<option value="'.$row['products_itemDescription'].'">'.$row['products_itemDescription'].'</option>';} echo '</select>'; ?> </div></td> <td><strong>Record</strong></td> <td><strong>Record</strong></td> <td><div><input class="form-control" type="number" name="requestQTY" required></div></td> <td><div><input class="form-control" type="number" name="requestUnit" step="0.01" min="0.01" max="1000000" required></div></td> <td><strong>Record</strong></td> <td class="col-md-1" id="deleteBtn"> <a class="btn btn-default deleteBtn">Delete</a></td>}]';
$('#tab_logic').append('<tr id="addr' + (i + 1) + '">' + x + '</tr>');
i++;
});
$("#SupplierS2forms, #ProjectS2forms, #WHS2forms, #DescriptionS2forms").select2(); });
in the PHP option it gives the id="DescriptionS2forms"
so I need to add a number for the id so I can use it in the Select2 Function as it doesn't accept same id
Example
id="DescriptionS2forms1" AND id="DescriptionS2forms2"

Checkbox in a dynamic table with dynamic input fields

I have a table with dynamic values and hidden input fields and dynamic checkbox. Checkboxes have same class names. When i click on a particular checkbox i want the input values from that particluar row should be sent to ajax.
Below is the code for dynamic table,
<table id="table">
<thead>
<tr>
<th >Sl.no</th>
<th >Owner Name</th>
<th >Contact Number</th>
<th class="text-center" data-title="Action">Action</th>
</tr>
</thead>
<tbody id="responsive-table-body">
<?php
$owner=mysql_query("select id,tmp_id,name,phone,activate from pgowner where active='1'");
if(mysql_num_rows($owner)){
$i=0;
while($owner1=mysql_fetch_array($owner)){
$id=$owner1['tmp_id'];
?>
<tr>
<td><span class="label label-default"><?php echo ++$i; ?></span></td>
<td>
<a href='viewprofile?id=<?php echo $id; ?>' target='_blank' style='color:blue;text-decoration:underline;'><?php echo $owner1['name']; ?></a>
<input type="hidden" name="ownerid" value="<?php echo $owner1['tmp_id']; ?>" id="ownerid" />
</td>
<td>
<?php echo $owner1['phone']; ?>
</td>
<td>
<input type="checkbox" name="activate[]" class="activate" id="activate" />
</td>
</tr>
<?php } }
?>
</tbody>
</table>
Here's the ajax code to fetch the value from the row in which checkbox is checked.
<script type="text/javascript">
$(document).ready(function(){
$('#activate').click(function(){
var ownerid=$('#ownerid').val();
var myonoffswitch=$('#activate').val();
if ($("#activate:checked").length == 0)
{
var a='0';
}
else
{
var a="1";
}
$.ajax({
type: "POST",
url: "profileactivation",
data: "value="+a +"&ownerid="+ownerid,
success: function(html){
alert("Successfully Done");
}
});
});
});
</script>
I am not able to fetch the input value from the row in which checkbox is checked. Please help.
Generated HTML looks like this,
<table id="table" >
<thead>
<tr>
<th >Sl.no</th>
<th >Owner Name</th>
<th >Contact Number</th>
<th >Action</th>
</tr>
</thead>
<tbody id="responsive-table-body">
<tr >
<td ><span class="label label-default">1</span></td>
<td>
Name1
<input type="hidden" name="ownerid" value="EdXzrq" id="ownerid">
</td>
<td>
9731269342
</td>
<td>
<input type="checkbox" name="activate[]" class="activate" id="activate">
</td>
</tr>
<tr >
<td ><span class="label label-default">2</span></td>
<td>
Name2
<input type="hidden" name="ownerid" value="RowMpg" id="ownerid">
</td>
<td>
7760807087
</td>
<td>
<input type="checkbox" name="activate[]" class="activate" id="activate">
</td>
</tr>
</tbody>
</table>
There are multiple issues.
Since you have the controls in a loop, using ID will create multiple elements with same ID which is invalid, instead use class or other selectors like attribute selector to select elements.
<input type="checkbox" name="activate[]" class="activate" />
<input type="hidden" name="ownerid" value="<?php echo $owner1['tmp_id']; ?>" />
then use a class selector to register the click hanlder and then find the owner id in the same row as given below
$(document).ready(function() {
$('.activate').click(function() {
var ownerid = $(this).closest('tr').find('input[name="ownerid"]').val();
var a = this.checked ? 1 : 0;
$.ajax({
type: "POST",
url: "profileactivation",
data: {
value: a,
ownerid: ownerid
},
success: function(html) {
alert("Successfully Done");
}
});
});
});

Pre-populating form fields with the row data by clicking on the row

Please help if you are seeing this.I want to pre-populate the form-field with row data after clicking on the same row.
SIMILAR TO THIS DEMO:http://jsbin.com/qavugo/2/edit?html,js,output
Problem is faced now. fillForm() function is OK(AS SHOWN IN THE DEMO inside the scripts) in order to populate the form field with row data.HOW DO I GET ROW DATA? But as I am populating the table using jsp like this
<table class="data-table" id="test" border="1">
<tr>
<td>Student ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>Year Level</td>
</tr>
<c:foreach items="${allStudents}" var="stud">
<tr>
<td>${stud.studentId}</td>
<td>${stud.firstname}</td>
<td>${stud.lastname}</td>
<td>${stud.yearLevel}</td>
</tr>
</c:foreach>
</table>
Which makes it more difficult for me for getting the rowData than what is showed in the DEMO.
MY FORM
<form name="frm" class="data-form" action="./StudentServlet" method="POST" onsubmit="return validateForm()">
<tr>
<td>
<label>Student ID --></label><input type="text" name="studentId" value="${student.studentId}" />
</td>
<td>
<label>First Name --></label><input type="text" name="firstname" value="${student.firstname}" />
</td>
<td>
<label>Last Name --></label>
<input type="text" name="lastname" value="${student.lastname}" />
</td>
<td>
<label>Year Level --></label><input type="text" name="yearLevel" value="${student.yearLevel}" />
</td>
</tr>
</form>
THE SCRIPTS
$(function() {
// I am not using dummy data here.
var rowData = [
// how and what should go here.Please help
];
row.on("click", function() {
fillForm(rowData);
});
return row;
});
$(".data-table").append(rows);
function fillForm(rowData) {
var form = $(".data-form");
form.find("input.value1").val(rowData.value1);
form.find("input.value2").val(rowData.value2);
form.find("input.value3").val(rowData.value3);
form.find("input.value4").val(rowData.value4);
}
I am updating the records like this
<table>
<tr>
<td colspan="5">
<input type="submit" name="action" value="Add" />
<input type="submit" name="action" value="Edit" />
<input type="submit" name="action" value="Delete" />
<input type="submit" name="action" value=Refresh />
</td>
</tr>
</table>
I am getting an error after clicking the/add/edit/delete button
Warning: StandardWrapperValve[StudentServlet]: Servlet.service() for servlet StudentServlet threw exception
java.lang.NumberFormatException: For input string: " "
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at com.joseph.controller.StudentServlet.processRequest(StudentServlet.java:35)
at com.joseph.controller.StudentServlet.doPost(StudentServlet.java:99)
That demo looks way too complicated for the task at hand. There's really no need to work with class references. You could simplify your approach by doing the following:
HTML:
<h1>Student Info:</h1>
<form class="data-form">
<label>Student ID
<input type="text" />
</label>
<label>First Name
<input type="text" />
</label>
<label>Last Name
<input type="text" />
</label>
<label>Year Level
<input type="text" />
</label>
</form>
<table class="data-table" id="test">
<thead>
<tr>
<th>Student ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Year Level</th>
</tr>
</thead>
<tr>
<td>1</td>
<td>Frank</td>
<td>Sinatra</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>Miles</td>
<td>Davis</td>
<td>4</td>
</tr>
<tr>
<td>3</td>
<td>Tom</td>
<td>Waits</td>
<td>6</td>
</tr>
</table>
JS:
$(document).ready(function () {
$("td", this).on("click", function () {
var tds = $(this).parents("tr").find("td");
$.each(tds, function (i, v) {
$($(".data-form input")[i]).val($(v).text());
});
});
});
The only condition for this to work is that the input order in the form needs to match the column order in the table. Here's a working JSFiddle for reference.
YOUR Form (data-form)tag includes your edit/delete/ update inputs.Keep that out of your form tag.Then the java.lang.NumberFormatException: For input string: " will not take place.See if it works.
I tried adding the code further as mentioned above.It did not worked well.I am facing same dilemma.Anyone plz tell where is it going wrong?
<script>
$(function()
row.on("click", function() {
$('INPUT', this).each(function(i){
rowData['value' + (i+1)] = this.value;
});
fillForm(rowData);
});
function fillForm(rowData) {
var form = $(".data-form");
form.find("input.value1").val(rowData.value1);
form.find("input.value2").val(rowData.value2);
form.find("input.value3").val(rowData.value3);
form.find("input.value4").val(rowData.value4);
}
}
</script>
Try adding this to the on.cick function
row.on("click", function() {
$('INPUT', this).each(function(i){
rowData['value' + (i+1)] = this.value;
});
fillForm(rowData);
});

Categories

Resources