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
Related
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.
I have a pretty much simple issue with a table i create with PHP foreach (in codeigniter).
One column inside the table has 2 checkboxes. One true and one false so when i create the table has some names and infos and then 2 checkboxes. Whenever the user clicks the true I create an AJAX POST call to my database to change the state of a column. But when the user has clicked true and then he clicks false I want the true checkbox to be unchecked.
Here is the code
<table class="responstable">
<tr>
<th>ID</th>
<th><span>Name</span></th>
<th>number1</th>
<th>number2</th>
</tr>
<?php
foreach($students as $column => $data ) { ?>
<tr>
<td><?php echo $data[0]->Userproperties_UserAM; ?></td>
<td><?php echo $data[0]->Userproperties_UserFullName; ?></td>
<td><?php echo $data[0]->UserAbsence; ?></td>
<td> <input class="true" id="<?php echo $data[0]->Userproperties_UserId; ?>" type='checkbox' value="<?php echo $data[0]->Userproperties_UserAM; ?>" />
<label for='true'>
<span></span>
True
</label>
<input class="false" id="<?php echo $data[0]->Userproperties_UserId; ?>" type='checkbox' value="<?php echo $data[0]->Userproperties_UserAM; ?>" />
<label for='false'>
<span></span>
False
</label></td>
</tr>
<?php } ?>
</table>
And the ajax code
$(document).ready(function() {
$('.true').change(function() {
if($(this).is(":checked")) {
$('.false').attr('checked', false);
var moduleid = <?php echo $moduleid; ?>;
var teacherid = <?php echo $teacherid; ?>;
var studentid = $(this).attr('id');
var weeknum = $("#dropi").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/TeacherParousies/send_parousia",
data: {
moduleid: moduleid,
studentid: studentid,
teacherid: teacherid,
parousia: 1,
weeknum: weeknum
},
success: function(res) {
},
error: function(err) {
}
});
}
});
$('.false').change(function() {
if($(this).is(":checked")) {
$('.true').attr('checked', false);
var moduleid = <?php echo $moduleid; ?>;
var teacherid = <?php echo $teacherid; ?>;
var studentid = $(this).attr('id');
var weeknum = $("#dropi").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/TeacherParousies/send_parousia",
data: {
moduleid: moduleid,
studentid: studentid,
teacherid: teacherid,
parousia: 0,
weeknum: weeknum
},
success: function(res) {
},
error: function(err) {
}
});
}
});
});
The problem here is that when i check the 2nd row of the table's checkbox lets say false, there is a change on the 1st row for true if it is checked.
Although I have stated
if($(this).is(":checked"))
Any idea?
In your case it .false and .true will uncheck all. You just need to check the nearest element.
Kindly replace the code $('.true').attr('checked', false); with this code $(this).closest( "td" ).find('.true').attr('checked', false);
and do same with for $('.false').attr('checked', false); this $(this).closest( "td" ).find('.false').attr('checked', false);
I have two same name multiple input fields. I want to send all fields value from another page using jquery ajax post method but i am not getting all rows input fields value. Please review my code.
Javascript code
<script type="text/javascript">
function getValue()
{
$.post("paidamt.php",
{
paidamt : $('#paidamt').val(),
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Html Code
<div>
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) {
?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" id="paidamt"></td>
<td><input type="checkbox" name="uid[]" id="uid"
value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<input type="button" name="submit" id="submit"
onclick="getValue(1)" value="Save Amt.">
</form>
</div>
<div id="divShow">
</div>
Try this one
var paidamt = $("input[name=paidamt]").map(function(){
return $(this).val();
}).get().join(",");
var uid = $("input[name=uid]").map(function(){
return $(this).val();
}).get().join(",");
$.ajax(
{
type: "POST",
url: 'paidamt.php',
data:
{
paidamt:paidamt,
uid:uid
}
});
Firstly you have given the input elements the same id which is repeated in the loop. This will end up in your HTML being invalid, you should change the id to class:
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) { ?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" class="paidamt"></td>
<td><input type="checkbox" name="uid[]" class="uid" value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<button type="submit" name="submit" id="submit">Save Amt.</button>
</form>
To actually send the input values in the AJAX request you can simply serialize() the containing form when the form is submit:
$(function() {
$('form').submit(function(e) {
$.ajax({
url: "paidamt.php",
type: 'POST',
data: $(this).serialize(),
success: function(data) {
$("#divShow").html(data);
});
});
});
});
I suggest to add class instead of id, since identically class can be repeated but id should not.
<script type="text/javascript">
function getValue()
{
var paidamtval = [];
$('#paidamt').each(function(){
paidamtval.push($(this).val());
});
$.post("paidamt.php",
{
paidamt : paidamtval,
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Since you will have many of these, id - needs to be unique, which in your case isn't, so remove "id="paidamt"
<td><input type="text" name="paidamt[]" id="paidamt"></td>
That's your first mistake. And secondly don't use $.post, to submit this form. Either remove AJAX submit, or bind form using something like jQuery Form plugin.
You try this code
$('document').ready(function(){
$('#submit').click(function(){
jQuery.ajax({
type: "POST",
url: "paidamt.php",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(html){
try{
$("#divShow").html(data);
}catch (e){
alert(JSON.stringify(e));
}
},
error : function(e){alert("error "+JSON.stringify(e)); }
});
});
});
in you paidamt.php file
$paidamt=$_POST['paidamt'];// its can array values
print_r($paidamt);// result display
I'm trying to display a list of players with a edit button next to each one. When edit is pressed, then the user can edit that player. I'm trying to do this using ajax. The problem: The table will display for a split second then it's a blank screen.
<?php foreach($players as $player): ?>
<tr>
<td><?= $player['first_name']; ?></td>
<td><?= $player['last_name']; ?></td>
<td><?= $player['email']; ?></td>
<td align="center" >
<form action="" method="post" id="edit_player">
<input type="hidden" name="user_id" value="<?= player['user_id']; ?>">
<input type="submit" value='Edit' name='submit'>
</form>
</td>
</tr>
<?php endforeach;?>
Here is my jquery/ajax code. I made some changes from earlier. I think it's better, but it's still not working.
$(document).ready(function() {
var contents = $('#teamMain');
$('.edit_player').each(function(index, value) {
var formData = $(this).attr('user_id');
$.ajax({
url: 'views/team_nav.php',
type: 'POST',
cache: false,
data: formData,
success: function(data){
contents.html(data);
}
});
});
});
I implemented a project in Yii. I want to delete data from table using ajax function.
In my controller I wrote this:
public function actionDelete1(){
if (isset($_POST['x1']) && isset($_POST['r_id'])) {
$hid=$_POST['x1'];
$rid=$_POST['r_id'];
echo $_POST['x1'].'recipe_id'.$_POST['r_id'];
$query="delete from ingredients where ingredienttype_id='$hid'";
$query1=Yii::app()->db->CreateCommand($query)->execute();
$this->redirect(array('recipe/update','id'=>$rid));
}
}
In my view part:
<script>
function removeRow1(x,y){
alert("Are sure want to delete");
$.ajax({
url: '<?php echo Yii::app()->createAbsoluteUrl("ingredients/delete1"); ?>',
type: 'POST',
data: 'x1='+x+'&r_id='+y,
success: function(res)
{
//alert(res);
////$("#truth").html(res);
},
error:function(){
alert("Failed request data from ajax page");
}
});
}
</script>
I display these three table data with one row:
<td id="data">
<?php
echo $i++;
?>
</td>
<td id="data">
<?php
$type=Ingredienttype::model()->find("id=$type_id");
echo $type['ingredient_type'];
?>
</td>
<td id="data">
<?php
$type1=Ingredient::model()->find("ingredient_id=$ingredient_id");
//echo $ingredient_id;
echo $type1['ingredientname'];
?>
</td>
<td id="data">
<?php
echo $quantity;
?>
</td>
<td id="data">
<?php
$mes_type=Measuringtype::model()->find("id=$measuringtype");
echo $mes_type['measuringname'];
?>
</td>
<input type="button" id="<?php echo $type_id; ?>" name="doesntMatter" class="REMOVETHIS btn btn-inverse btn-xs"
value="Del" onclick="removeRow1(this.id,<?php echo $model->recipe_id ?>)"/></td>
It's not working. Please suggest me how to delete ID using ajax.
First you have
$query="delete from ingredients where ingredienttype_id='$hid'";
where $hid is not defined yet!
Would you use either $hid or $rid ?
Secondly, sending params with ajax, data should be an object, I don't know if it works with a string. so to be sure, try using an object as follows
$.ajax({
url: '<?php echo Yii::app()->createAbsoluteUrl("ingredients/delete1"); ?>',
type: 'POST',
data: {'x1':x,'r_id':y},
success: function(res)
{
//----