I have a table that is dynamically populated from mysql database.User are expected to select a staff number, which automatically goes to the DB and fetches his staff number.I have like 10rows. it works fine for the first row but not the subsequent other others.
Please, take a look at the code and advice where I am missing it.
Thanks
<tr>
<th nowrap="nowrap">S/N</th>
<th nowrap="nowrap">VNO</th>
<th nowrap="nowrap">Name</th>
<th nowrap="nowrap">Staff No</th>
</tr>
<tr>
<?php
$c=0;
$st =mysqli_query($connection,"SELECT * FROM tab_flt WHERE mainloc='".$_SESSION['location']."' AND status='Active'");
while($r = mysqli_fetch_array($st)){ $c++?>
<td><?php echo $c;?></td>
<td><input type="text" name="flt[]" value="<?php echo $r['fltno'];?>" class="form-control" readonly="readonly" /></td>
<td><select name="opname[]" class="form-control" id="subloc">
<option>Select...</option>
<?php
$fs = getOperators($_SESSION['location']);
while($f = mysqli_fetch_array($fs)){?>
<option value="<?php echo $f['name'];?>"><?php echo $f['name'];?></option>
<?php };?>
</select></td>
<td id="staffno"></td>
</tr>
Ajax side:
<script type="text/javascript">
$(document).ready(function() {
$("#subloc").change(function(){
var sname = $("#subloc option:selected").val();
$.ajax({
type:"POST",
url:"process-opno.php",
data:{opname:sname}
}).done(function(data3){
$("#staffno").html(data3);
});
});
});
</script>
The above fetches the first rows when subloc id is selected successfully into staffno id.
But it does not do it for the remaining lines. What can i do so, that it will recognise the second line, third line etc and fetches the corresponding staff number into the staffno id .
Thanks.
Please try this:
PHP Part I have added classes for select box and select box ajax result
<tr>
<?php
$c=0;
$st =mysqli_query($connection,"SELECT * FROM tab_flt WHERE mainloc='".$_SESSION['location']."' AND status='Active'");
while($r = mysqli_fetch_array($st)){
$c++;
?>
<td><?php echo $c;?></td>
<td><input type="text" name="flt[]" value="<?php echo $r['fltno'];?>" class="form-control" readonly="readonly" /></td>
<td>
<select name="opname[]" class="form-control js-sel-box" data-id="<?php echo $c;?>">
<option>Select...</option>
<?php
$fs = getOperators($_SESSION['location']);
while($f = mysqli_fetch_array($fs)){
?>
<option value="<?php echo $f['name'];?>"><?php echo $f['name'];?></option>
<?php
};
?>
</select>
</td>
<td class="js-sel-box-ajax-result-<?php echo $c;?>"></td>
<?php
}//End While
?>
</tr>
Ajax Part:
<script type="text/javascript">
$(document).ready(function() {
$(".js-sel-box").change(function(){
var sname = $(this).val();
var result_id = $(this).attr("data-id");
$.ajax({
type:"POST",
url:"process-opno.php",
data:{opname:sname}
}).done(function(data3){
$(".js-sel-box-ajax-result-"+result_id).html(data3);
});
});
});
</script>
The same old problem with unique ids, change the id into a class,find all your elements based on the changed select
<script type="text/javascript">
$(document).ready(function() {
$("td select.form-control").change(function(){
var sname = $(this).val();
var el = $(this);
$.ajax({type:"POST",url:"process-opno.php",data:{opname:sname}})
.done(function(data3){
$(this).parent().next("td").html(data3);
});
});
});
</script>
Yes, its better to use class identifier instead of id to identify multiple DOM elements; but in yours it can be workable with minimum changes-
// use
var sname = $(this).val();
//put this line just var sname
var $object =$(this);
// instead of
var sname = $("#subloc option:selected").val();
// this is because- $('#subloc option:selected').val(); always returns the first
//dropdownList/optionlist from the DOM array, you can use `this` to track which DOM has been change recently
// another change in your code $object is $(this) equivalent but will not work inside ajax so you need to create $object as in code above..
// put this line
$($object).parents('tr').find("#staffno").html(data3);
//instead of
$("#staffno").html(data3);
// above line will search parent tr and will look for DOM element with id staffno a
Related
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 had 4 table like this
Table
And then im going to fill this form
Form
the workflow is, when i select Item Type and Treatment, the price should be filled based on the ServicePrice Table, I can get the Price from ServicePrice, but when I check XHR on network, it shows the value of Price but its data just show for 1st time, I mean when the modal opened, it shows the first data, when the option changed, the Price value keep like the 1st time modal open. so I want whenever the Item Type or Treatment changed, I want to make the price box filled dynamically
here's my form
<tr>
<td>Item Type</td>
<td>
<select name="ItemTypeID" class="form-control" id="ItemType" >
<option selected=""></option>
<?php
$sql2 = mysql_query("select * from itemtype");
while($record = mysql_fetch_array($sql2)){
?>
<option value="<?php echo $record['ID']; ?>" title="<?php echo $record['DefaultSpec']; ?>"> <?php echo $record["Name"]; ?> </option>
<?php } ?>
</select>
</td>
</tr>
<tr>
<td>Treatment</td>
<td>
<select name="TreatmentID" class="form-control" id="Treatment">
<?php
$sql2 = mysql_query("select * from treatment");
while($record = mysql_fetch_array($sql2)){
?>
<option value="<?php echo $record['ID']; ?>"> <?php echo $record["Name"]; ?> </option>
<?php } ?>
</select>
</td>
</tr>
and then my ajax
$("#ItemType, #Treatment").change(function(){
var ItemType = $(this).val();
var Treatment = $(this).val();
console.log(Treatment);
console.log(ItemType);
$.ajax({
type: "POST",
dataType: "html",
url: "GetPrice.php",
data: {ItemTypeID: ItemType, TreatmentID: Treatment},
success: function(result){
console.log(result);
$("#Price").val(result);
});
});
my GetPrice.php
<?php include "../Content/connection.php";
$a="SELECT * FROM ServicePrice WHERE ItemtypeID = '".$_POST["ItemTypeID"]."' AND TreatmentID = '".$_POST["TreatmentID"]."'";
$q=mysql_query($a);
while($record=mysql_fetch_array($q)){
echo $record['Price'];
}
?>
EDIT :
im making it like this it give me correct answer but the Price value triggered only if treatment dropdown changed, how can i make it trigger by booth dropdown?
$("#ItemType").change(function(){
var ItemType = $(this).val();
$("#Treatment").change(function(){
var Treatment = $(this).val();
the $(this).val() inside the change event handler will not work to get data for both the fields,
instead fetch the data of ItemType and Treatment individually
$("#ItemType, #Treatment").on('change', function(){
var ItemType = $("#ItemType").val();
var Treatment = $("#Treatment").val();
$.ajax({
type: "POST",
url: "GetPrice.php",
data: {ItemTypeID: ItemType, TreatmentID: Treatment},
success: function(result){
$("#Price").val(result);
}
});
});
I need help. I am experimenting with J QUERY for the first time. I have a mouseover function to get and display data from the database based on the row id. However, I am getting the same value for all the rows. Thanks!
while($stmt->fetch()){?>
<td class="other">
<input type="hidden" class="rowid" value="<?php echo $id ?>"/>
<?php echo round($other,2); ?>
</td>
<?php
}
?>
//jquery code:
$(document).ready(function(){
$(".other ").mouseover(function(){
var rowid = $('#rowid').val();
$.get('other.php',{postrowid:rowid},
function(data)
{
$('#otherResult').html(data);
$('#otherResult').show();
$(".other").mouseout(function(){
$('#otherResult').hide();
});
});
});
// Change:
var rowid = $('#rowid').val();
// To:
var rowid = $('input', this).val();
Sidenote: Instead of using a hidden field, you can add data to related tags using HTML5 data-* attribute:
<td class="other" data-id="<?php echo $id ?>">
<?php echo round($other,2); ?>
</td>
I have searched very long for a solution to this problem but could not find any.
I get data from the database to show some projects on my website. For each project i can click on a pen-symbol to edit the name of the project. I´d like to send the date per ajax request, but always get the data of the first project. If i try for example to edit the name of the second project "test", i get the data of the first project "blubb"
What i have tried:
- Used classes not Id´s
Call Ajax function from PHP foreach with form
- Used $this
Get Ajax variable from the PHP foreach loops
My code lookes like this (simplified):
< script type = "text/javascript" >
$(document).ready(function() {
$(".submit").click(function() {
//here are the problems, i only get the value of the first project
var new_project_name = $('.new_project_name').val();
var old_project_name = $('.old_project_name').val();
$.ajax({
type: "POST",
url: "php/edit/edit.php",
data: {
old_project_name: old_project_name,
new_project_name: new_project_name,
name: name
},
}).
done(function(response) {
blabla
});
});
}); < /script>
<?php foreach($db->query('SELECT * FROM portfolio ORDER BY position, id desc') as $row) { $name = $row['name']; ?>
<div class="rename">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td>Projektname:</td>
</tr>
<tr>
<td>
<input type="text" class="new_project_name" value="<?php echo $name;?>">
</td>
<input type="text" class="old_project_name" value="<?php echo $name;?>" hidden>
</tr>
<tr>
<td>
<input class="submit" type="submit" value="Umbenennen">
</td>
</tr>
</table>
</div>
<?php } ?>
Thank you for any help.
you could pass the id of the project to ajax and update the new value. For that you just need to pass the id of the element.
HTML
<input type="text" class="new_project_name" value="<?php echo $name;?>" rel="<?php echo $id; ?>">
jQuery
$(document).ready(function() {
$(".submit").click(function() {
var parentObj = $(this).closest('.rename');
var id = parentObj.find(' .new_project_name').attr('rel');
var project_name = parentObj.find(' .new_project_name').val();
$.ajax({
type: "POST",
url: "php/edit/edit.php",
data: {
project_name : project_name ,
id:id
},
}).
done(function(response) {
blabla
});
});
});
See the Fiddle and check console
http://jsfiddle.net/hoja/2caukhvo/11/
I know very little jquery so please excuse me if I don't make much sense.
I have a table that it's rows are populated from a php db query (the number of rows will vary) in this case there are two rows of data. Here is a portion of the php generated html table.
<table border=1 width=800px id=workout>
<tr>
<th width=300px id=clients>Client</th>
<th width=200px id=movements>Movements</th>
<th>X Completed</th>
</tr>
<tr>
<td><input type="hidden" name="client_id[]" class="clientval" value="1"></td>
<td>
<select name="movement[]" width=200 class='typeval' onchange='changeMovement()'>
<option value="select">Select...</option>
<option>Key Movement</option>
<option>Movement -1</option>
<option selected="selected" >Movement -2</option>
<option>Movement -3</option>
<option>Movement -4</option>
</select>
</td>
<td><label id="count"></label></td>
</tr>
<tr>
<td><input type="hidden" name="client_id[]" class="clientval" value="8">
<td>
<select name="movement[]" width=200 class='typeval' onchange='changeMovement()'>
<option value="select">Select...</option>
<option>Key Movement</option>
<option>Movement -1</option>
<option selected="selected" >Movement -2</option>
<option>Movement -3</option>
<option>Movement -4</option>
</select>
</td>
<td><label id="count"></label></td>
</tr>
I am passing the values of movement and client_id to a POST jquery so I can run a php query on the data and return result. How do I pass along the value of selected movement and client_id based on the row that the select menu is in.
For example: if user changes movement drop down menu on the 2nd row I want to send the client_id and the selected>Movement< to the jQuery function. Right now it is just getting the first row of my table and that is all.
Here is my edited jQuery:
Edited:
<script type="text/javascript">
var typeval,clientval, class_id;
$('.typeval').on('change', function(){
movement = $(".typeval option:selected").val();
client_id = $(this).parents('tr').find('input.clientval').val();
class_id = $(<? echo $class_id; ?>).val();
//console.log($(this).parents('tr').find('input.clientval').val(), $(this).val());
$.ajax(
{ url: "movement_count.php",
type: "post",
data: {typeval:typeval, client_id: clientval, class_id :},
dataType: "json",
});
success: (function(output) {
alert(output);
$(".count").html(output);
})
});
</script>
Since you're using jQuery I'd do it like this. Remove the inline JavaScript and bind to the change event of the select elements.
var typeval,clientval;
$('select.typeval').change(function() {
//console.log($(this).parents('tr').find('input').val(), $(this).val());
typeval = $(this).val();
clientval = $(this).parents('tr').find('input').val();
});
$(this).parents('tr').find('input').val(); //will give you the
client_id
$(this).val(); // will give you the value of the select item
You can then just drop those values into your AJAX call.
jsFiddle example
Well, you need to do the following:
1. Remove all onchange='changeMovement()', you won't need them anymore.
2. Just echo the class_id from PHP.
3. Fix the way you get the client_id as below.
Code:
$(document).ready(function() {
$('.typeval').change(function() {
var movement = $(this).val();
var client_id = $(this).parent().siblings().find('.clientval').val();
var class_id = <?php echo $class_id; ?>;
/* Do your AJAX call here */
});
});
Give your select and input elements a unique id using php. Something like:
<input type="hidden" id="client_id$client_id" ...
<select name="movement[]" id="mov$client_id" ...
Then in your javascript function use php to include the client_id like this:
changeMovement(client_id)
then you can use the client_id to change whatever movement that corresponds like this:
var client = $("#client_id"+client_id).val();
var movement = $("#mov"+client_id).val();
For the unique ID, you probably want to use whatever variable is populating the value field of your hidden inputs of each row. I say that without knowing exactly where those numbers are coming from.
Using James' solution it would look like this:
then the jquery looks like this:
var movement = this.value
var client_id = this.parent().find(".clientval")
Check this working example.. http://jsfiddle.net/sushanth009/BZ5Wt/
You can get the ClientId of the selected row by using this line..
var client = $(this).parent().parent().find('.clientval').val();