jQuery- Not able to select the right td - javascript

I can't seem to identify what went wrong with my jquery such that it keeps sending null data. Basically, after clicking a button I get a bunch of results and I want to be able to press edit and then edit that row which I can do but the values don't go into my ajax post to my api. I think that it would be my variable not selecting the correct td thus resulting in nothing being sent to the ajax post.
HTML:
<table id="results" class="hidden" cellspacing=10px>
<thead>
<tr class = "spacing">
<th id= "samIdTable">SAM ID</th>
<th id= "itemDescrip">Item Description</th>
<th id= "issuedQty">Issued QTY</th>
<th id= "openingQty">Opening QTY</th>
<th id= "closingQty">Closing QTY</th>
<th id= "corruptedQty">Corrupted QTY</th>
<th id="Remarks">Remarks</th>
</tr>
</thead>
<tbody id="bResults">
<tr class="rowdata">
<td>hi</td>
<td>hi</td>
<td>hi</td>
<td>hi</td>
<td>hi</td>
<td>hi</td>
<td>hi</td>
<td><input class="button-edit" type="submit" id="edit" value="Edit" onclick="edit(this)"></td>
</tr>
<tr class="rowdata">
<td>hi</td>
<td>hi</td>
<td>hi</td>
<td>hi</td>
<td>hi</td>
<td>hi</td>
<td>hi</td>
<td><input class="button-edit" type="submit" id="edit" value="Edit" onclick="edit(this)"></td>
</tr>
</tbody>
</table>
JS CODE
function edit(el){
var currentTD = $(el).closest('tr').find('td'); // tds except the td which closest to the edit button
var samId = currentTD.find("td:nth-child(1)").val();
var itemDescrip= currentTD.find("td:nth-child(2)").val();
var issueQty = currentTD.find("td:nth-child(3)").val();
var openingQty =currentTD.find("td:nth-child(4)").val();
var closingQty = currentTD.find("td:nth-child(5)").val();
var corruptedQty = currentTD.find("td:nth-child(6)").val();
var Remarks = currentTD.find("td:nth-child(7)").val();
var postData = { "samId": samId, "itemDescrip": itemDescrip, "issueQty" : issueQty,
"openQty" : openingQty, "closeQty" :closingQty,
"corrupQty": corruptedQty, "remarks": Remarks};
var postJSON = JSON.stringify(postData);
if ($(el).val() == 'Edit') {
$.each(currentTD, function () {
$(this).prop('contenteditable', true);
});
} else {
$.each(currentTD, function () {
$(this).prop('contenteditable', false);
});
}
$(el).val($(el).val() == 'Edit' ? 'Save' : 'Edit');
if($(el).val() == 'Edit' ){
$.ajax({
url: "http://localhost:3000/api/updateRecord", // server url
type: "POST", //POST or GET
contentType: "application/json", // data to send in ajax format or querystring format
data: postJSON,
dataType : "JSON", //dataType is you telling jQuery what kind of response to expect
success: function(response) {
alert('success');
if(response){
var txt = "";
txt += "<tr class='rowdata'><td>"+response.samID+"</td>"
+"<td>"+response.itemDescription+"</td>"
+"<td>"+response.issuedQTY + "</td>"
+"<td>"+response.openingQTY + "</td>"
+"<td>"+response.closingQTY+"</td>"
+"<td>"+response.corruptedQTY+"</td>"
+"<td>"+response.Remarks+"</td>"
+"</td>"+"</tr>";
}
if(txt != ""){
$("#results").removeClass("hidden");
$("#bResults").append(txt);
}
},
error: function(response) {
alert('error');
}
});
}
}
Do tell me if additional information is needed. Thank you in advance. Don't understand what is with the downvotes but I did state if additional information is needed, I will provide. If not, at least state reasons as to why it is downvoted and I could improve on it next time.

In your code var currentTD = $(el).closest('tr').find('td'); you have already selected the nearest <td> with query which does not have child <td> .Also you cannot get the value of td using .val().Use .html() instead.
I have modified some of your code like below.
Your html
<table id="results" class="hidden" cellspacing=10px>
<thead>
<tr class = "spacing">
<th id= "samIdTable">SAM ID</th>
<th id= "itemDescrip">Item Description</th>
<th id= "issuedQty">Issued QTY</th>
<th id= "openingQty">Opening QTY</th>
<th id= "closingQty">Closing QTY</th>
<th id= "corruptedQty">Corrupted QTY</th>
<th id="Remarks">Remarks</th>
</tr>
</thead>
<tbody id="bResults">
<tr class="rowdata">
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td><input class="button-edit" type="submit" id="edit" value="Edit" onclick="edit(this)"></td>
<tr class="rowdata">
<td>8</td>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
<td><input class="button-edit" type="submit" id="edit" value="Edit" onclick="edit(this)"></td>
</tbody>
</table>
And your javascript
function edit(el){
var currentTD = $(el).closest('tr').find('td'); // tds except the td which closest to the edit button
var current_id = $(el).closest('tr');
var samId = current_id.find("td:nth-child(1)").html();
var itemDescrip= current_id.find("td:nth-child(2)").html();
var issueQty = current_id.find("td:nth-child(3)").html();
var openingQty =current_id.find("td:nth-child(4)").html();
var closingQty = current_id.find("td:nth-child(5)").html();
var corruptedQty = current_id.find("td:nth-child(6)").html();
var Remarks = current_id.find("td:nth-child(7)").html();
var postData = { "samId": samId, "itemDescrip": itemDescrip, "issueQty" : issueQty,
"openQty" : openingQty, "closeQty" :closingQty,
"corrupQty": corruptedQty, "remarks": Remarks};
var postJSON = JSON.stringify(postData);
if ($(el).val() == 'Edit') {
$.each(currentTD, function () {
$(this).prop('contenteditable', true);
});
} else {
$.each(currentTD, function () {
$(this).prop('contenteditable', false);
});
}
$(el).val($(el).val() == 'Edit' ? 'Save' : 'Edit');
if($(el).val() == 'Edit' ){
$.ajax({
url: "http://localhost:3000/api/updateRecord", // server url
type: "POST", //POST or GET
contentType: "application/json", // data to send in ajax format or querystring format
data: postJSON,
dataType : "JSON", //dataType is you telling jQuery what kind of response to expect
success: function(response) {
alert('success');
if(response){
var txt = "";
txt += "<tr class='rowdata'><td>"+response.samID+"</td>"
+"<td>"+response.itemDescription+"</td>"
+"<td>"+response.issuedQTY + "</td>"
+"<td>"+response.openingQTY + "</td>"
+"<td>"+response.closingQTY+"</td>"
+"<td>"+response.corruptedQTY+"</td>"
+"<td>"+response.Remarks+"</td>"
+"</td>"+"</tr>";
}
if(txt != ""){
$("#results").removeClass("hidden");
$("#bResults").append(txt);
}
},
error: function(response) {
alert('error');
}
});
}
}
Hope it will work.

Instead of using find after getting the currentTD, I have used it as an array.
Please check the jsfiddle https://jsfiddle.net/jkpjjmeu/
function edit(el) {
var currentTD = $(el).closest('tr').find('td');
var samId = currentTD[0].textContent;
}

You're <tr>s don't close!
Add </tr> in the right places and try again.

Related

Table except table header not working html

Im been trying to select all checkbox in my table when clicking the checkbox in my header but the problem is when I try to submit all selected list it include the checkbox header. What I want is only the tbody should return value
what I've already tried, I change
$(':checkbox:checked')each(function(i){
id[i]=$(this).val()
})
To this , but not working
$(':checkbox:checked')not('thead tr').each(function(i){
id[i]=$(this).val()
})
my table
<button type="submit" id="update_btn" class="btn btn-secondary round btn-
min-width mr-1 mb-1" >Update Tag</button>
<table class="table" name="table" id="table">
<thead>
<tr >
<th >No</th>
<th><input type="checkbox" onClick="toggle(this)" /></th>
<th>ID Number</th>
<th >Name</th>
<th >Barangay</th>
<th >Sex</th>
<th >Sector</th>
<th Amount</th>
<th >Signature/Thumb Marks</th>
<th >ID Presented/ Date & Issuance</th>
<th>Date Received</th>
<th >Remarks</th>
</tr>
</thead>
<tbody class="report-content">
{% csrf_token %}
{% for user_information in benefeciaries %}
<tr id="{{user_information.id}}">
<td></td>
<td><input type="checkbox" name="product_id[]" value="
{{user_information.id}}"
id="delete_product"></td>
<td>{{user_information.covid_id}} </td>
<td>{{user_information.lastname}},
{{user_information.firstname}}
{{user_information.middle}}</td>
<td width="5%">{{user_information.barangay}}</td>
<td></td>
<td ></td>
<td>{{user_information.amount|floatformat:2|intcomma}}
</td>
<td></td>
<td ></td>
<td ></td>
<td></td>
</tr>
{% endfor %}
</tbody>
</table>
my javascript
$(document).ready(function(){
$('#update_btn').click(function(){
if(confirm("Are you sure ?")){
var id =[];
var csrf=$('input[name=csrfmiddlewaretoken]').val();
$(':checkbox:checked').each(function(i){ //I think this is the
problem
id[i]=$(this).val()
})
console.log(id)
$.ajax({
url:"/update/",
method:"POST",
data: {
id,
'prov':"{{province}}",
'muni':"{{municipal}}",
csrfmiddlewaretoken:csrf
},
success:function(response){
url:"/dashboard/"
// Swal.fire({title:"Successfully saved!",text:"Mark As
Paid",type:"success",confirmButtonClass:"btn btn-
success",buttonsStyling:!1})
}
})
}
})
});
If you only want to select the checkboxes in the tbody element, include that in the selector:
$('tbody :checkbox:checked')
In addition you can simplify the logic to create the array of selected checkbox values by using map() instead of each(). Try this:
let id = $('tbody :checkbox:checked').map((i, el) => el.value).get();`
Here's the complete example without some other improvements to the logic:
jQuery($ => {
$('#update_btn').click(function() {
if (!confirm("Are you sure ?"))
return;
let csrf = $('input[name=csrfmiddlewaretoken]').val();
let id = $('tbody :checkbox:checked').map((i, cb) => cb.value).get();
$.ajax({
url: "/update/",
method: "POST",
data: {
id,
'prov': "{{province}}",
'muni': "{{municipal}}",
csrfmiddlewaretoken: csrf
},
success: function(response) {
url: "/dashboard/"
/*
Swal.fire({
title: "Successfully saved!",
text: "Mark As Paid",
type: "success",
confirmButtonClass: "btn btn-success",
buttonsStyling: false
})
*/
}
});
})
});

How to display the values from ajax success data to the html table?

I need to view the ajax success message in my html table
my cshtml code is:
#*#{Customer.Models.Customers cust = ViewBag.Customers;
}*#
#{
}
<center><h1 style="color:red">User details</h1></center>
<div>
<table class="table">
<tr>
<td>ID</td>
<td>res.Id</td>
</tr>
<tr>
<td>FIRST NAME</td>
<td>res.Fname</td>
</tr>
<tr>
<td>LAST NAME</td>
<td>res.Lname</td>
</tr>
<tr>
<td>LOCATION</td>
<td>res.Location</td>
</tr>
<tr>
<td>Contact</td>
<td>res.Contact</td>
</tr>
<tr>
<td>Email</td>
<td>res.Email</td>
</tr>
<tr>
<td>Password</td>
<td>res.Password</td>
</tr>
<tr>
<td>Role</td>
<td>res.Category</td>
</tr>
<tr>
</table>
</div>
#section Scripts{
<script>
$.ajax({
contentType: "application/json",
type: "GET",
url: "https://localhost:44397/api/Values/Details/" + id,
success: function (data) {
alert('Welcome!');
res = data;
// window.location.href = "/Home/Details/" + data.id;
},
error: function (jqXHR, textStatus, errorThrown) {
$("#postResult").val(jqXHR.statusText);
}
});
</script>
}
Is there any way to use the success data to pass in the each table row?
That is I want the res to store the success data and then pass it to the table fields like res.Fname (eg) and it should display the data accordingly.
There are many way you can populate your table through Ajax response. Here the most readable and popular way you could try. See the below code snippet.
<table id="YourTableId" class="table table-bordered table-striped table-responsive table-hover">
<thead>
<tr>
<th align="left" class="yourTableTh">YourProperty</th>
<th align="left" class="yourTableTh">YourProperty2</th>
<th align="left" class="yourTableTh">YourProperty3</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
$.ajax({
contentType: "application/json",
type: "GET",
url: "https://localhost:44397/api/Values/Details/" + id,
success: function (data) {
alert('Welcome!');
// res = data;
var items = '';
$.each(data, function (i, item) {
var rows = "<tr>"
+ "<td class='yourTableTh'>" + item.YourProperty + "</td>"
+ "<td class='yourTableTh'>" + item.YourProperty2 + "</td>"
+ "<td class='yourTableTh'>" + item.YourProperty3 + "</td>"
+ "</tr>";
$('#YourTableId tbody').append(rows);
});
// window.location.href = "/Home/Details/" + data.id;
},
error: function (jqXHR, textStatus, errorThrown) {
$("#postResult").val(jqXHR.statusText);
}
});
</script>
Another Way Using C# Viewbag:
<table class="table table-bordered">
<thead>
<tr>
<th>Property Header</th>
<th>Property Header</th>
<th>Property Header</th>
</tr>
</thead>
<tbody>
#foreach (var item in ViewBag.ViewBagName)
{
<tr>
<td>#item.PropertyName</td>
<td>#item.PropertyName</td>
<td>#item.PropertyName</td>
</tr>
}
</tbody>
</table>
Let me know if you have any additional question.
Hope that would help.
If you need to show value in one column alone then use this type
#*#{Customer.Models.Customers cust = ViewBag.Customers;
}*#
#{
}
<center><h1 style="color:red">User details</h1></center>
<div>
<table class="table">
<tr>
<td>ID</td>
<td id="Id"></td>
</tr>
<tr>
<td>FIRST NAME</td>
<td id="Fname"></td>
</tr>
<tr>
<td>LAST NAME</td>
<td id="Lname"></td>
</tr>
<tr>
<td>LOCATION</td>
<td id="Location"></td>
</tr>
<tr>
<td>Contact</td>
<td id="Contact"></td>
</tr>
<tr>
<td>Email</td>
<td id="Email"></td>
</tr>
<tr>
<td>Password</td>
<td id="Password"></td>
</tr>
<tr>
<td>Role</td>
<td id="Category"></td>
</tr>
<tr>
</table>
</div>
#section Scripts{
<script>
$.ajax({
contentType: "application/json",
type: "GET",
url: "https://localhost:44397/api/Values/Details/" + id,
success: function (data) {
alert('Welcome!');
res = data;
document.getElementById("Id").innerHTML = res.Id;
document.getElementById("Fname").innerHTML= res.Fname;
document.getElementById("Lname").innerHTML= res.Lname;
document.getElementById("Location").innerHTML= res.Location;
document.getElementById("Contact").innerHTML= res.Contact;
document.getElementById("Email").innerHTML= res.Email;
document.getElementById("Password").innerHTML= res.Password;
document.getElementById("Category").innerHTML= res.Category;
// window.location.href = "/Home/Details/" + data.id;
},
error: function (jqXHR, textStatus, errorThrown) {
$("#postResult").val(jqXHR.statusText);
}
});
</script>
}
I think it will help you :)
You could use Partial view to contain the table data and return PartialViewResult from the api controller ,then show the partial view from the success function of ajax . The following is the steps:
_DetailsPartial
#model DemoTest.Models.User
<center><h1 style="color:red">User details</h1></center>
<div>
<table class="table">
<tr>
<td>ID</td>
<td>#Model.Id</td>
</tr>
<tr>
<td>FIRST NAME</td>
<td>#Model.Fname</td>
</tr>
<tr>
<td>LAST NAME</td>
<td>#Model.Lname</td>
</tr>
<tr>
<td>LOCATION</td>
<td>#Model.Location</td>
</tr>
<tr>
<td>Contact</td>
<td>#Model.Contact</td>
</tr>
<tr>
<td>Email</td>
<td>#Model.Email</td>
</tr>
<tr>
<td>Password</td>
<td>#Model.Password</td>
</tr>
<tr>
<td>Role</td>
<td>#Model.Category</td>
</tr>
<tr>
</table>
</div>
Api controller ,return PartialViewResult
[Route("api/[controller]/[action]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly DemoDbContext _context;
public ValuesController(DemoDbContext context)
{
_context = context;
}
[HttpGet("{id}")]
public async Task<IActionResult> Details(int id)
{
var user = await _context.User.FindAsync(id);
var myViewData = new ViewDataDictionary(new Microsoft.AspNetCore.Mvc.ModelBinding.EmptyModelMetadataProvider(), new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary())
{ { "User", user } };
myViewData.Model = user;
return new PartialViewResult()
{
ViewName= "_DetailsPartial",
ViewData= myViewData
};
}
}
The main view that contains the partial view, use ajax to show the result of success function in the <div id="userdetail"></div>
<div id="userdetail"></div>
#section Scripts{
<script>
var id = 1;
$.ajax({
//contentType: "application/json",
type: "GET",
url: "https://localhost:44343/api/Values/Details/" + id,
success: function (data) {
alert('Welcome!');
$("#userdetail").html(data);
// window.location.href = "/Home/Details/" + data.id;
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Failed!');
}
});
</script>
}
Result:
For more details about Partial View , you could refer to the official doc.

Why when referring to the second field, the value is taken from the first?

I recently work with jquery. And I have such a question. I add elements to the page via forEach and I need to access the field of a specific product in jquery.
My JQuery:
jQuery(document).ready(function() {
$('.count').on('blur', function getTotalPrice(){
var name = $('#name').html();
var count = $('.count').val();
$.ajax({
type: "GET",
url: "cart",
data: "name=" + name + "&count=" + count,
success: function(data){
$("#totalPrice").text("Total price: " + data['totalPrice'].toFixed(2)).wrap("<h4></h4>");
$("#productCount").text("(" + data['productCount'] + ")");
$.each([data['cartItems']], function(key, value) {
});
},
dataType: "json"
});
});
});
My Page:
<table>
<tr>
<th>Item</th>
<th>Name</th>
<th>Category</th>
<th>Company Manufacturer</th>
<th>QTY</th>
<th>Prices</th>
<th>Total Prices</th>
</tr>
<c:forEach items="${cartItems}" var="items">
<tr>
<td><a href="images/product/${items.key.imageName}"><img src="images/product/${items.key.imageName}" width=100></td>
<td><span id="name">${items.key.name}</span></td>
<td>${items.key.category.name}</td>
<td>${items.key.manufacturer.name}</td>
<td><input type="text" class="count" value="${items.value}"></td>
<td>${items.key.price}</td>
<td><span id="totalPriceForOne">${items.key.price * items.value}</span></td>
<td>Remove item</td>
</tr>
</c:forEach>
</table>
</div>
<div align="right" style="color: #0087ff">
<span id="totalPrice"><h4>Total price: ${totalPrice}</h4></span>
</div>
<div align="right">Make order</div>
My Page when i fill it:
<table>
<tr>
<th>Item</th>
<th>Name</th>
<th>Category</th>
<th>Company Manufacturer</th>
<th>QTY</th>
<th>Prices</th>
<th>Total Prices</th>
</tr>
<tr>
<td><a href="images/product/3.png"><img src="images/product/3.png" width=100></td>
<td><span class="name">ALLIANCE_SUNGLASSES</span></td>
<td>accessories</td>
<td>Luis Vuitton</td>
<td><input type="text" class="count" value="1"></td> //сюда обращается
<td>810.00</td>
<td><span id="totalPriceForOne">810.00</span></td>
<td>Remove item</td>
</tr>
<tr>
<td><a href="images/product/2.png"><img src="images/product/2.png" width=100></td>
<td><span class="name">45DAVID</span></td>
<td>jeans</td>
<td>Collins</td>
<td><input type="text" class="count" value="12"></td> //сюда обратиться не выходит
<td>100.00</td>
<td><span id="totalPriceForOne">1200.00</span></td>
<td>Remove item</td>
</tr>
</table>
So I have a problem, I want that when I change the values ​​of the count field, they change for that product opposite which this field is located. Now when I try to change the count in the second product, it refers to the field of the first product, and the values ​​do not change. If I turn to the first field, then everything is fine there, I indicate the quantity of goods I need, and it recounts the price for me. But why do I fail when I try to do this for the second product? How to fix it?
You need to change this line; var count = $('.count').val(); to var count = $(this).val();
Since there seems to be many instances of .count, you have to refer to the currently selected element with $(this).
For the name, it's a bit tricky, you have to find the nearest .name. Since the .count is inside a td, you have to use .parent() to navigate to the td. Once you're in the td, you have to use .parent() again to navigate to the tr. Once in the tr, you need to use .find(".name") to find the child with class name.
jQuery(document).ready(function() {
$('.count').on('blur', function getTotalPrice(){
// updated
var name = $(this).parent().parent().find('.name').html();
// updated
var count = $(this).val();
$.ajax({
type: "GET",
url: "cart",
data: "name=" + name + "&count=" + count,
success: function(data){
$("#totalPrice").text("Total price: " + data['totalPrice'].toFixed(2)).wrap("<h4></h4>");
$("#productCount").text("(" + data['productCount'] + ")");
$.each([data['cartItems']], function(key, value) {
});
},
dataType: "json"
});
});
});

Tablesorter with ajax refresh not working with more than one

I'm using jQueryUI tabs that has a table on each page. The tables are sorted by Tablesorter 2.0.
The following code works great when I have a single table undergoing a refresh on a page. If I add a second table w/ a refresh, only the first one updates. Can someone tell me how I can get two tables to be sorted by tablesorter with ajax refreshes of the data?
The reload is run through this JS function:
$(function () {
$(".tsRefresh").tablesorter({
headers: {
'.cbsort': { sorter: 'checkbox' },
'.nosort': { sorter: false, parser: false }
},
theme : 'jui',
headerTemplate : '{content} {icon}',
widgets : ['saveSort', 'uitheme'],
widgetOptions : {
zebra : ["odd", "even"]
}
});
function getBjson() {
var Tid = $('.tsRefresh').data('id');
var Ttable = $('.tsRefresh').data('table');
var Tbody = $('.tsRefresh').find('tbody').attr('id')
$.ajax({
type: "POST",
url: "ajax.php",
data: 'table=' + Ttable +'&id=' + Tid,
success: function(output) {
document.getElementById(Tbody).innerHTML = output;
// update tablesorter cache
$(".tsRefresh").trigger("update");
},
error: function (xhr, ajaxOptions, thrownError) {
$('#messageResponse').fadeIn(500);
$('#messageResponse').addClass('ui-state-error ui-corner-all').removeClass('ui-highlight-error');
$('#messageResponse').text(xhr.status + ' ' + thrownError + ': Something went wrong - check your inputs and try again.');
}
});
}
if( $('.tsRefresh').length) {
var Ttime = $('.tsRefresh').data('time');
var timer = setInterval(getBjson, Ttime);
getBjson();
}
});
The following is the table code:
<div id="tabs-1">
<fieldset>
<table width="100%" id="issue" name="issue" class="tsRefresh" data-id="<?=$item_id?>" data-table="eq-load" data-time="10000">
<thead>
<tr class="bold">
<th class="cbsort"><input type="checkbox" class="checkall"> </th>
<th>OAN/ID</th>
<th>Category</th>
<th>Desc</th>
<th>Issued To</th>
<th>SN</th>
</tr>
</thead>
<tbody id="container1">
</tbody>
</table>
</fieldset>
</div>
<div id="tabs-2">
<fieldset>
<table width="100%" id="my-load" name="my-load" class="tsRefresh" data-id="<?=$item_id?>" data-table="eq-load-me" data-time="10000">
<thead>
<tr class="bold">
<th class="cbsort"><input type="checkbox" class="checkall"> </th>
<th>OAN/ID</th>
<th>Category</th>
<th>Desc</th>
<th>Issued To</th>
<th>SN</th>
</tr>
</thead>
<tbody id="container2">
</tbody>
</table>
</fieldset>
</div>
My PHP script (ajax.php) outputs the following to the tablesorter's table:
<tr class="dialog-hover" data-table="eq-load-item" data-id="<?=$item_id?>">
<td align="center"><input type="checkbox" id="row-<?=$item_id?>" value="<?=$item_id?>"></td>
<td align="center" valign="top"><?=$item_oan?>-<?=$item_id?></td>
<td><?=$item_cat?></td>
<td align="center" valign="top"><?=$item_desc?></td>
<td align="center" valign="top"><?=$issue_name?></td>
<td align="center" valign="top"><?=$item_serial?></td>
</tr>

Updating table rows in datatables with jquery

How can I use jQuery ajax to handle checked checkboxes? How do I then send each checked checkbox in the html table, to ajax.php?
This is what I've tried so far:
ajax.php
session_start();
if (isset($_POST['id']) && isset($_POST['to']) && isset($_SESSION['user']['id'])) {
if (is_numeric($_POST['id']) && is_numeric($_POST['to'])) {
include("mysql_connector.php");
$user = $_SESSION['user']['id'];
$sendTo = mysql_real_escape_string(trim($_POST['to']));
foreach ($_POST['id'] as $id) {
$id = mysql_real_escape_string(trim($id));
mysql_query("UPDATE `email` SET status = '$sendTo' WHERE `email_id` = '$id' AND `userid` = '$user'");
}
}
}
Javascript:
$(".submit").click(function() {
var id = $("#id").val();
var to = $("#bins").val();
var dataString = 'id=' + id + '&to=' + to;
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
});
});
html:
<form method="POST">
<table id="inventory" class="table">
<thead>
<tr>
<th style="text-align: center;">Check All</th>
<th>Time Received</th>
<th>Email</th>
<th>Subject</th>
<th>ID</th>
</tr>
</thead>
<tbody>
<tr class="email">
<td style="text-align: center;"><input type="checkbox" name='msg[]' class="id" value="2" /></td>
<td>1231231</td>
<td>test</td>
<td>test</td>
<td>0</td>
</tr>
<tr class="email">
<td style="text-align: center;"><input type="checkbox" name='msg[]' class="id" value="3" /></td>
<td>1231231</td>
<td>test</td>
<td>test</td>
<td>1</td>
</tr>
</tbody>
</table>
</br>
<select name="bins" class="bins">
<option value="1">Archive</option>
<option value="2">Read</option>
<option value="3">Unread</option>
<option value="4">Save</option>
</select>
<input type="submit" name="move" value="Move" class="submit" style="width:auto;"/>
</form>
Thank you for reading.
First, it is invalid to have multiple dom elements with duplicate ids. If those checkboxes need ids, make them unique. If they don't need ids, then just drop them completely.
To get a list of the values of all checked checkboxes, do:
var checkedVals = [];
$("input[type='checkbox']:checked").each(function() {
checkedVals.push($(this).val());
});
Or you can fetch different groups of checkboxes by name:
var checkedMsgVals = [];
$("input[name='msg[]']:checked").each(function() {
checkedMsgVals.push($(this).val());
});
To send these to php, just include them in your data packet when you make the call. To do this you'll want to send an object over, not a querystring.
var dataObj = {'id': id, 'to': to, 'checkedValues': checkedMsgVals };
$.ajax({
type: "POST",
url: "ajax.php",
data: dataObj,
});

Categories

Resources