Dynamically created button in table per row in jquery - php

Only the first row is updating.. I was able to create a dynamically created select tags and button but every time I were to choose to the drop down, only the first row is being updated and the other rows will alert only "choose first" even though i already selected an option.
jquery func'
$('input').each(function(){
if($(this).attr("type")=="button"){
$(this).click(function{
var empid=$('#emp').val();
var job=$('#jobselect').val();
if(job !== "NULL"){
$.ajax({
type:"POST",
url:"<?php echo base_url(); ?>userskills/update",
data:{'Emp_ID':empid,'Job':job},
cache: false;
success:
function(data){
alert("Updated!");
}
});
}else{
alert("Choose first");
}
});
}
});
this is my tbody in the table
<tbody>
<?php foreach($job as $temp): ?>
<tr>
<td><?php echo $temp->Name?></td>
<td><?php echo $temp->Group?></td>
<td><?php echo $temp->Section?></td>
<td>
<select id="jobselect">
<?php foreach($roles as $role): ?>
<option value="<?php echo $role->RoleID">"><?php echo $role->RoleName?></option>
<?php endforeach; ?>
</select>
<input type="hidden" id="emp" value="<?php echo $temp->JobID?>" />
<input type="button" id="update"/>
</td>
</tr>
<?php endforeach; ?>
</tbody>

The id attribute is supposed to be unique within the document, so your current code creates invalid HTML. The browser won't be too bothered by it and will display your elements anyway, but then in JS if you select by element ID (like '#jobselect') you only get back the first element with that ID.
You should switch to use a common class instead, and then in your JS use DOM navigation to get from the clicked button (referenced by this) to its related controls using .closest() to get the containing td element and then .find() to get the items within that td:
$('input[type="button"]').click(function(){ // no need for .each()
var container = $(this).closest('td'); // 1. get common parent element
var empid = container.find('.emp').val(); // 2. note the use of .find() with
var job = container.find('.jobselect').val(); // class selectors here
if (job !== "NULL") {
$.ajax({
type:"POST",
url:"<?php echo base_url(); ?>userskills/update",
cache: false;
success:
function(data){
alert("Updated!");
}
});
} else {
alert("Choose first");
}
});
<tbody>
<?php foreach($job as $temp): ?>
<tr>
<td><?php echo $temp->Name?></td>
<td><?php echo $temp->Group?></td>
<td><?php echo $temp->Section?></td>
<td>
<select class="jobselect">
<?php foreach($roles as $role): ?>
<option value="<?php echo $role->RoleID">"><?php echo $role->RoleName?></option>
<?php endforeach; ?>
</select>
<input type="hidden" class="emp" value="<?php echo $temp->JobID?>"
<input type="button" class="update"/>
</td>
</tr>
<?php endforeach; ?>
</tbody>
Note that you don't need the .each() loop at all if you change your selector to just get the input elements that are buttons.

Related

Jquery only fired when changing one select input but not the other select tags

for a users table, I'm trying to dynamically create a feature which allows the admin person to change the user's role from the table by clicking the select tag and changing the the role from the list of the roles provided which would fire the JQuery at the bottom with an AJAX called. The problem is, it is only responding to just one select tag on the table which is the one at the top row. I have someone understanding of what is wrong but have no idea how to resolve it. I think I need to loop through the events and listen to which is firing but I do not know how to implement that. Any help is much appreciated.
<tbody>
<?php while ($all_admins = mysqli_fetch_assoc($admins)) { ?>
<tr>
<td><img src="<?php echo url_for('../images/staff/'.$all_admins['image'])?>" onerror="this.src='<?php echo url_for('../images/staff/profile.jpg') ?>'" style="border:1px solid #ddd;border-radius:2px; box-shadow: #4a5f63; height: 70px;width: 70px"></td>
<td><?php echo h($all_admins['first_name']) ?></td>
<td><?php echo h($all_admins['last_name']) ?></td>
<td><a class='btn btn-info' href="staff.php?source=show_staff&staff_id=<?php echo h($all_admins['id']) ?>"> <?php echo h($all_admins['email']) ?> </a></td>
<td>
<?php
$role = $all_admins['role'];
switch ($role){
case 'DE':
echo "Data Entry";
break;
case 'GU':
echo "General User";
break;
default:
echo "Administrator";
break;
}
?>
<span>
<select id="urole" name="role[]">
<option value="Admin" <?php echo ($role == 'Admin')?'selected':'' ?> >Admin</option>
<option value="DE" <?php echo ($role == 'DE')?'selected':'' ?> >Data Entry</option>
<option value="GU" <?php echo ($role == 'GU')?'selected':'' ?> >General User</option>
</select>
</span>
</td>
<td><a class='btn btn-info' href="staff.php?source=edit_staff&staff_id=<?php echo h($all_admins['id']) ?>">Edit</a></td>
<form method="post">
<input type="hidden" name="post_id" value="<?php //echo $post_id ?>">
<?php
echo '<td><input class="btn btn-danger" type="submit" name="delete" value="Delete"></td>';
?>
</form>
</tr>
$(document).ready(function ()
{
$("#urole").change(function (){
var val = $("#urole option:selected").val();
console.log(val);
// $("#urole").on('click', function(){
// v
// });
//displayData(val);
});
$("#urole").ready(function (){
var val = $("#urole option:selected").val();
console.log(val);
//displayData(val);
});
});
function displayData(query){
$.ajax({
url:"enrolled_learners/enrol_learner_provider.php",
method:"post",
data:{query:query},
success:function (data)
{
//console.log(data);
$('#q-provider').html(data);
}
});
}
</script>
Your issue is that you're using duplicate ids which is not valid. element ids must be unique. As such $("#urole") is internally designed to return only one element. Instead, you should use a common class on these elements and use $(".urole") to target all elements that have that class.
Change your form to
<select class="urole" name="role[]">
And your jQuery to:
$("#urole").change(function (){
var val = $(this).val();
console.log(val);
displayData(val);
});

How to pass and assign keyup value to php variable on same php file?

I need to pass the input value of this text field...
<input type="text" class="form-control" placeholder="No of persons" name="persons" id="persons" style="width:270px;">
and retrieve it in the same php file (assign it to $pers) in order to use that value for an if condition to display this part of a table inside a modal when a certain button is clicked.
<?php
if(isset($_POST['persons']))
{
$pers=$_POST['persons'];
}
$result=mysql_query("SELECT * FROM tblrooms");
while($row=mysql_fetch_array($result))
{
$rno = $row['room_name'];
$max = $row['max_occupancy'];
$status = $row['status'];
if($pers<=$max)
{
?>
<tr>
<td style="font-size:13px;"><?php echo $rno; ?></td>
<td style="font-size:13px;"><?php echo $max; ?></td>
<td style="font-size:13px; display:none;"><?php echo $status; ?></td>
</tr>
<?php
}
}
?>
Afterwards I have to retrieve some data inside the modal (I've already done that). So all I need is to assign the retrieved value from the text field in order to properly display the things inside the modal.
Script
<script>
$('#persons').keyup(function()
{
var aj = $('#persons').val();
$.ajax({
type: 'POST',
url: 'transaction_form.php',
data: {persons: aj},
success: function(response){
$('$result').html(response);
}
});
});
</script>

I have a mouseover function to get data from the database based on the value of each row. However, it is returning the same values for all row

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>

Get the value of text box using jquery

I have the following script :
<script>
$(document).ready(function() {
$('#edit').click(function (){
//get
employee_id = $('#employee_id').val();
alert(employee_id);
html='';
$.ajax({
type: "GET",
url: "<?php echo base_url();?>administrator/admin/get_employee_details/"+employee_id,
dataType: "json",
success: function(response) {
console.log(response);
$( '#fname' ).val(response[0].f_name);
alert(response[0].amount);
$( '#sname' ).val(response[0].l_name);
$( '#lname' ).val(response[0].other_name);
$( '#expiry_date' ).val(response[0].id_no);
$( '#quantity_available').val(response[0].dob)
$( '#gender' ).val(response[0].gender);
$( '#maritalstatus').val(response[0].marital_status)
$( '#sex' ).val(response[0].gender);
},
error: function(data){
}
})
});
});
</script>
The script is supposed pick the employee_id value from the table below :
<tbody>
<?php foreach($employee_details as $employee ):?>
<tr class="odd gradeX">
<td><?php echo $employee['employee_name'];?></td>
<td ><?php echo $employee['id_no'];?></td>
<td><?php echo $employee['dob'];?></td>
<td><?php echo $employee['gender'];?></td>
<td ><?php echo $employee['marital_status'];?></td>
<td><?php echo $employee['phone_no'];?></td>
<td><?php echo $employee['email'];?></td>
<td ><?php echo $employee['date_added'];?></td>
<td><?php echo $employee['residence'];?></td>
<td ><?php echo $employee['next_of_kin_name'];?></td>
<td><?php echo $employee['next_of_kin_relation'];?></td>
<td><?php echo $employee['next_of_kin_phone_no'];?></td>
<td ><?php echo $employee['is_active'];?></td>
<td><?php echo $employee['department_name'];?></td>
<td><?php echo $employee['employee_class'];?></td>
<td><a class="edit" href="#edit_details" id="edit">Edit </a></td>
<td> <a class="delete" href="#delete_details" id="delete" > Delete Employee</a></td>
<input type="text" name="employee_id" id="employee_id" value="<?php echo $employee['employee_id'];?>"/>
</tr>
<?php endforeach;?>
</tbody>
which is a hidden text field (employee_id) in the table when I click the Edit button. But when I click the link , I get an empty result with no employee_id yet I can see the employee id in the text box. How can I get the employee id from the text box for each specific row?
Id of an element must unique, so inside the loop use class instead of id, also move the employee_id field to a td element
<td>
<a class="edit" href="#edit_details">Edit </a>
</td>
<td>
<a class="delete" href="#delete_details" > Delete Employee</a>
<input type="text" name="employee_id" value="<?php echo $employee['employee_id'];?>" />
</td>
then
$(document).ready(function () {
$('.edit').click(function () {
//get
var employee_id = $(this).closest('tr').find('input[name="employee_id"]').val();
alert(employee_id);
html = '';
$.ajax({
type: "GET",
url: "<?php echo base_url();?>administrator/admin/get_employee_details/" + employee_id,
dataType: "json",
success: function (response) {
console.log(response);
$('#fname').val(response[0].f_name);
alert(response[0].amount);
$('#sname').val(response[0].l_name);
$('#lname').val(response[0].other_name);
$('#expiry_date').val(response[0].id_no);
$('#quantity_available').val(response[0].dob)
$('#gender').val(response[0].gender);
$('#maritalstatus').val(response[0].marital_status)
$('#sex').val(response[0].gender);
},
error: function (data) {
}
})
});
});
The id attribute must be unique in your web page. You can't have 2 elements with the same id.
So for your links and your inputs, you must generate a different id for each row. For example you can try id="employee_id-<?php echo $employee['employee_id'];?>".
But you can keep the same classes for each link and input, and use it in your javascript script code.
Then you must change your code :
$('.edit').click(function() {
var employee_id = this.closest('tr').find('.employee_id').val();
});
Use class attribute instead of id because id cant be repeated.
<input type="text" name="employee_id" class="employee_id" value="<?php echo $employee['employee_id'];?>"/>
$('.edit').click(function() {
var id = this.closest('tr').find('input.employee_id').val();
});
In Id you will be able to get employee id

Get Ajax variable from the PHP foreach loops

I have a simple ajax (jquery version) script and very short php function and they works fine without problem.
When I submit the value from the form input are, the ajax will work to send and get result from
the php script, in this case to get a total amount of the book order.
The Ajax script and html section are as follows:
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
// get field value
var qtyVal = $('#qty').val();
// use HTTP GET get ajax
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
//get xml value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
<body>
Total price:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div>
<form>
<p>
<label>quantity: </label>
<input type="text" id="qty" name="qty"/>
<br/>
<input type="submit" value="submit">
total price:</p>
<p> </p>
</form>
And the following php script serving as xml also works fine with above ajax request:
<?php
// XML document
header("Content-Type: text/xml");
header("Content-Type:text/html; charset=utf-8");
// get field values
$qty = (isset($_POST["qty"]) ) ? $_POST["qty"] : $_GET["qty"];
echo "<?xml version=\"1.0\" ?>";
echo "<datetime>";
echo "<qty>" . $qty*100 . "</qty>";
$total=$qty*100;
if ($total==0)
echo "<caution>"."please input number!"."</caution>";
else if ($total<=500)
echo "<caution>"."you shoud buy more!"."</caution>";
echo "";
echo "</datetime>";
?>
However when I combine the above scripts with my shopping cart foreach loops, it doesn't work and the ajax script failed to get variables from the form input area. I don't know if it is a variable scope issue (globals or local)? or anything else?
The following is the total script I would like to fixed with:
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
// get value from the form
var qtyVal = $('#qty').val();
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
</head>
<body>
<table border="1" align="center">
<tr>
<th>no</th>
<th>name</th>
<th>price</th>
<th>qty</th>
<th>update</th>
</tr>
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<form action="sessionCartUpdate.php">
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td><?php echo $_SESSION["psn"][$i];?></td>
<td><?php echo $_SESSION["pname"][$i];?></td>
<td><?php echo $_SESSION["price"][$i];?></td>
<td><input type="text" id="qty" name="qty" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<input type="submit" name="qty"
<td><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr>
</form>
<?php
}
?>
<tr><td colsan="5">total amount:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div></td></td>
</table>
<p>continue to shop
<p>Put your order
</body>
</html>
I would be very grateful if anyone can offer kind or possible suggestion or advice?
My goal is to put different number (variables) in the "input area" (name or id as "qty") throught the using of ajax to get a total amount of price and show the result in the div box (id="result" or "result1").
You should replace the id attribute with class because id is supposed to be unique in the dom and using class you can do a loop to get all quantities of the items in the cart
Another thing i have noticed that you have made the an individual form foreach item in the cart there should be one form having the multiple fields,also remove this line <input type="submit" name="qty" it doesent makes sense
<form action="sessionCartUpdate.php">
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td><?php echo $_SESSION["psn"][$i];?></td>
<td><?php echo $_SESSION["pname"][$i];?></td>
<td><?php echo $_SESSION["price"][$i];?></td>
<td><input type="text" class="qty" name="qty[]" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<td><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr>
<?php
}
?>
</form>
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
var qtyVal =0;
$( ".qty" ).each(function() {
qtyVal =qtyVal + parseInt($(this).val());
});
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
// get field values
$qty = (isset($_POST["qty"]) ) ? $_POST["qty"] : $_GET["qty"];
Instead of using both $_GET and $_POST, you can use $_REQUEST which will give data from either POST or GET.

Categories